# -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Graph utilities
===============

A module containing several graph utility functions.
"""

import numpy as np

try:
    from scipy.sparse import issparse
except ImportError:
    def issparse(*args, **kwargs):
        return False


def get_edges(adjacency_mat):
    if issparse(adjacency_mat):
        func = _sparse_get_edges
    else:
        func = _get_edges

    for result in func(adjacency_mat):
        yield result


def _sparse_get_edges(adjacency_mat):
    # Each non zero value in a COO matrix is stored in (row, col, value)
    # format
    coo_mat = adjacency_mat.tocoo()
    return zip(coo_mat.row, coo_mat.col)


def _get_edges(adjacency_mat):
    # Get indices of all non zero values
    i, j = np.where(adjacency_mat)

    return zip(i, j)


def straight_line_vertices(adjacency_mat, node_coords, directed=False):
    """
    Generate the vertices for straight lines between nodes.

    If it is a directed graph, it also generates the vertices which can be
    passed to an :class:`ArrowVisual`.

    Parameters
    ----------
    adjacency_mat : array
        The adjacency matrix of the graph
    node_coords : array
        The current coordinates of all nodes in the graph
    directed : bool
        Wether the graph is directed. If this is true it will also generate
        the vertices for arrows which can be passed to :class:`ArrowVisual`.

    Returns
    -------
    vertices : tuple
        Returns a tuple containing containing (`line_vertices`,
        `arrow_vertices`)
    """

    if (not issparse(adjacency_mat) and not isinstance(adjacency_mat,
                                                       np.ndarray)):
        adjacency_mat = np.array(adjacency_mat, float)

    if (adjacency_mat.ndim != 2 or adjacency_mat.shape[0] !=
            adjacency_mat.shape[1]):
        raise ValueError("Adjacency matrix should be square.")

    arrows = []

    edges = np.array(list(get_edges(adjacency_mat)))
    line_vertices = node_coords[edges.ravel()]

    arrows = np.array(arrows).reshape((len(arrows)/2, 4))

    return line_vertices, arrows


def rescale_layout(pos, scale=1):
    """
    Normalize the given coordinate list to the range [0, `scale`].

    Parameters
    ----------
    pos : array
        Coordinate list
    scale : number
        The upperbound value for the coordinates range

    Returns
    -------
    pos : array
        The rescaled (normalized) coordinates in the range [0, `scale`].

    Notes
    -----
    Changes `pos` in place.
    """

    pos -= pos.min(axis=0)
    pos *= scale / pos.max()

    return pos

@@ -232,16 +232,34 @@
 s.%0A%22%22%22%0A%0A
+import itertools%0A%0A
 import n
@@ -915,24 +915,791 @@
 zip(i, j)%0A%0A%0A
+def get_directed_edges(adjacency_mat):%0A    if issparse(adjacency_mat):%0A        func = _sparse_get_directed_edges%0A    else:%0A        func = _get_directed_edges%0A%0A    for result in func(adjacency_mat):%0A        print(%22Directed%22, result)%0A        yield result%0A%0A%0Adef _sparse_get_directed_edges(adjacency_mat):%0A    iu = np.triu_indices_from(adjacency_mat, 1)%0A    il = np.tril_indices_from(adjacency_mat)%0A%0A    lower = adjacency_mat.copy()%0A    lower%5Bil%5D = 0%0A%0A    adjacency_mat%5Biu%5D = 0%0A%0A    return itertools.chain(%0A        _sparse_get_edges(adjacency_mat),%0A        _sparse_get_edges(lower)%0A    )%0A%0A%0Adef _get_directed_edges(adjacency_mat):%0A    upper = np.triu(adjacency_mat, k=1)%0A    lower = np.tril(adjacency_mat)%0A%0A    return itertools.chain(get_edges(upper), get_edges(lower))%0A%0A%0A
 def straight
@@ -2810,14 +2810,32 @@
 rrow
-s = 
+_vertices = np.array(
 %5B%5D
+)
 %0A%0A  
@@ -2941,33 +2941,180 @@
     
-arrows = np.array(arrows)
+if directed:%0A        arrows = np.array(list(get_directed_edges(adjacency_mat)))%0A        arrow_vertices = node_coords%5Barrows.ravel()%5D%0A        arrow_vertices = arrow_vertices
 .res
@@ -3128,16 +3128,24 @@
 en(arrow
+_vertice
 s)/2, 4)
@@ -3178,16 +3178,24 @@
 s, arrow
+_vertice
 s%0A%0A%0Adef 

Add support for directed edges again