Exemplo n.º 1
0
def main():
    data = load_data()

    if args.edges == 0:
        ppiGraph = nx.Graph(data.humanppi, name="HumanPPI")
    else:
        ppiGraph = nx.Graph(data.humanppi[0:args.edges], name="HumanPPI")
    draw_kwargs = dict(node_size=5, font_size=6,
                       with_labels=False, linewidths=0.1, width=0.2)
    layout_kw = dict(iterations=args.iterations)
    img_title = 'Nodes: %i  Edges: %i  Iterations: %i  Runtime: %s'

    if args.iterations is None:
        # Number of iters will be set to 10, check the get_iterations method.
        iters = get_iterations()

        for iteration in iters:
            start_time = time.time()

            fig = plt.figure(figsize=(10, 10))
            ax = fig.add_subplot(111)
            nx.draw(ppiGraph, pos=nx.spring_layout(
                ppiGraph, iterations=iteration), **draw_kwargs)

            run_time = time.time() - start_time
            runtime_str = str(round(run_time, 2)) + ' seconds'

            print("Iterations: %i  Runt-time: %s" % (iteration, runtime_str))

            subs = (len(ppiGraph), args.edges, iteration, runtime_str)
            ax.set_title(img_title % subs)
            filepath = 'report/graphs' + '/' + \
                       zeros(iteration, padlength=4) + '.png'
            plt.savefig(filepath, bbox_inches='tight')
            print("Done! Saved at : " + filepath)

            fig.clf()
            plt.close()
    else:
        start_time = time.time()
        fig = plt.figure(figsize=(10, 10))
        ax = fig.add_subplot(111)
        nx.draw(ppiGraph, pos=nx.spring_layout(
            ppiGraph, **layout_kw), **draw_kwargs)

        runtime = time.time() - start_time
        runtime_str = str(round(runtime, 2)) + ' seconds'

        subs = (len(ppiGraph), args.edges, args.iterations, runtime_str)
        ax.set_title(img_title % subs)

        filepath = 'report/graphs' + '/' + \
                   zeros(args.iterations, padlength=4) + '.png'
        plt.savefig(filepath, bbox_inches='tight')
        print("Done! Saved at " + filepath)
        fig.clf()
        plt.close()
Exemplo n.º 2
0
def plot_graph(graph, protein, Tc, nodecolor, nodesymbol):

    fig = plt.figure(figsize=(20,20))
    ax = fig.add_subplot(111)
    
    drawkwargs = {'font_size': 10,\
                  'linewidths': 1,\
                  'width': 2,\
                  'with_labels': True,\
                  'node_size': 700,\
                  'node_color':nodecolor,\
                  'node_shape':'o',\
                  'style':'solid',\
                  'alpha':1,\
                  'cmap': mpl.cm.jet}

    pos=nx.spring_layout(graph, iterations=200)
    nx.draw(graph, pos, **drawkwargs )

    if protein in Tc:
        string = "Protein: %i  Cancer"
        string_s = (protein)
        title=string%string_s
    else:
        string = "Protein: %i  Non-Cancer"
        string_s = (protein)
        title=string%string_s
    
    ax.set_title(title)
    filepath = 'images'+'/'+zeros(protein, padlength=4)+'.jpg'
    plt.savefig(filepath,  bbox_inches='tight')
    print 'Written to: '+filepath
    fig.clf()
    plt.close()
    del fig
Exemplo n.º 3
0
def make_function_graphs(data):
    fgraph = nx.Graph(data.functions, name='Functions')

    drawkwargs = {'font_size': 10,\
                  'linewidths': 1,\
                  'width': 2,\
                  'with_labels': True,\
                  'node_size': 700,\
                  'node_color':'w',\
                  'node_shape':'o',\
                  'style':'solid',\
                  'alpha':1,\
                  'cmap': mpl.cm.jet}

    filepath = 'images'+'/functions/'

    for function in data.functions_only:
        g = nx.Graph() 
        nbrs = fgraph.neighbors(function)
        edges_to_add = [tuple([function, i]) for i in nbrs]
        g.add_edges_from(edges_to_add)

        fig = plt.figure(figsize=(20,20))
        ax = fig.add_subplot(111)
        pos=nx.spring_layout(g, iterations=20)
        nx.draw(g, pos, **drawkwargs )
        ax.set_title(function)

        filepathname = filepath+zeros(function, padlength=4)+'.jpg'
        plt.savefig(filepathname,  bbox_inches='tight')
        print 'Written to: '+filepathname
        fig.clf()
        plt.close()
        del fig
Exemplo n.º 4
0
def plot_graph(graph, protein, Tc, nodecolor, nodesymbol):

    fig = plt.figure(figsize=(20, 20))
    ax = fig.add_subplot(111)

    drawkwargs = {'font_size': 10,\
                  'linewidths': 1,\
                  'width': 2,\
                  'with_labels': True,\
                  'node_size': 700,\
                  'node_color':nodecolor,\
                  'node_shape':'o',\
                  'style':'solid',\
                  'alpha':1,\
                  'cmap': mpl.cm.jet}

    pos = nx.spring_layout(graph, iterations=200)
    nx.draw(graph, pos, **drawkwargs)

    if protein in Tc:
        string = "Protein: %i  Cancer"
        string_s = (protein)
        title = string % string_s
    else:
        string = "Protein: %i  Non-Cancer"
        string_s = (protein)
        title = string % string_s

    ax.set_title(title)
    filepath = 'images' + '/' + zeros(protein, padlength=4) + '.jpg'
    plt.savefig(filepath, bbox_inches='tight')
    print 'Written to: ' + filepath
    fig.clf()
    plt.close()
    del fig
Exemplo n.º 5
0
def make_function_graphs(data):
    fgraph = nx.Graph(data.functions, name='Functions')

    drawkwargs = {'font_size': 10,\
                  'linewidths': 1,\
                  'width': 2,\
                  'with_labels': True,\
                  'node_size': 700,\
                  'node_color':'w',\
                  'node_shape':'o',\
                  'style':'solid',\
                  'alpha':1,\
                  'cmap': mpl.cm.jet}

    filepath = 'images' + '/functions/'

    for function in data.functions_only:
        g = nx.Graph()
        nbrs = fgraph.neighbors(function)
        edges_to_add = [tuple([function, i]) for i in nbrs]
        g.add_edges_from(edges_to_add)

        fig = plt.figure(figsize=(20, 20))
        ax = fig.add_subplot(111)
        pos = nx.spring_layout(g, iterations=20)
        nx.draw(g, pos, **drawkwargs)
        ax.set_title(function)

        filepathname = filepath + zeros(function, padlength=4) + '.jpg'
        plt.savefig(filepathname, bbox_inches='tight')
        print 'Written to: ' + filepathname
        fig.clf()
        plt.close()
        del fig
Exemplo n.º 6
0
def eye(N, dtype=np.float32):
    """
    Construct a 2D matrix with ones on the diagonal and zeros elsewhere.

    Constructs a matrix in device memory whose diagonal elements
    are set to 1 and non-diagonal elements are set to 0.

    Parameters
    ----------
    N : int
        Number of rows or columns in the output matrix.

    Returns
    -------
    e_gpu : pycuda.gpuarray.GPUArray
        Diagonal matrix of dimensions `[N, N]` with diagonal values
        set to 1.

    Examples
    --------
    >>> import pycuda.driver as drv
    >>> import pycuda.gpuarray as gpuarray
    >>> import pycuda.autoinit
    >>> import numpy as np
    >>> import linalg
    >>> linalg.init()
    >>> N = 5
    >>> e_gpu = linalg.eye(N)
    >>> np.all(e_gpu.get() == np.eye(N))
    True
    >>> e_gpu = linalg.eye(v_gpu, np.complex64)
    >>> np.all(e_gpu.get() == np.eye(N, np.complex64))
    True

    """

    if dtype not in [np.float32, np.float64, np.complex64, np.complex128]:
        raise ValueError("unrecognized type")
    if N <= 0:
        raise ValueError("N must be greater than 0")

    use_double = int(dtype in [np.float64, np.complex128])
    use_complex = int(dtype in [np.complex64, np.complex128])

    # Initialize output matrix:
    e_gpu = misc.zeros((N, N), dtype)

    # Get block/grid sizes:
    dev = misc.get_current_device()
    block_dim, grid_dim = misc.select_block_grid_sizes(dev, e_gpu.shape)

    # Set this to False when debugging to make sure the compiled kernel is
    # not cached:
    cache_dir = None
    eye_mod = SourceModule(eye_template.substitute(use_double=use_double, use_complex=use_complex), cache_dir=cache_dir)

    eye = eye_mod.get_function("eye")
    eye(e_gpu, np.uint32(N), block=block_dim, grid=grid_dim)

    return e_gpu
Exemplo n.º 7
0
def diag(v_gpu):
    """
    Construct a diagonal matrix.

    Constructs a matrix in device memory whose diagonal elements
    correspond to the elements in the specified array; all
    non-diagonal elements are set to 0.

    Parameters
    ----------
    v_obj : pycuda.gpuarray.GPUArray
        Input array of length `n`.

    Returns
    -------
    d_gpu : pycuda.gpuarray.GPUArray
        Diagonal matrix of dimensions `[n, n]`.

    Examples
    --------
    >>> import pycuda.driver as drv
    >>> import pycuda.gpuarray as gpuarray
    >>> import pycuda.autoinit
    >>> import numpy as np
    >>> import linalg
    >>> linalg.init()
    >>> v = np.array([1, 2, 3, 4, 5, 6], np.float32)
    >>> v_gpu = gpuarray.to_gpu(v)
    >>> d_gpu = linalg.diag(v_gpu)
    >>> np.all(d_gpu.get() == np.diag(v))
    True
    >>> v = np.array([1j, 2j, 3j, 4j, 5j, 6j], np.complex64)
    >>> v_gpu = gpuarray.to_gpu(v)
    >>> d_gpu = linalg.diag(v_gpu)
    >>> np.all(d_gpu.get() == np.diag(v))
    True

    """

    if v_gpu.dtype not in [np.float32, np.float64, np.complex64,
                           np.complex128]:
        raise ValueError('unrecognized type')

    if len(v_gpu.shape) > 1:
        raise ValueError('input array cannot be multidimensional')

    use_double = int(v_gpu.dtype in [np.float64, np.complex128])
    use_complex = int(v_gpu.dtype in [np.complex64, np.complex128])

    # Initialize output matrix:
    d_gpu = misc.zeros((v_gpu.size, v_gpu.size), v_gpu.dtype)

    # Get block/grid sizes:
    dev = misc.get_current_device()
    block_dim, grid_dim = misc.select_block_grid_sizes(dev, d_gpu.shape)

    # Set this to False when debugging to make sure the compiled kernel is
    # not cached:
    cache_dir=None
    diag_mod = \
             SourceModule(diag_template.substitute(use_double=use_double,
                                                   use_complex=use_complex),
                          cache_dir=cache_dir)

    diag = diag_mod.get_function("diag")
    diag(v_gpu, d_gpu, np.uint32(v_gpu.size),
         block=block_dim,
         grid=grid_dim)

    return d_gpu
Exemplo n.º 8
0
def diag(v_gpu):
    """
    Construct a diagonal matrix if input array is one-dimensional,
    or extracts diagonal entries of a two-dimensional array.

    --- If input-array is one-dimensional: 
    Constructs a matrix in device memory whose diagonal elements
    correspond to the elements in the specified array; all
    non-diagonal elements are set to 0.
    
    --- If input-array is two-dimensional: 
    Constructs an array in device memory whose elements
    correspond to the elements along the main-diagonal of the specified 
    array.

    Parameters
    ----------
    v_obj : pycuda.gpuarray.GPUArray
            Input array of shape `(n,m)`.

    Returns
    -------
    d_gpu : pycuda.gpuarray.GPUArray
            ---If v_obj has shape `(n,1)`, output is 
               diagonal matrix of dimensions `[n, n]`.
            ---If v_obj has shape `(n,m)`, output is 
               array of length `min(n,m)`.

    Examples
    --------
    >>> import pycuda.driver as drv
    >>> import pycuda.gpuarray as gpuarray
    >>> import pycuda.autoinit
    >>> import numpy as np
    >>> import linalg
    >>> linalg.init()
    >>> v = np.array([1, 2, 3, 4, 5, 6], np.float32)
    >>> v_gpu = gpuarray.to_gpu(v)
    >>> d_gpu = linalg.diag(v_gpu)
    >>> np.all(d_gpu.get() == np.diag(v))
    True
    >>> v = np.array([1j, 2j, 3j, 4j, 5j, 6j], np.complex64)
    >>> v_gpu = gpuarray.to_gpu(v)
    >>> d_gpu = linalg.diag(v_gpu)
    >>> np.all(d_gpu.get() == np.diag(v))
    True
    >>> v = np.array([[1., 2., 3.],[4., 5., 6.]], np.float64)
    >>> v_gpu = gpuarray.to_gpu(v)
    >>> d_gpu = linalg.diag(v_gpu)
    >>> d_gpu
    array([ 1.,  5.])

    """

    if v_gpu.dtype not in [np.float32, np.float64, np.complex64,
                           np.complex128]:
        raise ValueError('unrecognized type')

    if (len(v_gpu.shape) > 1) and (len(v_gpu.shape) < 3):
        # Since CUDA assumes that arrays are stored in column-major
        # format, the input matrix is assumed to be transposed:
        n, m = v_gpu.shape
        square = (n == m)

        # Allocate the output array
        d_gpu = gpuarray.empty(min(m, n), v_gpu.dtype.type)

        diag_kernel = el.ElementwiseKernel("double *x, double *y, int z", "y[i] = x[(z+1)*i]", "diakernel")
        diag_kernel(v_gpu,d_gpu,max(m,n))

        return d_gpu
    elif len(v_gpu.shape) >= 3:
        raise ValueError('input array cannot have greater than 2-dimensions')

    use_double = int(v_gpu.dtype in [np.float64, np.complex128])
    use_complex = int(v_gpu.dtype in [np.complex64, np.complex128])

    # Initialize output matrix:
    d_gpu = misc.zeros((v_gpu.size, v_gpu.size), v_gpu.dtype)

    # Get block/grid sizes:
    dev = misc.get_current_device()
    block_dim, grid_dim = misc.select_block_grid_sizes(dev, d_gpu.shape)

    # Set this to False when debugging to make sure the compiled kernel is
    # not cached:
    cache_dir=None
    diag_mod = \
             SourceModule(diag_template.substitute(use_double=use_double,
                                                   use_complex=use_complex),
                          cache_dir=cache_dir)

    diag = diag_mod.get_function("diag")
    diag(v_gpu, d_gpu, np.uint32(v_gpu.size),
         block=block_dim,
         grid=grid_dim)

    return d_gpu
Exemplo n.º 9
0
def eye(N, dtype=np.float32):
    """
    Construct a 2D matrix with ones on the diagonal and zeros elsewhere.

    Constructs a matrix in device memory whose diagonal elements
    are set to 1 and non-diagonal elements are set to 0.

    Parameters
    ----------
    N : int
        Number of rows or columns in the output matrix.

    Returns
    -------
    e_gpu : pycuda.gpuarray.GPUArray
        Diagonal matrix of dimensions `[N, N]` with diagonal values
        set to 1.

    Examples
    --------
    >>> import pycuda.driver as drv
    >>> import pycuda.gpuarray as gpuarray
    >>> import pycuda.autoinit
    >>> import numpy as np
    >>> import linalg
    >>> linalg.init()
    >>> N = 5
    >>> e_gpu = linalg.eye(N)
    >>> np.all(e_gpu.get() == np.eye(N))
    True
    >>> e_gpu = linalg.eye(v_gpu, np.complex64)
    >>> np.all(e_gpu.get() == np.eye(N, np.complex64))
    True

    """

    if dtype not in [np.float32, np.float64, np.complex64, np.complex128]:
        raise ValueError('unrecognized type')
    if N <= 0:
        raise ValueError('N must be greater than 0')

    use_double = int(dtype in [np.float64, np.complex128])
    use_complex = int(dtype in [np.complex64, np.complex128])

    # Initialize output matrix:
    e_gpu = misc.zeros((N, N), dtype)

    # Get block/grid sizes:
    dev = misc.get_current_device()
    block_dim, grid_dim = misc.select_block_grid_sizes(dev, e_gpu.shape)

    # Set this to False when debugging to make sure the compiled kernel is
    # not cached:
    cache_dir = None
    eye_mod = \
             SourceModule(eye_template.substitute(use_double=use_double,
                                                   use_complex=use_complex),
                          cache_dir=cache_dir)

    eye = eye_mod.get_function("eye")
    eye(e_gpu, np.uint32(N), block=block_dim, grid=grid_dim)

    return e_gpu
Exemplo n.º 10
0
def diag(v_gpu):
    """
    Construct a diagonal matrix.

    Constructs a matrix in device memory whose diagonal elements
    correspond to the elements in the specified array; all
    non-diagonal elements are set to 0.

    Parameters
    ----------
    v_obj : pycuda.gpuarray.GPUArray
        Input array of length `n`.

    Returns
    -------
    d_gpu : pycuda.gpuarray.GPUArray
        Diagonal matrix of dimensions `[n, n]`.

    Examples
    --------
    >>> import pycuda.driver as drv
    >>> import pycuda.gpuarray as gpuarray
    >>> import pycuda.autoinit
    >>> import numpy as np
    >>> import linalg
    >>> linalg.init()
    >>> v = np.array([1, 2, 3, 4, 5, 6], np.float32)
    >>> v_gpu = gpuarray.to_gpu(v)
    >>> d_gpu = linalg.diag(v_gpu)
    >>> np.all(d_gpu.get() == np.diag(v))
    True
    >>> v = np.array([1j, 2j, 3j, 4j, 5j, 6j], np.complex64)
    >>> v_gpu = gpuarray.to_gpu(v)
    >>> d_gpu = linalg.diag(v_gpu)
    >>> np.all(d_gpu.get() == np.diag(v))
    True

    """

    if v_gpu.dtype not in [
            np.float32, np.float64, np.complex64, np.complex128
    ]:
        raise ValueError('unrecognized type')

    if len(v_gpu.shape) > 1:
        raise ValueError('input array cannot be multidimensional')

    use_double = int(v_gpu.dtype in [np.float64, np.complex128])
    use_complex = int(v_gpu.dtype in [np.complex64, np.complex128])

    # Initialize output matrix:
    d_gpu = misc.zeros((v_gpu.size, v_gpu.size), v_gpu.dtype)

    # Get block/grid sizes:
    dev = misc.get_current_device()
    block_dim, grid_dim = misc.select_block_grid_sizes(dev, d_gpu.shape)

    # Set this to False when debugging to make sure the compiled kernel is
    # not cached:
    cache_dir = None
    diag_mod = \
             SourceModule(diag_template.substitute(use_double=use_double,
                                                   use_complex=use_complex),
                          cache_dir=cache_dir)

    diag = diag_mod.get_function("diag")
    diag(v_gpu, d_gpu, np.uint32(v_gpu.size), block=block_dim, grid=grid_dim)

    return d_gpu
Exemplo n.º 11
0
def main():
    data = load_data()

    if args.edges == 0:
        ppiGraph = nx.Graph(data.humanppi, name="HumanPPI")
    else:
        ppiGraph = nx.Graph(data.humanppi[0:args.edges], name="HumanPPI")

    draw_kwargs = dict(node_size=5,
                       font_size=6,
                       with_labels=False, 
                       linewidths=0.1, 
                       width=0.2)

    layout_kw = dict(iterations=args.iterations)
    img_title = 'Nodes: %i  Edges: %i  Iterations: %i  Runtime: %s'

    if args.iterations == None:

        iters = get_iterations()

        for iteration in iters:
            starttime = time.time()

            fig = plt.figure(figsize=(10,10))
            ax = fig.add_subplot(111)
            nx.draw(ppiGraph, pos=nx.spring_layout(ppiGraph, iterations=iteration ), **draw_kwargs )

            runtime = time.time() - starttime
            runtime_str = str(round(runtime, 2))+' seconds' 

            print "Iterations: %i  Run-time: %s "%(iteration, runtime_str)

            subs = (len(ppiGraph), args.edges, iteration, runtime_str)
            ax.set_title(img_title%subs)

            filepath = 'graphs'+'/'+zeros(iteration, padlength=4)+'.png'
            
            plt.savefig(filepath,  bbox_inches='tight')
            print 'Written to: '+filepath

            fig.clf()
            plt.close()
    else:
        starttime = time.time()

        fig = plt.figure(figsize=(10,10))
        ax = fig.add_subplot(111)
        nx.draw(ppiGraph, pos=nx.spring_layout(ppiGraph, **layout_kw ), **draw_kwargs )

        runtime = time.time() - starttime
        runtime_str = str(round(runtime, 2))+' seconds' 

        subs = (len(ppiGraph), args.edges, args.iterations, runtime_str)
        ax.set_title(img_title%subs)

        filepath = 'graphs'+'/'+zeros(args.iterations, padlength=4)+'.png'
        plt.savefig(filepath,  bbox_inches='tight')
        print 'Written to: '+filepath
        fig.clf()
        plt.close()