├── pidpy ├── tests │ ├── __init__.py │ ├── check_significance.py │ └── test_PIDCalculator.py ├── __init__.py ├── setupcython.py ├── utilsc.pyx ├── utils.py └── PIDCalculator.py ├── docs ├── source │ ├── api.rst │ └── conf.py └── Makefile ├── .gitignore ├── setup.py ├── README.md └── LICENSE /pidpy/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /pidpy/__init__.py: -------------------------------------------------------------------------------- 1 | from pidpy.PIDCalculator import PIDCalculator 2 | -------------------------------------------------------------------------------- /pidpy/setupcython.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | from Cython.Build import cythonize 3 | import numpy as np 4 | 5 | setup( 6 | ext_modules = cythonize("pidpy/utilsc.pyx"), 7 | include_dirs=[np.get_include()] 8 | ) 9 | -------------------------------------------------------------------------------- /pidpy/tests/check_significance.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from pidpy import PIDCalculator 3 | 4 | X = np.random.randint(2,size=[30,3]) 5 | y = np.random.randint(10,size=[30,]) 6 | 7 | pid = PIDCalculator(X, y) 8 | 9 | pid.decomposition(debiased=True, return_std_surrogates=True, test_significance=True) 10 | 11 | 12 | dec,pv = pid.decomposition(debiased=True, return_individual_unique=False, test_significance=True) -------------------------------------------------------------------------------- /docs/source/api.rst: -------------------------------------------------------------------------------- 1 | **************** 2 | Module Reference 3 | **************** 4 | 5 | :mod:`pidpy` -- Partial Information Decomposition in Python. 6 | ============================================================ 7 | 8 | 9 | .. automodule:: pidpy.PIDCalculator 10 | 11 | 12 | :class:`PIDCalculator` 13 | ------------------------------------- 14 | 15 | .. autoclass:: pidpy.PIDCalculator.PIDCalculator 16 | :members: 17 | 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Setuptools distribution folder. 2 | /dist/ 3 | 4 | # Python egg metadata, regenerated from source files by setuptools. 5 | /*.egg-info 6 | 7 | # My files # 8 | ############ 9 | docs/build/ 10 | profiling/ 11 | pidpy/PIDER.py 12 | pidpy/parallel_prova.py 13 | pidpy/*.html 14 | pidpy/generators.py 15 | pidpy/try_PIDCalculator.py 16 | pidpy/PIDCalculatorPP.py 17 | pidpy/tests/spec_info_tests.py 18 | pidpy/setting_attributes.py 19 | pidpy/tests/check_significance.py 20 | profiling/* 21 | 22 | *.png 23 | *.eps 24 | 25 | # Compiled source # 26 | ################### 27 | *.com 28 | *.class 29 | *.dll 30 | *.exe 31 | *.o 32 | *.so 33 | *.pyc 34 | 35 | # Packages # 36 | ############ 37 | # it's better to unpack these files and commit the raw source 38 | # git has its own built in compression methods 39 | *.7z 40 | *.dmg 41 | *.gz 42 | *.iso 43 | *.jar 44 | *.rar 45 | *.tar 46 | *.zip 47 | 48 | # Logs and databases # 49 | ###################### 50 | *.log 51 | *.sql 52 | *.sqlite 53 | 54 | # OS generated files # 55 | ###################### 56 | .DS_Store 57 | .DS_Store? 58 | ._* 59 | .Spotlight-V100 60 | .Trashes 61 | ehthumbs.db 62 | Thumbs.db 63 | 64 | # Other files # 65 | *.xml 66 | *.iml 67 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | 2 | try: 3 | from setuptools import setup 4 | except ImportError: 5 | from distutils.core import setup 6 | 7 | import numpy as np 8 | from distutils.extension import Extension 9 | 10 | 11 | def readme(): 12 | with open('README.md') as f: 13 | return f.read() 14 | 15 | 16 | setup(name='pidpy', 17 | version='0.1', 18 | description='Partial Information Decomposition in Python', 19 | long_description=readme(), 20 | classifiers=[ 21 | 'Development Status :: 3 - Alpha', 22 | 'License :: OSI Approved :: BSD License', 23 | 'Programming Language :: Python :: 2.7', 24 | 'Topic :: Information Theory', 25 | ], 26 | keywords='partial information decomposition synergy ' 27 | 'redundancy unique', 28 | #url='http://github.com/', 29 | author='Pietro Marchesi', 30 | author_email='pietromarchesi92@gmail.com', 31 | license='new BSD', 32 | packages=['pidpy'], 33 | install_requires=[ 34 | 'numpy', 35 | 'joblib', 36 | 'pymorton' 37 | ], 38 | include_package_data=True, 39 | zip_safe=False, 40 | test_suite = 'nose.collector', 41 | tests_require = ['nose'], 42 | ext_modules=[Extension('pidpy.utilsc', ['pidpy/utilsc.c'])], 43 | include_dirs=[np.get_include()] 44 | ) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | pidpy 2 | ===== 3 | 4 | pidpy is a Python package for partial information decomposition. 5 | Specifically, it can be used to compute the pure terms of the decomposition 6 | for an arbitrary number of source variables using the original proposal 7 | of Williams & Beer [1]. 8 | 9 | 10 | 11 | Installation 12 | ------------ 13 | After cloning or downloading the repository, do 14 | 15 | ``` 16 | cd pidpy 17 | ``` 18 | 19 | Then you can install normally with 20 | 21 | ``` 22 | $ python setup.py install 23 | ``` 24 | 25 | or 26 | 27 | ``` 28 | $ pip install . 29 | ``` 30 | 31 | However, it is recommended to install with the _develop_ option, with 32 | 33 | ``` 34 | $ python setup.py develop 35 | ``` 36 | 37 | or 38 | 39 | ``` 40 | $ pip install -e . 41 | ``` 42 | 43 | 44 | Tests 45 | ----- 46 | From the root directory, execute `nosetests`. 47 | 48 | Quickstart 49 | ----------- 50 | pidpy supports any number of feature variables with binary values 51 | (taking on either `0` or `1`). For variables taking on integer non-binary 52 | variables, support is limited to triplets. 53 | 54 | In general, a good rule of thumb is to make sure that 55 | `n_variables < log2(n_samples / (3*n_labels))`. 56 | 57 | The main class `PIDCalculator` can be instantiated with a feature array `X` of 58 | shape `(n_samples, n_variables)` and an array of labels `y` of shape `(n_samples,)`. 59 | 60 | ```python 61 | from pidpy import PIDCalculator 62 | pid = PIDCalculator(X,y) 63 | ``` 64 | 65 | Then the pure synergy, redundancy, and unique terms of the information 66 | decomposition can be computed, together with the full mutual information (values 67 | given in bits). 68 | 69 | ```python 70 | pid.synergy() 71 | pid.redundancy() 72 | pid.unique() 73 | pid.mutual() 74 | ```` 75 | 76 | The information values can also be debiased with shuffled surrogates, where 77 | the parameter `n` specifies the number of surrogates to be used. 78 | 79 | ```python 80 | pid.synergy(debiased = True, n = 50) 81 | pid.redundancy(debiased = True, n = 50) 82 | pid.unique(debiased = True, n = 50 83 | pid.mutual(debiased = True, n = 50) 84 | ``` 85 | These methods return a tuple containing the original value debiased by 86 | subtracting from it the mean of the surrogates, and the standard deviation 87 | of the surrogates. 88 | 89 | Lastly, the `decomposition` method can be used as a shortcut to get a full 90 | picture of the partial information decomposition. 91 | 92 | ```python 93 | synergy, redundancy, unique, mutual = pid.decomposition() 94 | ```` 95 | For more detailed information, see the documentation. To obtain a p-value 96 | for every information theoretic quantity (computed as the fraction of 97 | surrogates for which the information theoretic quantity is higher 98 | than the observed one), you can do: 99 | 100 | ```python 101 | decomposition, p_values = pid.decomposition(debiased = True, n = 50, 102 | return_std_surrogates = False, 103 | test_significance = True) 104 | ```` 105 | In this case, an additional tuple is returned containing a p-value 106 | for every term. 107 | 108 | Building the documentation 109 | ----------- 110 | To build the docs, you need to have Sphinx installed, together with the 111 | `numpydoc` Sphinx extension (`pip install numpydoc`). 112 | To build the documentation in html format: 113 | 114 | ``` 115 | cd docs 116 | make html 117 | ``` 118 | 119 | Or 120 | 121 | ``` 122 | sphinx-build -b html ./source ./build/html 123 | ``` 124 | 125 | Then in `build/html` you can open `api.html` to begin reading 126 | the documentation. 127 | 128 | [1] Williams, P. L., & Beer, R. D. (2010). 129 | Nonnegative decomposition of multivariate information. 130 | arXiv preprint arXiv:1004.2515. -------------------------------------------------------------------------------- /pidpy/utilsc.pyx: -------------------------------------------------------------------------------- 1 | #cython: profile=True 2 | import numpy as np 3 | cimport cython 4 | cimport numpy as np 5 | from libc.math cimport log2, fabs 6 | 7 | 8 | @cython.boundscheck(False) 9 | @cython.wraparound(False) 10 | @cython.cdivision(True) 11 | def _compute_joint_probability_nonbin(np.ndarray[np.int64_t, ndim=1] X, 12 | np.ndarray[np.int64_t, ndim=1] y): 13 | ''' 14 | The joint probability table is built only with values which actually 15 | appear in X. 16 | ''' 17 | cdef int nsamp = y.shape[0] 18 | cdef int nlabels = len(list(set(y))) 19 | cdef np.ndarray[np.int64_t, ndim=1] vals 20 | vals = np.array(sorted(list(set(X)))) 21 | nvals = vals.shape[0] 22 | cdef np.ndarray[np.int64_t, ndim=2] joint 23 | joint = np.zeros([nvals, nlabels], dtype = np.int64) 24 | 25 | for i in xrange(nsamp): 26 | for j in range(nvals): 27 | if X[i] == vals[j]: 28 | ind = j 29 | joint[ind, y[i]] += 1 30 | 31 | return joint / np.float(nsamp) 32 | 33 | 34 | @cython.boundscheck(False) 35 | @cython.wraparound(False) 36 | @cython.cdivision(True) 37 | def _compute_joint_probability_bin(np.ndarray[np.int64_t, ndim=1] X, 38 | np.ndarray[np.int64_t, ndim=1] y, 39 | int nvals): 40 | ''' 41 | The joint probability table is set up with all possible values 42 | of X (faster, but requires construction of arrays which are too big 43 | if X is not binary). 44 | ''' 45 | cdef int nsamp = y.shape[0] 46 | cdef int nlabels = len(list(set(y))) 47 | cdef np.ndarray[np.int64_t, ndim=2] joint 48 | joint = np.zeros([nvals, nlabels], dtype = np.int64) 49 | 50 | for i in xrange(nsamp): 51 | joint[X[i], y[i]] += 1 52 | 53 | return joint / np.float(nsamp) 54 | 55 | 56 | 57 | @cython.boundscheck(False) 58 | @cython.wraparound(False) 59 | def _compute_mutual_info(np.ndarray[np.float64_t, ndim=1] X_mar_, 60 | np.ndarray[np.float64_t, ndim=1] y_mar_, 61 | np.ndarray[np.float64_t, ndim=2] joint): 62 | cdef double I = 0 63 | cdef int xlen = X_mar_.shape[0] 64 | cdef int ylen = y_mar_.shape[0] 65 | 66 | for i in xrange(xlen): 67 | for j in xrange(ylen): 68 | if fabs(joint[i,j]) > 10**(-8): 69 | I += joint[i,j] * log2(joint[i,j] / (X_mar_[i]*y_mar_[j])) 70 | return I 71 | 72 | 73 | from cython.parallel import prange 74 | from cython.view cimport array as cvarray 75 | from cpython cimport array as c_array 76 | from array import array 77 | 78 | @cython.boundscheck(False) 79 | @cython.wraparound(False) 80 | def _map_binary_array_par(long[:,:] X): 81 | 82 | cdef int N = X.shape[0] 83 | cdef int n = X.shape[1] 84 | cyarr = cvarray(shape=(N,), itemsize=sizeof(int), format="i") 85 | cdef int[:] Xmap = cyarr 86 | 87 | cdef int[:] Xmapout 88 | Xmapout = _map_binary_array_par_inner(X, Xmap, N, n) 89 | 90 | return np.array(Xmapout,dtype = 'int64') 91 | 92 | 93 | 94 | @cython.boundscheck(False) 95 | @cython.wraparound(False) 96 | cdef int[:] _map_binary_array_par_inner(long[:,:] X, int[:] Xmap, int N, int n): 97 | cdef int i 98 | for i in prange(N, schedule=dynamic, nogil=True): 99 | Xmap[i] = _map_binary_par(X[i,:], n) 100 | return Xmap 101 | 102 | 103 | @cython.boundscheck(False) 104 | @cython.wraparound(False) 105 | cdef int _map_binary_par(long[:] x, int n) nogil: 106 | 107 | cdef int tot = 0 108 | cdef int i 109 | 110 | cdef int p = 1 111 | for i in range(n): 112 | if x[i]: 113 | tot += p 114 | p = p << 1 115 | return tot 116 | 117 | 118 | @cython.boundscheck(False) 119 | @cython.wraparound(False) 120 | @cython.cdivision(True) 121 | def _compute_specific_info(int label, np.float64_t[:] y_mar_, 122 | np.float64_t[:,:] cond_Xy, 123 | np.float64_t[:,:] cond_yX, 124 | np.float64_t[:,:] joint): 125 | 126 | cdef double Ispec = 0 127 | cdef int n = cond_Xy.shape[0] 128 | cdef double mar = y_mar_[label] 129 | cdef double c 130 | cdef double contrib 131 | 132 | for x in range(n): 133 | if mar > 1e-8: 134 | c = cond_yX[x, label] 135 | if c > 1e-8: 136 | contrib = cond_Xy[x, label] * (log2(1.0 / mar) 137 | - log2(1.0 / c)) 138 | Ispec += contrib 139 | return Ispec 140 | 141 | 142 | 143 | #--------------------------------------------------------------------- 144 | # The functions below are not in use, kept for profiling comparison. 145 | 146 | @cython.boundscheck(False) 147 | @cython.wraparound(False) 148 | def _map_binary(np.ndarray[np.int64_t, ndim=1] x): 149 | 150 | cdef int tot = 0 151 | cdef int i 152 | cdef int n = x.shape[0] 153 | 154 | for i in range(n): 155 | if x[i]: 156 | tot += 1< 0: 70 | # print('Computing %s' %fn.__name__) 71 | setattr(self, attr_name, fn(self)) 72 | return getattr(self, attr_name) 73 | 74 | return _lazyprop 75 | 76 | 77 | def _group_without_unit(group, unit): 78 | ''' 79 | Returns the tuple given by `group without the element give by `uni`. 80 | ''' 81 | if isinstance(unit, int): 82 | unit = [unit] 83 | return tuple(k for k in group if not k in unit) 84 | 85 | 86 | def _get_surrogate_val(surrogate, fun, **kwargs): 87 | return getattr(surrogate, fun)(**kwargs) 88 | 89 | 90 | def _isbinary(X): 91 | return set(X.flatten()) == {0,1} 92 | 93 | 94 | def _joint_probability(X, y, binary = True): 95 | if X.ndim > 1: 96 | Xmap = _map_array(X, binary = binary) 97 | N = X.shape[1] 98 | else: 99 | Xmap = X 100 | N = 1 101 | 102 | if binary and N < 12: 103 | nvals = 2 ** N 104 | joint = _compute_joint_probability_bin(Xmap,y,nvals) 105 | else: 106 | joint = _compute_joint_probability_nonbin(Xmap, y) 107 | 108 | return joint 109 | 110 | 111 | def _joint_var(X, y, binary = True): 112 | joints = [] 113 | for i in range(X.shape[1]): 114 | joints.append(_joint_probability(X[:, i], y, binary = binary)) 115 | return joints 116 | 117 | 118 | def _joint_sub(X, y, binary = True): 119 | joints = [] 120 | for i in range(X.shape[1]): 121 | group = _group_without_unit(range(X.shape[1]), i) 122 | joints.append(_joint_probability(X[:, group], y, binary = binary)) 123 | return joints 124 | 125 | 126 | def _Imin(y_mar_, spec_info): 127 | Im = 0 128 | for i in range(len(y_mar_)): 129 | Im += y_mar_[i]*np.min(spec_info[i]) 130 | return Im 131 | 132 | 133 | def _Imax(y_mar_, spec_info): 134 | Im = 0 135 | for i in range(len(y_mar_)): 136 | Im += y_mar_[i]*np.max(spec_info[i]) 137 | return Im 138 | 139 | 140 | def _conditional_probability_from_joint(joint): 141 | X_mar = joint.sum(axis = 1) 142 | y_mar = joint.sum(axis = 0) 143 | 144 | cond_Xy = joint.astype(float) / y_mar[np.newaxis, :] 145 | cond_yX = joint.astype(float) / X_mar[:, np.newaxis] 146 | return cond_Xy, cond_yX 147 | 148 | 149 | #------------------------------------------------------------- 150 | # The functions below are not currently in use. 151 | 152 | def map_binary(x): 153 | ''' 154 | Map vector of binary digits to the corresponding integer in the binary system. 155 | ''' 156 | return sum(1 << i for i, b in enumerate(np.flipud(x)) if b) 157 | 158 | 159 | def _map_binary_array(X, binary = True): 160 | ''' 161 | Maps binary array. Old version in which mapping of the single 162 | rows of `X` is performed by the Cython function _map_binary 163 | ''' 164 | mapped = np.zeros(X.shape[0],dtype=int) 165 | for i in range(X.shape[0]): 166 | mapped[i] = _map_binary(X[i,:]) 167 | return mapped 168 | 169 | 170 | def _map_binary_array_original(X, binary = True): 171 | ''' 172 | Old function, used only for profiling purposes. 173 | ''' 174 | mapped = np.zeros(X.shape[0],dtype=int) 175 | for i in range(X.shape[0]): 176 | mapped[i] = map_binary(X[i,:]) 177 | 178 | return mapped 179 | 180 | 181 | def cantor_pairing_function(k1, k2, safe=True): 182 | ''' 183 | Cantor pairing function 184 | http://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function 185 | ''' 186 | z = int(0.5 * (k1 + k2) * (k1 + k2 + 1) + k2) 187 | if safe and (k1, k2) != depair(z): 188 | raise ValueError("{} and {} cannot be paired".format(k1, k2)) 189 | return z 190 | 191 | 192 | def depair(z): 193 | ''' 194 | Inverse of Cantor pairing function 195 | http://en.wikipedia.org/wiki/Pairing_function#Inverting_the_Cantor_pairing_function 196 | ''' 197 | w = math.floor((math.sqrt(8 * z + 1) - 1) / 2) 198 | t = (w ** 2 + w) / 2 199 | y = int(z - t) 200 | x = int(w - y) 201 | # assert z != pair(x, y, safe=False): 202 | return x, y 203 | 204 | 205 | def map_nonbinary(x): 206 | x = np.array(x) 207 | for i in range(len(x) - 1): 208 | # tup[i+1] = tup[i] * tup[i+1] 209 | x[i + 1] = cantor_pairing_function(x[i], x[i + 1]) 210 | return x[i + 1] 211 | 212 | 213 | def feature_values(X): 214 | # figure out whether X is binary or not, returning the 215 | # discrete feature values. 216 | nvals = len(set(X.reshape([X.shape[0] * X.shape[1], ]))) 217 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 21 | 22 | .PHONY: help 23 | help: 24 | @echo "Please use \`make ' where is one of" 25 | @echo " html to make standalone HTML files" 26 | @echo " dirhtml to make HTML files named index.html in directories" 27 | @echo " singlehtml to make a single large HTML file" 28 | @echo " pickle to make pickle files" 29 | @echo " json to make JSON files" 30 | @echo " htmlhelp to make HTML files and a HTML help project" 31 | @echo " qthelp to make HTML files and a qthelp project" 32 | @echo " applehelp to make an Apple Help Book" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | @echo " coverage to run coverage check of the documentation (if enabled)" 49 | 50 | .PHONY: clean 51 | clean: 52 | rm -rf $(BUILDDIR)/* 53 | 54 | .PHONY: html 55 | html: 56 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 57 | @echo 58 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 59 | 60 | .PHONY: dirhtml 61 | dirhtml: 62 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 63 | @echo 64 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 65 | 66 | .PHONY: singlehtml 67 | singlehtml: 68 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 69 | @echo 70 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 71 | 72 | .PHONY: pickle 73 | pickle: 74 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 75 | @echo 76 | @echo "Build finished; now you can process the pickle files." 77 | 78 | .PHONY: json 79 | json: 80 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 81 | @echo 82 | @echo "Build finished; now you can process the JSON files." 83 | 84 | .PHONY: htmlhelp 85 | htmlhelp: 86 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 87 | @echo 88 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 89 | ".hhp project file in $(BUILDDIR)/htmlhelp." 90 | 91 | .PHONY: qthelp 92 | qthelp: 93 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 94 | @echo 95 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 96 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 97 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pidpy.qhcp" 98 | @echo "To view the help file:" 99 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pidpy.qhc" 100 | 101 | .PHONY: applehelp 102 | applehelp: 103 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 104 | @echo 105 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 106 | @echo "N.B. You won't be able to view it unless you put it in" \ 107 | "~/Library/Documentation/Help or install it in your application" \ 108 | "bundle." 109 | 110 | .PHONY: devhelp 111 | devhelp: 112 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 113 | @echo 114 | @echo "Build finished." 115 | @echo "To view the help file:" 116 | @echo "# mkdir -p $$HOME/.local/share/devhelp/pidpy" 117 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pidpy" 118 | @echo "# devhelp" 119 | 120 | .PHONY: epub 121 | epub: 122 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 123 | @echo 124 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 125 | 126 | .PHONY: latex 127 | latex: 128 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 129 | @echo 130 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 131 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 132 | "(use \`make latexpdf' here to do that automatically)." 133 | 134 | .PHONY: latexpdf 135 | latexpdf: 136 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 137 | @echo "Running LaTeX files through pdflatex..." 138 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 139 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 140 | 141 | .PHONY: latexpdfja 142 | latexpdfja: 143 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 144 | @echo "Running LaTeX files through platex and dvipdfmx..." 145 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 146 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 147 | 148 | .PHONY: text 149 | text: 150 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 151 | @echo 152 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 153 | 154 | .PHONY: man 155 | man: 156 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 157 | @echo 158 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 159 | 160 | .PHONY: texinfo 161 | texinfo: 162 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 163 | @echo 164 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 165 | @echo "Run \`make' in that directory to run these through makeinfo" \ 166 | "(use \`make info' here to do that automatically)." 167 | 168 | .PHONY: info 169 | info: 170 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 171 | @echo "Running Texinfo files through makeinfo..." 172 | make -C $(BUILDDIR)/texinfo info 173 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 174 | 175 | .PHONY: gettext 176 | gettext: 177 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 178 | @echo 179 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 180 | 181 | .PHONY: changes 182 | changes: 183 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 184 | @echo 185 | @echo "The overview file is in $(BUILDDIR)/changes." 186 | 187 | .PHONY: linkcheck 188 | linkcheck: 189 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 190 | @echo 191 | @echo "Link check complete; look for any errors in the above output " \ 192 | "or in $(BUILDDIR)/linkcheck/output.txt." 193 | 194 | .PHONY: doctest 195 | doctest: 196 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 197 | @echo "Testing of doctests in the sources finished, look at the " \ 198 | "results in $(BUILDDIR)/doctest/output.txt." 199 | 200 | .PHONY: coverage 201 | coverage: 202 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 203 | @echo "Testing of coverage in the sources finished, look at the " \ 204 | "results in $(BUILDDIR)/coverage/python.txt." 205 | 206 | .PHONY: xml 207 | xml: 208 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 209 | @echo 210 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 211 | 212 | .PHONY: pseudoxml 213 | pseudoxml: 214 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 215 | @echo 216 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 217 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # pidpy documentation build configuration file, created by 4 | # sphinx-quickstart on Tue Jan 17 21:06:18 2017. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | 18 | # If extensions (or modules to document with autodoc) are in another directory, 19 | # add these directories to sys.path here. If the directory is relative to the 20 | # documentation root, use os.path.abspath to make it absolute, like shown here. 21 | #sys.path.insert(0, os.path.abspath('.')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | #needs_sphinx = '1.0' 27 | 28 | # Add any Sphinx extension module names here, as strings. They can be 29 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 30 | # ones. 31 | extensions = [ 32 | 'sphinx.ext.autodoc', 33 | 'sphinx.ext.autosummary', 34 | 'numpydoc', 35 | #'sphinx.ext.napoleon', 36 | 'sphinx.ext.todo', 37 | 'sphinx.ext.mathjax', 38 | 'sphinx.ext.viewcode', 39 | ] 40 | # numpydoc settings 41 | numpydoc_show_class_members = True 42 | 43 | #autoclass_content = "both" 44 | 45 | 46 | # Add any paths that contain templates here, relative to this directory. 47 | templates_path = ['_templates'] 48 | 49 | # The suffix(es) of source filenames. 50 | # You can specify multiple suffix as a list of string: 51 | # source_suffix = ['.rst', '.md'] 52 | source_suffix = '.rst' 53 | 54 | # The encoding of source files. 55 | #source_encoding = 'utf-8-sig' 56 | 57 | # The master toctree document. 58 | master_doc = 'api' 59 | 60 | # General information about the project. 61 | project = u'pidpy' 62 | copyright = u'2017, Pietro Marchesi' 63 | author = u'Pietro Marchesi' 64 | 65 | # The version info for the project you're documenting, acts as replacement for 66 | # |version| and |release|, also used in various other places throughout the 67 | # built documents. 68 | # 69 | # The short X.Y version. 70 | version = u'1.0' 71 | # The full version, including alpha/beta/rc tags. 72 | release = u'1.0' 73 | 74 | # The language for content autogenerated by Sphinx. Refer to documentation 75 | # for a list of supported languages. 76 | # 77 | # This is also used if you do content translation via gettext catalogs. 78 | # Usually you set "language" from the command line for these cases. 79 | language = None 80 | 81 | # There are two options for replacing |today|: either, you set today to some 82 | # non-false value, then it is used: 83 | #today = '' 84 | # Else, today_fmt is used as the format for a strftime call. 85 | #today_fmt = '%B %d, %Y' 86 | 87 | # List of patterns, relative to source directory, that match files and 88 | # directories to ignore when looking for source files. 89 | exclude_patterns = [] 90 | 91 | # The reST default role (used for this markup: `text`) to use for all 92 | # documents. 93 | #default_role = None 94 | 95 | # If true, '()' will be appended to :func: etc. cross-reference text. 96 | #add_function_parentheses = True 97 | 98 | # If true, the current module name will be prepended to all description 99 | # unit titles (such as .. function::). 100 | #add_module_names = True 101 | 102 | # If true, sectionauthor and moduleauthor directives will be shown in the 103 | # output. They are ignored by default. 104 | #show_authors = False 105 | 106 | # The name of the Pygments (syntax highlighting) style to use. 107 | pygments_style = 'sphinx' 108 | 109 | # A list of ignored prefixes for module index sorting. 110 | #modindex_common_prefix = [] 111 | 112 | # If true, keep warnings as "system message" paragraphs in the built documents. 113 | #keep_warnings = False 114 | 115 | # If true, `todo` and `todoList` produce output, else they produce nothing. 116 | todo_include_todos = True 117 | 118 | 119 | # -- Options for HTML output ---------------------------------------------- 120 | 121 | # The theme to use for HTML and HTML Help pages. See the documentation for 122 | # a list of builtin themes. 123 | html_theme = 'nature' 124 | 125 | # Theme options are theme-specific and customize the look and feel of a theme 126 | # further. For a list of options available for each theme, see the 127 | # documentation. 128 | #html_theme_options = {} 129 | 130 | # Add any paths that contain custom themes here, relative to this directory. 131 | #html_theme_path = [] 132 | 133 | # The name for this set of Sphinx documents. If None, it defaults to 134 | # " v documentation". 135 | #html_title = None 136 | 137 | # A shorter title for the navigation bar. Default is the same as html_title. 138 | #html_short_title = None 139 | 140 | # The name of an image file (relative to this directory) to place at the top 141 | # of the sidebar. 142 | #html_logo = None 143 | 144 | # The name of an image file (within the static path) to use as favicon of the 145 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 146 | # pixels large. 147 | #html_favicon = None 148 | 149 | # Add any paths that contain custom static files (such as style sheets) here, 150 | # relative to this directory. They are copied after the builtin static files, 151 | # so a file named "default.css" will overwrite the builtin "default.css". 152 | html_static_path = ['_static'] 153 | 154 | # Add any extra paths that contain custom files (such as robots.txt or 155 | # .htaccess) here, relative to this directory. These files are copied 156 | # directly to the root of the documentation. 157 | #html_extra_path = [] 158 | 159 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 160 | # using the given strftime format. 161 | #html_last_updated_fmt = '%b %d, %Y' 162 | 163 | # If true, SmartyPants will be used to convert quotes and dashes to 164 | # typographically correct entities. 165 | #html_use_smartypants = True 166 | 167 | # Custom sidebar templates, maps document names to template names. 168 | #html_sidebars = {} 169 | 170 | # Additional templates that should be rendered to pages, maps page names to 171 | # template names. 172 | #html_additional_pages = {} 173 | 174 | # If false, no module index is generated. 175 | #html_domain_indices = True 176 | 177 | # If false, no index is generated. 178 | #html_use_index = True 179 | 180 | # If true, the index is split into individual pages for each letter. 181 | #html_split_index = False 182 | 183 | # If true, links to the reST sources are added to the pages. 184 | #html_show_sourcelink = True 185 | 186 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 187 | #html_show_sphinx = True 188 | 189 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 190 | #html_show_copyright = True 191 | 192 | # If true, an OpenSearch description file will be output, and all pages will 193 | # contain a tag referring to it. The value of this option must be the 194 | # base URL from which the finished HTML is served. 195 | #html_use_opensearch = '' 196 | 197 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 198 | #html_file_suffix = None 199 | 200 | # Language to be used for generating the HTML full-text search index. 201 | # Sphinx supports the following languages: 202 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 203 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' 204 | #html_search_language = 'en' 205 | 206 | # A dictionary with options for the search language support, empty by default. 207 | # Now only 'ja' uses this config value 208 | #html_search_options = {'type': 'default'} 209 | 210 | # The name of a javascript file (relative to the configuration directory) that 211 | # implements a search results scorer. If empty, the default will be used. 212 | #html_search_scorer = 'scorer.js' 213 | 214 | # Output file base name for HTML help builder. 215 | htmlhelp_basename = 'pidpydoc' 216 | 217 | # -- Options for LaTeX output --------------------------------------------- 218 | 219 | latex_elements = { 220 | # The paper size ('letterpaper' or 'a4paper'). 221 | #'papersize': 'letterpaper', 222 | 223 | # The font size ('10pt', '11pt' or '12pt'). 224 | #'pointsize': '10pt', 225 | 226 | # Additional stuff for the LaTeX preamble. 227 | #'preamble': '', 228 | 229 | # Latex figure (float) alignment 230 | #'figure_align': 'htbp', 231 | } 232 | 233 | # Grouping the document tree into LaTeX files. List of tuples 234 | # (source start file, target name, title, 235 | # author, documentclass [howto, manual, or own class]). 236 | latex_documents = [ 237 | (master_doc, 'pidpy.tex', u'pidpy Documentation', 238 | u'Pietro Marchesi', 'manual'), 239 | ] 240 | 241 | # The name of an image file (relative to this directory) to place at the top of 242 | # the title page. 243 | #latex_logo = None 244 | 245 | # For "manual" documents, if this is true, then toplevel headings are parts, 246 | # not chapters. 247 | #latex_use_parts = False 248 | 249 | # If true, show page references after internal links. 250 | #latex_show_pagerefs = False 251 | 252 | # If true, show URL addresses after external links. 253 | #latex_show_urls = False 254 | 255 | # Documents to append as an appendix to all manuals. 256 | #latex_appendices = [] 257 | 258 | # If false, no module index is generated. 259 | #latex_domain_indices = True 260 | 261 | 262 | # -- Options for manual page output --------------------------------------- 263 | 264 | # One entry per manual page. List of tuples 265 | # (source start file, name, description, authors, manual section). 266 | man_pages = [ 267 | (master_doc, 'pidpy', u'pidpy Documentation', 268 | [author], 1) 269 | ] 270 | 271 | # If true, show URL addresses after external links. 272 | #man_show_urls = False 273 | 274 | 275 | # -- Options for Texinfo output ------------------------------------------- 276 | 277 | # Grouping the document tree into Texinfo files. List of tuples 278 | # (source start file, target name, title, author, 279 | # dir menu entry, description, category) 280 | texinfo_documents = [ 281 | (master_doc, 'pidpy', u'pidpy Documentation', 282 | author, 'pidpy', 'One line description of project.', 283 | 'Miscellaneous'), 284 | ] 285 | 286 | # Documents to append as an appendix to all manuals. 287 | #texinfo_appendices = [] 288 | 289 | # If false, no module index is generated. 290 | #texinfo_domain_indices = True 291 | 292 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 293 | #texinfo_show_urls = 'footnote' 294 | 295 | # If true, do not generate a @detailmenu in the "Top" node's menu. 296 | #texinfo_no_detailmenu = False 297 | -------------------------------------------------------------------------------- /pidpy/tests/test_PIDCalculator.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import numpy as np 3 | 4 | from pidpy import PIDCalculator 5 | 6 | 7 | def compare_values(X, y, test_syn=None, test_red=None, 8 | test_uni=None, test_mi=None, test_mi_vars=None, 9 | decimal=3): 10 | ''' 11 | Utility function to test pidpy results against examples in the literature. 12 | ''' 13 | 14 | pid = PIDCalculator(X, y) 15 | syn = pid.synergy() 16 | uni = pid.unique() 17 | red = pid.redundancy() 18 | mi = pid.mutual() 19 | 20 | syn_d, syn_std = pid.synergy(debiased=True, n=0) 21 | uni_d, uni_std = pid.unique(debiased=True, n=0) 22 | red_d, red_std = pid.redundancy(debiased=True, n=0) 23 | mi_d, mi_std = pid.mutual(debiased=True, n=0) 24 | 25 | mi_vars = pid.mutual(individual=True) 26 | mi_vars2 = pid.mutual(debiased = True, individual=True, n = 0)[0] 27 | 28 | 29 | dec = pid.decomposition(debiased=False, as_percentage=False, 30 | return_individual_unique=True) 31 | 32 | if test_syn is not None: 33 | np.testing.assert_almost_equal(syn, test_syn, decimal=decimal, 34 | err_msg='Synergy mismatch') 35 | np.testing.assert_almost_equal(dec[0], test_syn, decimal=decimal, 36 | err_msg='Synergy [decomposition] mismatch') 37 | np.testing.assert_almost_equal(syn_d, test_syn, decimal=decimal, 38 | err_msg='Synergy [debiased] mismatch') 39 | if test_red is not None: 40 | np.testing.assert_almost_equal(red, test_red, decimal=decimal, 41 | err_msg='Redundancy mismatch') 42 | np.testing.assert_almost_equal(dec[1], test_red, decimal=decimal, 43 | err_msg='Redundancy [decomposition] mismatch') 44 | np.testing.assert_almost_equal(red_d, test_red, decimal=decimal, 45 | err_msg='Redundancy [debiased] mismatch') 46 | if test_uni is not None: 47 | np.testing.assert_array_almost_equal(uni, test_uni, decimal=decimal, 48 | err_msg='Unique Info mismatch') 49 | np.testing.assert_array_almost_equal(dec[2], test_uni, 50 | decimal=decimal, 51 | err_msg='Unique [decomposition] mismatch') 52 | np.testing.assert_array_almost_equal(uni_d, test_uni, 53 | decimal=decimal, 54 | err_msg='Unique [debiased] mismatch') 55 | if test_mi is not None: 56 | np.testing.assert_almost_equal(mi, test_mi, decimal=decimal, 57 | err_msg='Mutual Info (global) mismatch') 58 | np.testing.assert_array_almost_equal(dec[3], test_mi, 59 | decimal=decimal, 60 | err_msg='Mutual [decomposition] mismatch') 61 | np.testing.assert_array_almost_equal(mi_d, test_mi, 62 | decimal=decimal, 63 | err_msg='Mutual [debiased] mismatch') 64 | if test_mi_vars is not None: 65 | np.testing.assert_array_almost_equal(mi_vars, test_mi_vars, 66 | decimal=decimal, 67 | err_msg='Mutual Info (individual) mismatch') 68 | 69 | np.testing.assert_array_almost_equal(mi_vars2, test_mi_vars, 70 | decimal=decimal, 71 | err_msg='Mutual Info (individual) mismatch') 72 | 73 | 74 | class test_ExampleGatesTimme2014(unittest.TestCase): 75 | ''' 76 | Examples gates taken from: 77 | 78 | Timme, Nicholas, et al. "Synergy, redundancy, and multivariate information 79 | measures: an experimentalist's perspective." Journal of computational 80 | neuroscience 36.2 (2014): 119-140. 81 | ''' 82 | 83 | def test_Timme2014_Example1(self): 84 | X = np.array([[0, 0], 85 | [1, 0], 86 | [0, 1], 87 | [1, 1]]) 88 | 89 | y = np.array([0, 1, 1, 0]) 90 | 91 | test_syn = 1 92 | test_red = 0 93 | test_uni = [0, 0] 94 | test_mi = 1 95 | test_mi_vars = [0, 0] 96 | 97 | compare_values(X,y,test_syn = test_syn, 98 | test_red = test_red, 99 | test_uni = test_uni, 100 | test_mi = test_mi, 101 | test_mi_vars = test_mi_vars) 102 | 103 | def test_Timme2014_Example2(self): 104 | X = np.array([[0, 0], 105 | [1, 0], 106 | [0, 1], 107 | [1, 1]]) 108 | 109 | y = np.array([0, 1, 0, 1]) 110 | 111 | test_syn = 0 112 | test_red = 0 113 | test_uni = [1, 0] 114 | test_mi = 1 115 | test_mi_vars = [1, 0] 116 | 117 | compare_values(X,y,test_syn = test_syn, 118 | test_red = test_red, 119 | test_uni = test_uni, 120 | test_mi = test_mi, 121 | test_mi_vars = test_mi_vars) 122 | 123 | def test_Timme2014_Example3(self): 124 | X = np.array([[0, 0], 125 | [1, 0], 126 | [0, 1], 127 | [1, 1]]) 128 | 129 | y = np.array([0, 0, 0, 1]) 130 | 131 | 132 | test_syn = 0.5 133 | test_red = 0.311 134 | test_uni = [0, 0] 135 | test_mi = 0.811 136 | test_mi_vars = [0.311, 0.311] 137 | 138 | compare_values(X,y,test_syn = test_syn, 139 | test_red = test_red, 140 | test_uni = test_uni, 141 | test_mi = test_mi, 142 | test_mi_vars = test_mi_vars) 143 | 144 | def test_Timme2014_Example4(self): 145 | X = np.array([[0, 0], 146 | [0, 0], 147 | [0, 0], 148 | [1, 1], 149 | [1, 1], 150 | [1, 1], 151 | [1, 1], 152 | [1, 1], 153 | [1, 1], 154 | [1, 1]]) 155 | 156 | y = np.array([0,1,1,0,1,1,1,1,1,1]) 157 | 158 | test_syn = 0 159 | test_red = 0.0323 160 | test_uni = [0, 0] 161 | test_mi = 0.0323 162 | test_mi_vars = [0.0323, 0.0323] 163 | 164 | compare_values(X,y,test_syn = test_syn, 165 | test_red = test_red, 166 | test_uni = test_uni, 167 | test_mi = test_mi, 168 | test_mi_vars = test_mi_vars, decimal = 4) 169 | 170 | def test_Timme2014_Example5(self): 171 | X = np.array([[0, 0], 172 | [1, 0], 173 | [0, 1], 174 | [1, 1]]) 175 | 176 | y = np.array([0, 1, 2, 3]) 177 | 178 | test_syn = 1 179 | test_red = 1 180 | test_uni = [0, 0] 181 | test_mi = 2 182 | test_mi_vars = [1, 1] 183 | 184 | compare_values(X,y,test_syn = test_syn, 185 | test_red = test_red, 186 | test_uni = test_uni, 187 | test_mi = test_mi, 188 | test_mi_vars = test_mi_vars, decimal = 4) 189 | 190 | def test_Timme2014_Example6(self): 191 | 192 | X = np.array([[0, 0], 193 | [1, 1]]) 194 | 195 | y = np.array([0, 0]) 196 | 197 | test_syn = 0 198 | test_red = 0 199 | test_uni = [0, 0] 200 | test_mi = 0 201 | test_mi_vars = [0, 0] 202 | 203 | compare_values(X,y,test_syn = test_syn, 204 | test_red = test_red, 205 | test_uni = test_uni, 206 | test_mi = test_mi, 207 | test_mi_vars = test_mi_vars, decimal = 7) 208 | 209 | def test_Timme2014_Example7(self): 210 | 211 | X = np.array([[0, 0, 0], 212 | [1, 0, 0], 213 | [0, 1, 0], 214 | [1, 1, 0], 215 | [0, 0, 1], 216 | [1, 0, 1], 217 | [0, 1, 1], 218 | [1, 1, 1]]) 219 | 220 | y = np.array([0, 1, 1, 0, 1, 0, 0, 1]) 221 | 222 | test_syn = 1 223 | test_mi = 1 224 | test_mi_vars = [0, 0, 0] 225 | 226 | compare_values(X,y,test_syn = test_syn, 227 | test_red = None, 228 | test_uni = None, 229 | test_mi = test_mi, 230 | test_mi_vars = test_mi_vars, decimal = 4) 231 | 232 | test_syn = 0 233 | compare_values(X[:,[0,1]],y,test_syn = test_syn) 234 | 235 | 236 | def test_Timme2014_Example8(self): 237 | 238 | X = np.array([[0, 0, 0], 239 | [1, 0, 0], 240 | [0, 1, 0], 241 | [1, 1, 0], 242 | [0, 0, 1], 243 | [1, 0, 1], 244 | [0, 1, 1], 245 | [1, 1, 1]]) 246 | 247 | y = np.array([0, 1, 1, 0, 0, 1, 1, 0]) 248 | 249 | test_syn = 0 250 | test_mi = 1 251 | test_mi_vars = [0, 0, 0] 252 | 253 | compare_values(X,y,test_syn = test_syn, 254 | test_red = None, 255 | test_uni = None, 256 | test_mi = test_mi, 257 | test_mi_vars = test_mi_vars, decimal = 4) 258 | 259 | test_syn = 1 260 | compare_values(X[:,[0,1]],y,test_syn = test_syn) 261 | 262 | def test_Timme2014_Example4_testLabels(self): 263 | # test that label mapping to different integers gives the same 264 | # result 265 | 266 | X = np.array([[0, 0], 267 | [0, 0], 268 | [0, 0], 269 | [1, 1], 270 | [1, 1], 271 | [1, 1], 272 | [1, 1], 273 | [1, 1], 274 | [1, 1], 275 | [1, 1]]) 276 | 277 | y = np.array([12, 31, 31, 12, 31, 31, 31, 31, 31, 31]) 278 | 279 | test_syn = 0 280 | test_red = 0.0323 281 | test_uni = [0, 0] 282 | test_mi = 0.0323 283 | test_mi_vars = [0.0323, 0.0323] 284 | 285 | compare_values(X, y, test_syn=test_syn, 286 | test_red=test_red, 287 | test_uni=test_uni, 288 | test_mi=test_mi, 289 | test_mi_vars=test_mi_vars, decimal=4) 290 | 291 | def test_Timme2014_Example8_testLabels(self): 292 | 293 | X = np.array([[0, 0, 0], 294 | [1, 0, 0], 295 | [0, 1, 0], 296 | [1, 1, 0], 297 | [0, 0, 1], 298 | [1, 0, 1], 299 | [0, 1, 1], 300 | [1, 1, 1]]) 301 | 302 | y = np.array([2, 8, 8, 2, 2, 8, 8, 2]) 303 | 304 | test_syn = 0 305 | test_mi = 1 306 | test_mi_vars = [0, 0, 0] 307 | 308 | compare_values(X, y, test_syn=test_syn, 309 | test_red=None, 310 | test_uni=None, 311 | test_mi=test_mi, 312 | test_mi_vars=test_mi_vars, decimal=4) 313 | 314 | test_syn = 1 315 | compare_values(X[:, [0, 1]], y, test_syn=test_syn) 316 | 317 | 318 | 319 | 320 | class test_ExampleGatesInce2016(unittest.TestCase): 321 | ''' 322 | Examples taken from: 323 | 324 | Williams, Paul L., and Randall D. Beer. 325 | "Nonnegative decomposition of multivariate information." 326 | arXiv preprint arXiv:1004.2515 (2010). 327 | ''' 328 | 329 | def test_Ince2016_Figure3A(self): 330 | X = np.array([[0, 0], 331 | [0, 1], 332 | [1, 0]]) 333 | 334 | y = np.array([0, 1, 2]) 335 | 336 | 337 | test_syn = 0.3333 338 | test_red = 0.5850 339 | test_uni = [0.3333, 0.3333] 340 | 341 | 342 | compare_values(X,y,test_syn = test_syn, 343 | test_red = test_red, 344 | test_uni = test_uni, 345 | decimal = 4) 346 | 347 | 348 | def test_Ince2016_Figure3B(self): 349 | X = np.array([[0, 0], 350 | [0, 1], 351 | [1, 1], 352 | [1, 0]]) 353 | 354 | y = np.array([0, 1, 1, 2]) 355 | 356 | 357 | test_syn = 0.5 358 | test_red = 0.5 359 | test_uni = [0, 0.5] 360 | 361 | 362 | compare_values(X,y,test_syn = test_syn, 363 | test_red = test_red, 364 | test_uni = test_uni, 365 | decimal = 7) 366 | 367 | 368 | def test_Ince2016_Figure3C(self): 369 | X = np.array([[0, 0], 370 | [1, 1], 371 | [0, 1], 372 | [1, 1], 373 | [0, 1], 374 | [1, 0]]) 375 | 376 | y = np.array([0, 0, 1, 1, 2, 2]) 377 | 378 | 379 | test_syn = 0.6667 380 | test_red = 0 381 | test_uni = [0, 0.2516] 382 | 383 | 384 | compare_values(X,y,test_syn = test_syn, 385 | test_red = test_red, 386 | test_uni = test_uni, 387 | decimal = 4) 388 | 389 | 390 | class test_DebiasedMeasures(unittest.TestCase): 391 | 392 | # TODO: tile the arrays from the examples and test debiased measures 393 | # maybe introducing some noise? 394 | # make sure that if you run debiased on repetitions, you get 395 | # very close to the true value 396 | pass 397 | 398 | 399 | -------------------------------------------------------------------------------- /pidpy/PIDCalculator.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from joblib import Parallel, delayed 3 | 4 | from pidpy.utils import lazy_property 5 | from pidpy.utils import _get_surrogate_val 6 | from pidpy.utils import _isbinary 7 | from pidpy.utils import _joint_probability, _conditional_probability_from_joint 8 | from pidpy.utils import _joint_sub, _joint_var 9 | from pidpy.utils import _Imin, _Imax 10 | 11 | from pidpy.utilsc import _compute_mutual_info 12 | from pidpy.utilsc import _compute_specific_info 13 | 14 | # NOTE: division by zero can occur when generating the marginal distributions 15 | # if not all possible patterns of the sources are realized (cond_yX ends up 16 | # having nans). A check is inserted in pidpy.utilsc._compute_specific_info, 17 | # so that contributions to the specific information are only calculated on 18 | # non-nan terms. 19 | 20 | np.seterr(divide='ignore', invalid='ignore') 21 | 22 | #TODO: add option to test significane in the functions for the individual terms 23 | 24 | class PIDCalculator(): 25 | 26 | ''' 27 | Calculator class for the partial information decomposition of mutual 28 | information for discrete variables. 29 | 30 | Parameters 31 | ---------- 32 | X : 2D ndarray, shape (n_samples, n_features) 33 | Data from which to obtain the information decomposition. 34 | 35 | y : 1D ndarray, shape (n_samples, ) 36 | Array containing the labels of the dependent variable. 37 | 38 | **kwargs 39 | safe_labels : bool, optional (default = False) 40 | If `True`, it is assumed that the `n` labels the compose `y` 41 | are the integers in `range(n)`. If `False`, the above is checked 42 | and if it is found to be false, `y` is mapped so that the label 43 | values are `range(n)`. This is necessary because the label values 44 | are used for indexing in the construction of probability tables. 45 | `safe_labels` should be kept to `False`, setting to `True` is only 46 | done internally to speed up the initialization of the PID calculators 47 | used to generate surrogate data. 48 | 49 | binary : bool, optional 50 | Directly specifies whether `X` is a binary array. If not provided, 51 | the PID calculator runs a check on the whole array `X` to verify 52 | if it is binary. This parameter is used internally and passed 53 | to the surrogates to avoid multiple checks being run on the same 54 | array. 55 | If the data is binary and has a relatively low number of variables, 56 | the probability tables can be generated with a faster routine. 57 | 58 | labels : list, optional 59 | Allows to directly specify the labels in `y`. If not provided, 60 | labels are extracted from the `y` array using `set`. This parameter 61 | is used internally to speed up the instantiation of surrogate 62 | calculators. 63 | 64 | n_jobs : int, optional 65 | The generation of surrogate data sets and the computation of 66 | their information values can be executed in parallel, with n_jobs 67 | specifying the number of parallel jobs to be launched through 68 | the Joblib library. There is a known issue with large arrays, 69 | for which parallelization is not possible. In that case a 70 | execution is continued with 1 sequential job. 71 | 72 | alpha: float, optional 73 | If the `decomposition` method is asked to return the sum of the 74 | unique information while `test_significance` is set to true, 75 | the sum is of the unique information of individual sources is 76 | computed only for sources which are significant with significance 77 | level `alpha`. Default level is `0.01`. 78 | 79 | 80 | Notes 81 | ----- 82 | Partial information decomposition of binary data (`X` contains only 83 | `0` and `1`, no restrictions on `y`) is supported for an arbitrary 84 | number of variables (although ensure that the number of data points is 85 | sufficient to accurately build the probability tables). 86 | Decomposition of integer non-binary data is only supported for up to 87 | three variables. 88 | 89 | References 90 | ---------- 91 | ''' 92 | 93 | def __init__(self, X, y, **kwargs): 94 | 95 | if X.shape[0] != y.shape[0]: 96 | raise ValueError('The number of samples in the feature and labels' 97 | 'arrays should match.') 98 | 99 | if not issubclass(X.dtype.type, np.integer): 100 | X = X.astype('int') 101 | 102 | if not 'binary' in kwargs: 103 | self.binary = _isbinary(X) 104 | else: 105 | self.binary = kwargs['binary'] 106 | 107 | 108 | if not 'n_jobs' in kwargs: 109 | self.n_jobs = -1 110 | else: 111 | self.n_jobs = kwargs['n_jobs'] 112 | 113 | if not 'alpha' in kwargs: 114 | self.alpha = 0.05 115 | else: 116 | self.alpha = kwargs['alpha'] 117 | 118 | if not self.binary and X.shape[1] > 3: 119 | raise NotImplementedError('Decomposition of non-binary data with more' 120 | 'than 3 variables is not supported yet.') 121 | 122 | # labels are passed by the main calculator as kwargs to the calculators 123 | # used for debiasing, to avoid recomputing the set of labels 124 | if not 'labels' in kwargs: 125 | original_labels = list(set(y)) 126 | else: 127 | original_labels = kwargs['labels'] 128 | 129 | if not ('safe_labels' in kwargs and kwargs['safe_labels']): 130 | if not original_labels == range(len(original_labels)): 131 | y = np.array([original_labels.index(lab) for lab in y]) 132 | 133 | self.labels = range(len(original_labels)) 134 | self.original_labels = original_labels 135 | 136 | self.Nlabels = len(self.labels) 137 | self.verbosity = 0 138 | self.X = X 139 | self.y = y 140 | self.Nsamp = y.shape[0] 141 | self.Nneurons = X.shape[1] 142 | self.surrogate_pool = [] 143 | 144 | 145 | @lazy_property 146 | def joint_var_(self): 147 | ''' 148 | Joint probability tables of every individual variable of `X` with `y`. 149 | ''' 150 | joint_var_ = _joint_var(self.X, self.y, binary = self.binary) 151 | return joint_var_ 152 | 153 | @lazy_property 154 | def joint_sub_(self): 155 | ''' 156 | Joint probability tables of all groups of `n-1` variables of `X`. 157 | ''' 158 | joint_sub_ = _joint_sub(self.X, self.y, binary = self.binary) 159 | return joint_sub_ 160 | 161 | @lazy_property 162 | def joint_full_(self): 163 | ''' 164 | Full joint probability of `X` and `y`. 165 | ''' 166 | joint_full_ = _joint_probability(self.X, self.y, binary = self.binary) 167 | return joint_full_ 168 | 169 | @lazy_property 170 | def spec_info_var_(self): 171 | ''' 172 | Specific information for every label for all individual variables of `X`. 173 | ''' 174 | spec_info_var_ = self._spec_info(self.labels, self.joint_var_) 175 | return spec_info_var_ 176 | 177 | 178 | @lazy_property 179 | def spec_info_sub_(self): 180 | ''' 181 | Specific information for every label for all groups of `n-1` variables 182 | of `X`. 183 | ''' 184 | spec_info_sub_ = self._spec_info(self.labels, self.joint_sub_) 185 | return spec_info_sub_ 186 | 187 | @lazy_property 188 | def spec_info_uni_(self): 189 | ''' 190 | Rearranged specific information values to compute unique information. 191 | ''' 192 | spec_info_uni_ = [] 193 | sv = self.spec_info_var_ 194 | ss = self.spec_info_sub_ 195 | for i in range(self.Nneurons): 196 | spec_info_i = [[sv[j][i], ss[j][i]] for j in range(self.Nlabels)] 197 | spec_info_uni_.append(spec_info_i) 198 | return spec_info_uni_ 199 | 200 | @lazy_property 201 | def X_mar_(self): 202 | ''' 203 | Marginal probability of `X`. 204 | ''' 205 | X_mar_ = self.joint_full_.sum(axis=1) 206 | return X_mar_ 207 | 208 | @lazy_property 209 | def y_mar_(self): 210 | ''' 211 | Marginal probability of `y`. 212 | ''' 213 | # TODO build this without referring to the full joint 214 | y_mar_ = self.joint_full_.sum(axis=0) 215 | return y_mar_ 216 | 217 | @lazy_property 218 | def mi_var_(self): 219 | ''' 220 | Mutual information between each individual variables of `X` and `y`. 221 | ''' 222 | mi_var_ = [] 223 | for joint in self.joint_var_: 224 | x_mar_ = joint.sum(axis = 1) 225 | mi = _compute_mutual_info(x_mar_, self.y_mar_, joint) 226 | mi_var_.append(mi) 227 | return mi_var_ 228 | 229 | @lazy_property 230 | def mi_full_(self): 231 | ''' 232 | Mutual of information between `X` and `y`. 233 | ''' 234 | mi_full_ = _compute_mutual_info(self.X_mar_, self.y_mar_, 235 | self.joint_full_) 236 | return mi_full_ 237 | 238 | def synergy(self, debiased = False, n = 50): 239 | ''' 240 | Compute the pure synergy between the variables of the data array X. 241 | 242 | Parameters 243 | ---------- 244 | debiased: bool, optional 245 | If True, synergy is debiased with shuffled surrogates. Default is 246 | False. 247 | 248 | n : int, optional 249 | Number of surrogate data sets to be used for debiasing. Defaults 250 | to 50. 251 | 252 | Returns 253 | ------- 254 | synergy : float 255 | Pure synergy of the variables in `X`. 256 | standard_deviation : float 257 | Standard deviation of the synergy of the surrogate sets, only 258 | returned if `debiased = True`. 259 | ''' 260 | 261 | if debiased: 262 | self.syn = self._debiased('synergy', n) 263 | else: 264 | self.syn = self.mi_full_ - _Imax(self.y_mar_, self.spec_info_sub_) 265 | return self.syn 266 | 267 | def redundancy(self, debiased = False, n = 50): 268 | ''' 269 | Compute the pure synergy between the variables of the data array X. 270 | 271 | Parameters 272 | ---------- 273 | debiased: bool, optional 274 | If True, redundancy is debiased with shuffled surrogates. Default is 275 | False. 276 | 277 | n : int, optional 278 | Number of surrogate data sets to be used for debiasing. Defaults 279 | to 50. 280 | 281 | Returns 282 | ------- 283 | redundancy : float 284 | Pure redundancy of the variables in `X`. 285 | standard_deviation : float 286 | Standard deviation of the redundancy of the surrogate sets, only 287 | returned if `debiased = True`. 288 | ''' 289 | 290 | if debiased: 291 | self.red = self._debiased('redundancy', n) 292 | else: 293 | self.red = _Imin(self.y_mar_, self.spec_info_var_) 294 | return self.red 295 | 296 | 297 | def unique(self, debiased = False, n = 50): 298 | ''' 299 | Compute the unique information of the variables in the data array X. 300 | 301 | Parameters 302 | ---------- 303 | debiased: bool, optional 304 | If True, synergy is debiased with shuffled surrogates. Default is 305 | False. 306 | 307 | n : int, optional 308 | Number of surrogate data sets to be used for debiasing. Defaults 309 | to 50. 310 | 311 | Returns 312 | ------- 313 | unique : 1D ndarray (n_variables, ) 314 | Unique information of each of the variables in `X`. 315 | standard_deviation : 1D ndarray (n_variables, ) 316 | Standard deviation of the unique information of the surrogate sets 317 | for each variable in `X`. 318 | Only returned if `debiased = True`. 319 | ''' 320 | 321 | if debiased: 322 | self.uni = self._debiased('unique', n) 323 | else: 324 | uni = np.zeros(self.Nneurons) 325 | for i in range(self.Nneurons): 326 | unique = self.mi_var_[i] - _Imin(self.y_mar_, self.spec_info_uni_[i]) 327 | uni[i] = unique 328 | self.uni = uni 329 | return self.uni 330 | 331 | def mutual(self, debiased = False, n = 50, individual = False, decimals = 8): 332 | 333 | ''' 334 | Compute the mutual between `X` and `y`. 335 | 336 | Parameters 337 | ---------- 338 | debiased: bool, optional (default = False) 339 | If True, mutual information is debiased with shuffled surrogates. 340 | 341 | n : int, optional (default = 50) 342 | Number of surrogate data sets to be used for debiasing. 343 | 344 | individual : bool, optional (default = False) 345 | If `False`, mutual information between the full `X` and `y` 346 | is calculated. 347 | If `True`, mutual information is computed for each of the 348 | individual variables (columns) which compose `X`, and an array 349 | of MI values is returned. 350 | 351 | Returns 352 | ------- 353 | mutual information 354 | Mutual information in bits. If `debiased = False`, a single 355 | float value is returned (or a list if `individual = True`). 356 | If `debiased = True`, a tuple is returned where the first element 357 | contains the MI values (float or 1D ndarray of floats, 358 | depending on `individual`) and the second 359 | element contains the associated standard deviation(s). 360 | 361 | Examples 362 | -------- 363 | 364 | >>> X = np.array([[0, 0], 365 | [1, 0], 366 | [0, 1], 367 | [1, 1]]) 368 | >>> y = np.array([0, 1, 1, 0]) 369 | >>> pid = PIDCalculator(X,y) 370 | >>> pid.mutual() 371 | 1.0 372 | >>> pid.mutual(individual=True) 373 | [0.0, 0.0] 374 | ''' 375 | if debiased: 376 | mi = self._debiased('mutual', n, individual = False) 377 | self.mi = mi 378 | if individual: 379 | mi = self._debiased('mutual',n, individual = True) 380 | 381 | else: 382 | if individual: 383 | mi = self.mi_var_ 384 | self.mi_individual = mi 385 | else: 386 | mi = self.mi_full_ 387 | self.mi = mi 388 | 389 | return mi 390 | 391 | def decomposition(self, debiased = False, as_percentage = False, n = 50, 392 | decimal = 8, return_individual_unique = False, 393 | return_std_surrogates = False, test_significance=False): 394 | ''' 395 | Decompose the mutual information of `X` into the pure synergy, 396 | redunandcy, and unique terms. 397 | 398 | Parameters 399 | ---------- 400 | debiased : bool, optional (default = False) 401 | If True, the values of the decomposition are debiased using 402 | shuffled surrogates. 403 | 404 | as_percentage : bool, optional (default = False) 405 | If True, the values of synergy, redundancy, and mutual information 406 | are returned as a percentage of mutual information. The mutual 407 | information value is returned in bits. 408 | 409 | n : int, optional (default = 50) 410 | Number of shuffled data sets used for debiasing. 411 | 412 | decimal : int, optional (default = 8) 413 | Round off the output to a certain decimal position. 414 | 415 | return_individual_unique : bool, optional (default = False) 416 | If True, unique information is returned as an array containing 417 | the corresponding value for each variable in `X`. If False, 418 | it is returned as the sum of all the individual unique information 419 | terms. 420 | 421 | return_std_surrogates : bool, optional (default = False) 422 | If True, the standard deviation associated with the surrogate data 423 | sets for each information theoretic measure is returned. 424 | 425 | test_significance : bool, optional (default = False) 426 | If True, a p-value is computed for every term of the decomposition 427 | as the fraction of surrogates for which the value of the term is 428 | higher than the observed one (unshuffled). 429 | 430 | Returns 431 | ------- 432 | decomposition : tuple 433 | If `return_std_surrogates = False`, the tuple 434 | `decomposition = (synergy, redundancy, unique, mutual)` is returned 435 | (with the values of synergy, redundancy, and unique information 436 | expressed in bits if `as_percentage = False`, or as 437 | percentages of the mutual information if `as_percentage = True`). 438 | If `return_std_surrogates = True`, decomposition is a tuple containing 439 | two tuples, namely 440 | `decomposition = ((synergy, redundancy, unique, mutual), 441 | (std_synergy, std_redundancy, std_unique, std_mutual))` 442 | If `test_significance = True`, a tuple 443 | `(p_val_syn, p_val_red, p_val_uni, p_val_mi)` is also returned, so 444 | that the output is either `decomposition = (information_terms, 445 | standard_deviations, p_values)`, or only `decomposition = 446 | (information_terms, p_values)`. 447 | 448 | Examples 449 | -------- 450 | Compute the partial information decomposition 451 | >>> pid = PIDCalculator(X,y) 452 | >>> syn, red, uni, mut = pid.decomposition() 453 | 454 | Compute the partial information decomposition with 100 surrogates 455 | used for debiasing, and return the decomposition terms as a percentage 456 | of mutual information (the latter is still returned in bits) 457 | >>> syn, red, uni, mut = pid.decomposition(debiased = True, n = 30, as_percentage=True) 458 | ''' 459 | 460 | if debiased: 461 | syn, std_syn, p_syn = self.synergy(debiased = True, n = n) 462 | red, std_red, p_red = self.redundancy(debiased = True, n = n) 463 | uni, std_uni, p_uni = self.unique(debiased = True, n = n) 464 | mi, std_mi, p_mi = self.mutual(debiased = True, n = n) 465 | 466 | else: 467 | syn = self.synergy(debiased = False) 468 | red = self.redundancy(debiased = False) 469 | uni = self.unique(debiased = False) 470 | mi = self.mutual(debiased = False) 471 | 472 | if as_percentage: 473 | if mi > 1e-08: 474 | syn = 100 * syn / mi 475 | red = 100 * red / mi 476 | uni = 100 * uni / mi 477 | 478 | else: 479 | syn, red = 0, 0 480 | uni = np.zeros_like(uni) 481 | 482 | if not return_individual_unique: 483 | if test_significance: 484 | uni = np.sum(uni[p_uni < self.alpha]) 485 | p_uni = None 486 | else: 487 | uni = np.sum(uni) 488 | 489 | decomposition = (np.round(syn, decimal), np.round(red, decimal), 490 | np.round(uni, decimal), np.round(mi, decimal)) 491 | 492 | if return_std_surrogates: 493 | if not return_individual_unique: 494 | std_uni = np.mean(std_uni) 495 | 496 | if as_percentage: 497 | if mi > 1e-08: 498 | std_syn = 100 * std_syn / mi 499 | std_red = 100 * std_red / mi 500 | std_uni = 100 * std_uni / mi 501 | 502 | std_decomposition = (std_syn, std_red, std_uni, std_mi) 503 | 504 | decomposition = (decomposition, std_decomposition) 505 | 506 | if test_significance: 507 | if return_std_surrogates: 508 | decomposition = decomposition + ((p_syn, p_red, p_uni, p_mi),) 509 | if not return_std_surrogates: 510 | decomposition = (decomposition, (p_syn, p_red, p_uni, p_mi)) 511 | 512 | return decomposition 513 | 514 | def specific_information(self): 515 | ''' 516 | User method to obtain the specific information. 517 | 518 | Returns 519 | ------- 520 | spec_info: 2D ndarray, shape (n_variables, n_labels) 521 | ''' 522 | 523 | return np.array(self.spec_info_var_).T 524 | 525 | def _debiased_synergy(self, n = 50): 526 | out = self._debiased('synergy', n) 527 | self.debiased_syn = out 528 | return self.debiased_syn 529 | 530 | def _debiased_redundancy(self, n = 50): 531 | out = self._debiased('redundancy', n) 532 | self.debiased_red = out 533 | return self.debiased_red 534 | 535 | def _debiased_unique(self, n = 50): 536 | out = self._debiased('unique', n) 537 | self.debiased_uni = out 538 | return self.debiased_uni 539 | 540 | def _debiased_mutual(self, n = 50): 541 | out = self._debiased('mutual', n) 542 | self.debiased_mi = out 543 | return self.debiased_mi 544 | 545 | # TODO: specific info of certain var for all labels 546 | # TODO: specific info of certain label for all vars 547 | # TODO: specific info of certain label certain var 548 | # TODO: the above debiased 549 | 550 | def _debiased(self, fun, n, test_significance=True, **kwargs): 551 | res = getattr(self, fun)(**kwargs) 552 | self._make_surrogates(n) 553 | 554 | if fun in ['unique'] or \ 555 | ('individual' in kwargs and kwargs['individual']): 556 | col = self.Nneurons 557 | else: 558 | col = 1 559 | 560 | # for n_jobs = 1, the original implementation is still a bit faster 561 | 562 | if self.n_jobs != 1: 563 | try: 564 | null_list = Parallel(n_jobs=self.n_jobs)(delayed 565 | (_get_surrogate_val)(self.surrogate_pool[i], fun, **kwargs) 566 | for i in range(n)) 567 | null = np.array(null_list, ndmin=2).T 568 | 569 | # TODO: fix this. Problems occur only with large arrays. 570 | except ValueError as err: 571 | print("Parallel processing has encountered a " 572 | "problem (the exception is stored in the attribute 'err'.)" 573 | +"\nContinuing execution with n_jobs = 1.") 574 | self.err = err 575 | 576 | self.n_jobs = 1 577 | 578 | if self.n_jobs == 1: 579 | null = np.zeros([n,col]) 580 | for i in range(n): 581 | surrogate = self.surrogate_pool[i] 582 | sval = getattr(surrogate, fun)(**kwargs) 583 | null[i,:] = sval 584 | 585 | if null.shape[0] > 0: 586 | mean = np.mean(null, axis = 0) 587 | std = np.std(null, axis=0) 588 | 589 | if test_significance: 590 | p_val = self._p_value(res, null) 591 | 592 | else: 593 | mean = np.zeros(col, dtype = int) 594 | std = np.empty(col) 595 | std[:] = np.nan 596 | 597 | if mean.shape[0] == 1: 598 | mean = mean[0] 599 | if std.shape[0] == 1: 600 | std = std[0] 601 | 602 | if (null.shape[0] > 0) and test_significance: 603 | return res - mean, std, p_val 604 | else: 605 | return res - mean, std 606 | 607 | def _make_surrogates(self, n = 50): 608 | for i in range(n - len(self.surrogate_pool)): 609 | self.surrogate_pool.append(self._surrogate()) 610 | 611 | 612 | def _surrogate(self): 613 | ind = np.random.permutation(self.Nsamp) 614 | sur = PIDCalculator(self.X, self.y[ind], verbosity = 1, 615 | binary = self.binary, labels = self.labels, 616 | safe_labels=True) 617 | return sur 618 | 619 | 620 | def _p_value(self, obs, null): 621 | ''' 622 | Compute the p-value of an information theoretic (IT) quantity as the 623 | fraction of surrogates for which the IT quantity is larger than the 624 | observed value (corresponding to the unshuffled data). 625 | ''' 626 | pval = np.sum(null > obs, axis=0) / null.shape[0] 627 | if pval.shape[0] == 1: 628 | pval = pval[0] 629 | return pval 630 | 631 | 632 | def _redundancy_pairs(self): 633 | ''' 634 | Experimental function to compute the average redundancy between 635 | all the pairs of variables in `X`. The idea is to characterize a group 636 | of variables not only by the pure redundancy between all of them, 637 | but also to explore redundancy at lower levels (pairs). 638 | ''' 639 | red_pairs = [] 640 | for i in range(self.Nneurons): 641 | for j in range(self.Nneurons): 642 | if i != j: 643 | spec_info_pair = [[self.spec_info_var_[n][i], 644 | self.spec_info_var_[n][j]] 645 | for n in self.labels] 646 | 647 | red_pair = _Imin(self.y_mar_, spec_info_pair) 648 | red_pairs.append(red_pair) 649 | self.red_pairs = np.mean(red_pairs) 650 | return self.red_pairs 651 | 652 | def _spec_info(self, labels, joints): 653 | spec_info_full_ = [] 654 | for lab in labels: 655 | spec_info_lab = [] 656 | for joint in joints: 657 | cond_Xy, cond_yX = _conditional_probability_from_joint(joint) 658 | info = _compute_specific_info(lab, self.y_mar_, 659 | cond_Xy, cond_yX, joint) 660 | spec_info_lab.append(info) 661 | spec_info_full_.append(spec_info_lab) 662 | return spec_info_full_ 663 | 664 | def _lattice(self): 665 | """ 666 | Old experimental function which computes nodes on the 667 | redundancy lattice. 668 | """ 669 | uni = [] 670 | for i in range(self.Nneurons): 671 | unique = self.mi_var_[i] - _Imin(self.y_mar_, self.spec_info_sub_) 672 | uni.append(unique) 673 | self.uni = uni 674 | return uni 675 | 676 | 677 | 678 | 679 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . --------------------------------------------------------------------------------