Ejemplo n.º 1
0
def test_minimum_spanning_tree():
    adjacency_matrix = np.array([[0, 11, 13, 12], [11, 0, 0, 14],
                                 [13, 0, 0, 10], [12, 14, 10, 0]])
    g = UndirectedGraph(adjacency_matrix)
    t = g.minimum_spanning_tree(root_vertex=0)
    assert t.n_edges == 3
    assert_allclose(
        t.adjacency_matrix.todense(),
        csr_matrix(([11., 12., 10.], ([0, 0, 3], [1, 3, 2])),
                   shape=(4, 4)).todense())
    assert t.get_adjacency_list() == [[1, 3], [], [], [2]]
    assert t.predecessors_list == [None, 0, 3, 0]
Ejemplo n.º 2
0
def test_minimum_spanning_tree():
    adjacency_matrix = np.array([[0, 11, 13, 12],
                                 [11, 0, 0, 14],
                                 [13, 0, 0, 10],
                                 [12, 14, 10, 0]])
    g = UndirectedGraph(adjacency_matrix)
    t = g.minimum_spanning_tree(root_vertex=0)
    assert t.n_edges == 3
    assert_allclose(t.adjacency_matrix.todense(),
                    csr_matrix(([11., 12., 10.], ([0, 0, 3], [1, 3, 2])),
                               shape=(4, 4)).todense())
    assert t.get_adjacency_list() == [[1, 3], [], [], [2]]
    assert t.predecessors_list == [None, 0, 3, 0]
Ejemplo n.º 3
0
def _compute_minimum_spanning_tree(shapes, root_vertex, level_str, verbose):
    # initialize edges and weights matrix
    n_vertices = shapes[0].n_points
    n_edges = nchoosek(n_vertices, 2)
    weights = np.zeros((n_vertices, n_vertices))
    edges = np.empty((n_edges, 2), dtype=np.int32)

    # fill edges and weights
    e = -1
    for i in range(n_vertices - 1):
        for j in range(i + 1, n_vertices, 1):
            # edge counter
            e += 1

            # print progress
            if verbose:
                print_dynamic(
                    '{}Computing complete graph`s weights - {}'.format(
                        level_str,
                        progress_bar_str(float(e + 1) / n_edges,
                                         show_bar=False)))

            # fill in edges
            edges[e, 0] = i
            edges[e, 1] = j

            # create data matrix of edge
            diffs_x = [s.points[i, 0] - s.points[j, 0] for s in shapes]
            diffs_y = [s.points[i, 1] - s.points[j, 1] for s in shapes]
            coords = np.array([diffs_x, diffs_y])

            # compute mean
            m = np.mean(coords, axis=1)

            # compute covariance
            c = np.cov(coords)

            # get weight
            for im in range(len(shapes)):
                weights[i, j] += -np.log(
                    multivariate_normal.pdf(coords[:, im], mean=m, cov=c))
            weights[j, i] = weights[i, j]

    # create undirected graph
    complete_graph = UndirectedGraph(edges)

    if verbose:
        print_dynamic('{}Minimum spanning graph computed.\n'.format(level_str))

    # compute minimum spanning graph
    return complete_graph.minimum_spanning_tree(weights, root_vertex)
Ejemplo n.º 4
0
def _compute_minimum_spanning_tree(shapes, root_vertex, level_str, verbose):
    # initialize edges and weights matrix
    n_vertices = shapes[0].n_points
    n_edges = nchoosek(n_vertices, 2)
    weights = np.zeros((n_vertices, n_vertices))
    edges = np.empty((n_edges, 2), dtype=np.int32)

    # fill edges and weights
    e = -1
    for i in range(n_vertices-1):
        for j in range(i+1, n_vertices, 1):
            # edge counter
            e += 1

            # print progress
            if verbose:
                print_dynamic('{}Computing complete graph`s weights - {}'.format(
                    level_str,
                    progress_bar_str(float(e + 1) / n_edges,
                                     show_bar=False)))

            # fill in edges
            edges[e, 0] = i
            edges[e, 1] = j

            # create data matrix of edge
            diffs_x = [s.points[i, 0] - s.points[j, 0] for s in shapes]
            diffs_y = [s.points[i, 1] - s.points[j, 1] for s in shapes]
            coords = np.array([diffs_x, diffs_y])

            # compute mean
            m = np.mean(coords, axis=1)

            # compute covariance
            c = np.cov(coords)

            # get weight
            for im in range(len(shapes)):
                weights[i, j] += -np.log(multivariate_normal.pdf(coords[:, im],
                                                                 mean=m, cov=c))
            weights[j, i] = weights[i, j]

    # create undirected graph
    complete_graph = UndirectedGraph(edges)

    if verbose:
        print_dynamic('{}Minimum spanning graph computed.\n'.format(level_str))

    # compute minimum spanning graph
    return complete_graph.minimum_spanning_tree(weights, root_vertex)
Ejemplo n.º 5
0
def test_minimum_spanning_tree():
    adjacency_array = np.array([[3, 1], [2, 3], [0, 3], [2, 0], [0, 1]])
    weights = np.array([[0, 11, 13, 12], [11, 0, 0, 14], [13, 0, 0, 10],
                        [12, 14, 10, 0]])
    g = UndirectedGraph(adjacency_array)
    t = g.minimum_spanning_tree(weights, root_vertex=0)
    assert t.n_edges == 3
    assert_allclose(t.adjacency_array, np.array([[0, 1], [0, 3], [3, 2]]))
    assert t.adjacency_list == [[1, 3], [], [], [2]]
    assert_allclose(
        t.get_adjacency_matrix(),
        np.array([[False, True, False, True], [False, False, False, False],
                  [False, False, False, False], [False, False, True, False]]))
    assert t.predecessors_list == [None, 0, 3, 0]
Ejemplo n.º 6
0
def _compute_minimum_spanning_tree(shapes,
                                   root_vertex=0,
                                   prefix='',
                                   verbose=False):
    # initialize weights matrix
    n_vertices = shapes[0].n_points
    weights = np.zeros((n_vertices, n_vertices))

    # print progress if requested
    range1 = range(n_vertices - 1)
    if verbose:
        range1 = print_progress(
            range1,
            end_with_newline=False,
            prefix='{}Deformation graph - Computing complete graph`s '
            'weights'.format(prefix))

    # compute weights
    for i in range1:
        for j in range(i + 1, n_vertices, 1):
            # create data matrix of edge
            diffs_x = [s.points[i, 0] - s.points[j, 0] for s in shapes]
            diffs_y = [s.points[i, 1] - s.points[j, 1] for s in shapes]
            coords = np.array([diffs_x, diffs_y])

            # compute mean and covariance
            m = np.mean(coords, axis=1)
            c = np.cov(coords)

            # get weight
            for im in range(len(shapes)):
                weights[i, j] += -np.log(
                    multivariate_normal.pdf(coords[:, im], mean=m, cov=c))
            weights[j, i] = weights[i, j]

    # create undirected graph
    complete_graph = UndirectedGraph(weights)

    if verbose:
        print_dynamic('{}Deformation graph - Minimum spanning graph '
                      'computed.\n'.format(prefix))

    # compute minimum spanning graph
    return complete_graph.minimum_spanning_tree(root_vertex)
Ejemplo n.º 7
0
def test_increment():
    # arguments values
    mode_values = ["concatenation", "subtraction"]
    n_features_per_vertex_values = [2, 3]
    sparse_values = [True, False]
    n_components_values = [None, 30]

    # create graph
    n_vertices = 6
    edges = np.array([[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0]])
    graphs = [
        DirectedGraph.init_from_edges(edges, n_vertices),
        UndirectedGraph(np.zeros((n_vertices, n_vertices))),
    ]

    for n_features_per_vertex in n_features_per_vertex_values:
        # create samples
        n_samples = 100
        samples = []
        for i in range(n_samples):
            samples.append(np.random.rand(n_vertices * n_features_per_vertex))

        for graph in graphs:
            for mode in mode_values:
                for sparse in sparse_values:
                    for n_components in n_components_values:
                        # Incremental GMRF
                        gmrf1 = GMRFVectorModel(
                            samples[:50],
                            graph,
                            mode=mode,
                            sparse=sparse,
                            n_components=n_components,
                            dtype=np.float64,
                            incremental=True,
                        )
                        gmrf1.increment(samples[50::])

                        # Non incremental GMRF
                        gmrf2 = GMRFVectorModel(
                            samples,
                            graph,
                            mode=mode,
                            sparse=sparse,
                            n_components=n_components,
                            dtype=np.float64,
                        )

                        # Compare
                        if sparse:
                            assert_array_almost_equal(
                                gmrf1.precision.todense(),
                                gmrf2.precision.todense())
                        assert_array_almost_equal(gmrf1.mean_vector,
                                                  gmrf2.mean_vector)
Ejemplo n.º 8
0
def _compute_minimum_spanning_tree(shapes, root_vertex=0, prefix='',
                                   verbose=False):
    # initialize weights matrix
    n_vertices = shapes[0].n_points
    weights = np.zeros((n_vertices, n_vertices))

    # print progress if requested
    range1 = range(n_vertices-1)
    if verbose:
        range1 = print_progress(
            range1, end_with_newline=False,
            prefix='{}Deformation graph - Computing complete graph`s '
                   'weights'.format(prefix))

    # compute weights
    for i in range1:
        for j in range(i+1, n_vertices, 1):
            # create data matrix of edge
            diffs_x = [s.points[i, 0] - s.points[j, 0] for s in shapes]
            diffs_y = [s.points[i, 1] - s.points[j, 1] for s in shapes]
            coords = np.array([diffs_x, diffs_y])

            # compute mean and covariance
            m = np.mean(coords, axis=1)
            c = np.cov(coords)

            # get weight
            for im in range(len(shapes)):
                weights[i, j] += -np.log(multivariate_normal.pdf(coords[:, im],
                                                                 mean=m, cov=c))
            weights[j, i] = weights[i, j]

    # create undirected graph
    complete_graph = UndirectedGraph(weights)

    if verbose:
        print_dynamic('{}Deformation graph - Minimum spanning graph '
                      'computed.\n'.format(prefix))

    # compute minimum spanning graph
    return complete_graph.minimum_spanning_tree(root_vertex)
Ejemplo n.º 9
0
def test_minimum_spanning_tree():
    adjacency_array = np.array([[3, 1],
                                [2, 3],
                                [0, 3],
                                [2, 0],
                                [0, 1]])
    weights = np.array([[0, 11, 13, 12],
                        [11, 0, 0, 14],
                        [13, 0, 0, 10],
                        [12, 14, 10, 0]])
    g = UndirectedGraph(adjacency_array)
    t = g.minimum_spanning_tree(weights, root_vertex=0)
    assert t.n_edges == 3
    assert_allclose(t.adjacency_array, np.array([[0, 1], [0, 3], [3, 2]]))
    assert t.adjacency_list == [[1, 3], [], [], [2]]
    assert_allclose(t.get_adjacency_matrix(),
                    np.array([[False, True, False, True],
                              [False, False, False, False],
                              [False, False, False, False],
                              [False, False, True, False]]))
    assert t.predecessors_list == [None, 0, 3, 0]
def test_mahalanobis_distance():
    # arguments values
    mode_values = ['concatenation', 'subtraction']
    n_features_per_vertex_values = [2, 3]
    sparse_values = [True, False]
    subtract_mean_values = [True, False]
    n_components_values = [None, 30]

    # create graph
    n_vertices = 6
    edges = np.array([[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0]])
    graphs = [
        DirectedGraph.init_from_edges(edges, n_vertices),
        UndirectedGraph(np.zeros((n_vertices, n_vertices)))
    ]

    for n_features_per_vertex in n_features_per_vertex_values:
        # create samples
        n_samples = 50
        samples = []
        for i in range(n_samples):
            samples.append(
                PointCloud(np.random.rand(n_vertices, n_features_per_vertex)))
        test_sample = PointCloud(
            np.random.rand(n_vertices, n_features_per_vertex))

        for graph in graphs:
            for mode in mode_values:
                for sparse in sparse_values:
                    for n_components in n_components_values:
                        # train GMRF
                        gmrf = GMRFModel(samples,
                                         graph,
                                         mode=mode,
                                         sparse=sparse,
                                         n_components=n_components,
                                         dtype=np.float64)

                        for subtract_mean in subtract_mean_values:
                            # compute costs
                            if graph.n_edges == 0:
                                cost1 = _compute_sum_cost_block_diagonal(
                                    samples, test_sample, graph,
                                    n_features_per_vertex, subtract_mean)
                            else:
                                cost1 = _compute_sum_cost_block_sparse(
                                    samples, test_sample, graph,
                                    n_features_per_vertex, subtract_mean, mode)
                            cost2 = gmrf.mahalanobis_distance(
                                test_sample, subtract_mean=subtract_mean)
                            assert_almost_equal(cost1, cost2)
Ejemplo n.º 11
0
    def __init__(self,
                 adjacency_array_appearance=None,
                 gaussian_per_patch=True,
                 adjacency_array_deformation=None,
                 root_vertex_deformation=None,
                 adjacency_array_shape=None,
                 features=no_op,
                 patch_shape=(17, 17),
                 normalization_diagonal=None,
                 n_levels=2,
                 downscale=2,
                 scaled_shape_models=False,
                 use_procrustes=True,
                 max_shape_components=None,
                 n_appearance_parameters=None):
        # check parameters
        checks.check_n_levels(n_levels)
        checks.check_downscale(downscale)
        checks.check_normalization_diagonal(normalization_diagonal)
        max_shape_components = checks.check_max_components(
            max_shape_components, n_levels, 'max_shape_components')
        features = checks.check_features(features, n_levels)
        n_appearance_parameters = _check_n_parameters(
            n_appearance_parameters, n_levels, 'n_appearance_parameters')

        # appearance graph
        if adjacency_array_appearance is None:
            self.graph_appearance = None
        elif adjacency_array_appearance == 'yorgos':
            self.graph_appearance = 'yorgos'
        else:
            self.graph_appearance = UndirectedGraph(adjacency_array_appearance)

        # shape graph
        if adjacency_array_shape is None:
            self.graph_shape = None
        else:
            self.graph_shape = UndirectedGraph(adjacency_array_shape)

        # check adjacency_array_deformation, root_vertex_deformation
        if adjacency_array_deformation is None:
            self.graph_deformation = None
            if root_vertex_deformation is None:
                self.root_vertex = 0
        else:
            if root_vertex_deformation is None:
                self.graph_deformation = DirectedGraph(
                    adjacency_array_deformation)
            else:
                self.graph_deformation = Tree(adjacency_array_deformation,
                                              root_vertex_deformation)

        # store parameters
        self.features = features
        self.patch_shape = patch_shape
        self.normalization_diagonal = normalization_diagonal
        self.n_levels = n_levels
        self.downscale = downscale
        self.scaled_shape_models = scaled_shape_models
        self.max_shape_components = max_shape_components
        self.n_appearance_parameters = n_appearance_parameters
        self.use_procrustes = use_procrustes
        self.gaussian_per_patch = gaussian_per_patch
Ejemplo n.º 12
0
def test_create_graph_exception():
    adj = np.array([[0, 1, 3], [0, 2, 4]])
    with raises(ValueError):
        UndirectedGraph(adj)
Ejemplo n.º 13
0
    ]
)
point = np.array([[10, 10]])

# Define undirected graph and pointgraph
adj_undirected = np.array(
    [
        [0, 1, 1, 0, 0, 0],
        [1, 0, 1, 1, 0, 0],
        [1, 1, 0, 0, 1, 0],
        [0, 1, 0, 0, 1, 1],
        [0, 0, 1, 1, 0, 0],
        [0, 0, 0, 1, 0, 0],
    ]
)
g_undirected = UndirectedGraph(adj_undirected)
pg_undirected = PointUndirectedGraph(points, adj_undirected)

# Define directed graph and pointgraph
adj_directed = csr_matrix(
    ([1] * 8, ([1, 2, 1, 2, 1, 2, 3, 3], [0, 0, 2, 1, 3, 4, 4, 5])), shape=(6, 6)
)
g_directed = DirectedGraph(adj_directed)
pg_directed = PointDirectedGraph(points, adj_directed)

# Define tree and pointtree
adj_tree = np.array(
    [
        [0, 1, 1, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 1, 1, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 1, 0, 0, 0],
Ejemplo n.º 14
0
def test_create_graph_exception():
    adj = np.array([[0, 1, 3], [0, 2, 4]])
    UndirectedGraph(adj)
Ejemplo n.º 15
0
import numpy as np
from numpy.testing import assert_allclose
from nose.tools import raises

from menpo.shape import UndirectedGraph, DirectedGraph, Tree

# Define adjacency arrays
adj_undirected = np.array([[0, 1], [0, 2], [1, 2], [1, 3], [2, 4], [3, 4],
                           [3, 5]])
g_undirected = UndirectedGraph(adj_undirected)
adj_directed = np.array([[1, 0], [2, 0], [1, 2], [2, 1], [1, 3], [2, 4],
                         [3, 4], [3, 5]])
g_directed = DirectedGraph(adj_directed)
adj_tree = np.array([[0, 1], [0, 2], [1, 3], [1, 4], [2, 5], [3, 6], [4, 7],
                     [5, 8]])
g_tree = Tree(adj_tree, 0)


@raises(ValueError)
def test_create_graph_exception():
    adj = np.array([[0, 1, 3], [0, 2, 4]])
    UndirectedGraph(adj)


@raises(ValueError)
def test_create_tree_exception_1():
    adj = np.array([[0, 1], [0, 2], [1, 3], [1, 4], [2, 5], [3, 6], [4, 7],
                    [5, 8], [0, 4]])
    Tree(adj, 0)