def adjacency ( tree ) : dd = ids ( tree ) N = len ( dd ) A = np . zeros ( ( N , N ) ) def _adj ( node ) : if np . isscalar ( node ) : return elif isinstance ( node , tuple ) and len ( node ) == 2 : A [ dd [ node ] , dd [ node [ 0 ] ] ] = 1 A [ dd [ node [ 0 ] ] , dd [ node ] ] = 1 _adj ( node [ 0 ] ) A [ dd [ node ] , dd [ node [ 1 ] ] ] = 1 A [ dd [ node [ 1 ] ] , dd [ node ] ] = 1 _adj ( node [ 1 ] ) _adj ( tree ) return A
construct adjacency matrix python
Construct the adjacency matrix of the tree : param tree : : return :
def adjacency(tree):
    """
    Construct the adjacency matrix of the tree
    :param tree:
    :return:
    """
    dd = ids(tree)
    N = len(dd)
    A = np.zeros((N, N))

    def _adj(node):
        if np.isscalar(node):
            return
        elif isinstance(node, tuple) and len(node) == 2:
            A[dd[node], dd[node[0]]] = 1
            A[dd[node[0]], dd[node]] = 1
            _adj(node[0])

            A[dd[node], dd[node[1]]] = 1
            A[dd[node[1]], dd[node]] = 1
            _adj(node[1])

    _adj(tree)
    return A