<commit_before>#===============================================================================
# Copyright (c) 2016, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#
# * Neither the name of paramz.core.constrainable nor the names of its
#   contributors may be used to endorse or promote products derived from
#   this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#===============================================================================

from manifold import distances
from scipy.sparse.csgraph import minimum_spanning_tree, dijkstra
from scipy.sparse import csr_matrix, find, lil_matrix
from scipy.cluster.hierarchy import average, fcluster, dendrogram
from scipy.spatial.distance import pdist, squareform
import numpy as np

class ManifoldCorrection(object):
    def __init__(self, gplvm, distance=distances.mean_embedding_dist):
        """
        Construct a correction class for the BayesianGPLVM given.

        All evaluations on this object are lazy, so do not change attributes
        at runtime in order to have a consistent model.

        :param [GPy.models.BayesianGPLVM,GPy.models.GPLVM] gplvm:
            an optimized GPLVM or BayesianGPLVM model from GPy
        :param func dist: dist(X,G), the distance to use for pairwise distances
            in X using the manifold embedding G
        """
        self.gplvm = gplvm
        self.distance = distance

    @property
    def X(self):
        if getattr(self, '_X', None) is None:
            try:
                self._X = self.gplvm.X.mean
                self._X.mean
            except AttributeError:
                # not bayesian GPLVM
                self._X = self.gplvm.X
            #self._X = self._X * self.gplvm.kern.input_sensitivity()
        return self._X

    @property
    def G(self):
        if getattr(self, '_G', None) is None:
            self._G = self.gplvm.predict_wishard_embedding(self.X)
        return self._G

    @property
    def manifold_corrected_distance_matrix(self):
        """
        Returns the distances between all pairs of inputs, corrected for
        the manifold embedding.
        """
        if getattr(self, '_M', None) is None:
            self._M = csr_matrix(self.distance(self.X, self.G))
        return self._M

    @property
    def minimal_spanning_tree(self):
        """
        Create a minimal spanning tree using the distance correction method given.

        You can explore different distance corrections in manifold.distances.
        """
        if getattr(self, '_mst', None) is None:
            self._mst = minimum_spanning_tree(self.manifold_corrected_distance_matrix)
        return self._mst

    def knn_graph(self, k, include_mst=False):
        """
        Return a k-nearest-neighbour graph with k neighbours.

        Optionally you can add the minimal spanning tree in, in order to
        ensure a fully connected graph. This only adds edges which are not already there,
        so that the connections are made.
        """
        D = self.manifold_corrected_distance_matrix
        idxs = np.argsort(D)
        r = range(D.shape[0])
        idx = idxs[:, :k]
        _distances = lil_matrix(D.shape)
        for neighbours in idx.T:
            _distances[r, neighbours] = D[r, neighbours]
        if include_mst:
            mst = self.minimal_spanning_tree
            for i,j,v in find(mst):
                if _distances[i,j] == 0:
                    _distances[i,j] = v
        return _distances

    def knn_corrected_distances(self, knn_graph):
        """
        Return all distances along the knn_graph given.

        You can get the knn_graph by calling knn_graph on this object.
        """
        return dijkstra(knn_graph, directed=False)

    def knn_corrected_structure(self, knn_graph):
        """
        Return the structure distances, where each edge along knn graph has a
        distance of one, such that the distance just means the number of
        hops to make in order to get from one point to another.

        This can be very helpful in doing structure analysis
        and clustering of the manifold embedded data points.
        """
        return dijkstra(knn_graph, directed=False, unweighted=True)

    @property
    def tree_corrected_distances(self):
        """
        Return the distances summed along the manifold minimal spanning tree.

        This reflects the structure and distances along the manifold in order
        to include the pseudo stretch of the Wishart embedding of the manifold.
        """
        if getattr(self, '_corrected_distances', None) is None:
            self._corrected_distances = dijkstra(self.minimal_spanning_tree, directed=False, return_predecessors=True)
        return self._corrected_distances[0]

    @property
    def tree_corrected_structure(self):
        """
        Return the structure distances, where each edge along the manifold
        minimal spanning tree has a distance of one, such that the
        distance just means the number of hops to make in order to get from
        one point to another. This can be very helpful in doing structure analysis
        and clustering of the manifold embedded data points.
        """
        if getattr(self, '_corrected_structure', None) is None:
            self._corrected_structure = dijkstra(self.minimal_spanning_tree, directed=False, unweighted=True)
        return self._corrected_structure


    @property
    def tree_structure_linkage(self):
        """
        Return the UPGMA linkage matrix based on the correlation structure of
        the manifold embedding MST
        """
        if getattr(self, '_Slinkage', None) is None:
            self._Slinkage = average(pdist(self.manifold_corrected_structure, metric='correlation'))
        return self._Slinkage

    @property
    def tree_distance_linkage(self):
        """
        Return the UPGMA linkage matrix for the manifold distances
        """
        if getattr(self, '_Mlinkage', None) is None:
            self._Mlinkage = average(squareform(self.manifold_corrected_distances, ))
        return self._Mlinkage

    def cluster(self, linkage, num_classes):
        """
        Cluster the linkage matrix into num_classes number of classes.
        """
        return fcluster(linkage, t=num_classes, criterion='maxclust')

    def plot_dendrogram(self, linkage, **kwargs):
        """
        plot a dendrogram for the linkage matrix with leaf labels. The kwargs go
        directly into the scipy function :py:func:`scipy.cluster.hierarchy.dendrogram`
        """
        return dendrogram(linkage, **kwargs)

    def pseudo_time(self, start):
        """
        Returns the pseudo times along the manifold for the given starting point
        start to all other points (including start).

        If the starting point is not a leaf, we will select a direction randomly
        and go backwards in time for one direction and forward for the other.

        :param int start: The index of the starting point in self.X
        """
        D = self.manifold_corrected_distances<commit_msg>[knn_graph] added knn_graph and restructured a little<commit_after>#===============================================================================
# Copyright (c) 2016, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#
# * Neither the name of paramz.core.constrainable nor the names of its
#   contributors may be used to endorse or promote products derived from
#   this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#===============================================================================

from manifold import distances
from scipy.sparse.csgraph import minimum_spanning_tree, dijkstra
from scipy.sparse import csr_matrix, find, lil_matrix
from scipy.cluster.hierarchy import average, fcluster, dendrogram
from scipy.spatial.distance import pdist, squareform
import numpy as np

class ManifoldCorrection(object):
    def __init__(self, gplvm, distance=distances.mean_embedding_dist):
        """
        Construct a correction class for the BayesianGPLVM given.

        All evaluations on this object are lazy, so do not change attributes
        at runtime in order to have a consistent model.

        :param [GPy.models.BayesianGPLVM,GPy.models.GPLVM] gplvm:
            an optimized GPLVM or BayesianGPLVM model from GPy
        :param func dist: dist(X,G), the distance to use for pairwise distances
            in X using the manifold embedding G
        """
        self.gplvm = gplvm
        self.distance = distance

    @property
    def X(self):
        if getattr(self, '_X', None) is None:
            try:
                self._X = self.gplvm.X.mean
                self._X.mean
            except AttributeError:
                # not bayesian GPLVM
                self._X = self.gplvm.X
            #self._X = self._X * self.gplvm.kern.input_sensitivity()
        return self._X

    @property
    def G(self):
        if getattr(self, '_G', None) is None:
            self._G = self.gplvm.predict_wishard_embedding(self.X)
        return self._G

    @property
    def manifold_corrected_distance_matrix(self):
        """
        Returns the distances between all pairs of inputs, corrected for
        the manifold embedding.
        """
        if getattr(self, '_M', None) is None:
            self._M = csr_matrix(self.distance(self.X, self.G))
        return self._M

    @property
    def minimal_spanning_tree(self):
        """
        Create a minimal spanning tree using the distance correction method given.

        You can explore different distance corrections in manifold.distances.
        """
        if getattr(self, '_mst', None) is None:
            self._mst = minimum_spanning_tree(self.manifold_corrected_distance_matrix)
        return self._mst

    def knn_graph(self, k, include_mst=False):
        """
        Return a k-nearest-neighbour graph with k neighbours.

        Optionally you can add the minimal spanning tree in, in order to
        ensure a fully connected graph. This only adds edges which are not already there,
        so that the connections are made.
        """
        D = self.manifold_corrected_distance_matrix
        idxs = np.argsort(D)
        r = range(D.shape[0])
        idx = idxs[:, :k]
        _distances = lil_matrix(D.shape)
        for neighbours in idx.T:
            _distances[r, neighbours] = D[r, neighbours]
        if include_mst:
            mst = self.minimal_spanning_tree
            for i,j,v in find(mst):
                if _distances[i,j] == 0:
                    _distances[i,j] = v
        return _distances

    def knn_corrected_distances(self, knn_graph):
        """
        Return all distances along the knn_graph given.

        You can get the knn_graph by calling knn_graph on this object.
        """
        return dijkstra(knn_graph, directed=False)

    def knn_corrected_structure(self, knn_graph):
        """
        Return the structure distances, where each edge along knn graph has a
        distance of one, such that the distance just means the number of
        hops to make in order to get from one point to another.

        This can be very helpful in doing structure analysis
        and clustering of the manifold embedded data points.
        """
        return dijkstra(knn_graph, directed=False, unweighted=True)

    @property
    def tree_corrected_distances(self):
        """
        Return the distances summed along the manifold minimal spanning tree.

        This reflects the structure and distances along the manifold in order
        to include the pseudo stretch of the Wishart embedding of the manifold.
        """
        if getattr(self, '_corrected_distances', None) is None:
            self._corrected_distances = dijkstra(self.minimal_spanning_tree, directed=False, return_predecessors=True)
        return self._corrected_distances[0]

    @property
    def tree_corrected_structure(self):
        """
        Return the structure distances, where each edge along the manifold
        minimal spanning tree has a distance of one, such that the
        distance just means the number of hops to make in order to get from
        one point to another. This can be very helpful in doing structure analysis
        and clustering of the manifold embedded data points.
        """
        if getattr(self, '_corrected_structure', None) is None:
            self._corrected_structure = dijkstra(self.minimal_spanning_tree, directed=False, unweighted=True)
        return self._corrected_structure


    @property
    def tree_structure_linkage(self):
        """
        Return the UPGMA linkage matrix based on the correlation structure of
        the manifold embedding MST
        """
        if getattr(self, '_Slinkage', None) is None:
            self._Slinkage = average(pdist(self.tree_corrected_structure, metric='correlation'))
        return self._Slinkage

    @property
    def tree_distance_linkage(self):
        """
        Return the UPGMA linkage matrix for the manifold distances
        """
        if getattr(self, '_Mlinkage', None) is None:
            self._Mlinkage = average(squareform(self.tree_corrected_distances, ))
        return self._Mlinkage

    def cluster(self, linkage, num_classes):
        """
        Cluster the linkage matrix into num_classes number of classes.
        """
        return fcluster(linkage, t=num_classes, criterion='maxclust')

    def plot_dendrogram(self, linkage, **kwargs):
        """
        plot a dendrogram for the linkage matrix with leaf labels. The kwargs go
        directly into the scipy function :py:func:`scipy.cluster.hierarchy.dendrogram`
        """
        return dendrogram(linkage, **kwargs)

    def pseudo_time(self, start):
        """
        Returns the pseudo times along the manifold for the given starting point
        start to all other points (including start).

        If the starting point is not a leaf, we will select a direction randomly
        and go backwards in time for one direction and forward for the other.

        :param int start: The index of the starting point in self.X
        """
        D = self.manifold_corrected_distances
{'fraction_non_alphanumeric': 0.08226559693449886, 'fraction_numerical': 0.0008382229673093043, 'mean_word_length': 2.783238958097395, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7225491', 'n_tokens_mistral': 4549, 'n_tokens_neox': 4202, 'n_words': 1705}