def show_flows(g, ngs, fgs): p0 = gd.getpos(g) ckw = dict([(k, dict(facecolor='gray', alpha=1, linewidth=.5, arrowstyle='-|>', edgecolor='black', color='gray', shrinkA=0, shrinkB=0)) for k in g.edges()]) skw = dict(facecolor='none', edgecolor='black', s=20) gd.draw(g, p0, g.edges(), ckw=ckw, skw=skw, cktype='simple') colors = mycolors.getct(len(fgs)) for i, fg in enumerate(fgs): edges = fg.edges() weights = [fg[e[0]][e[1]]['weight'] for e in edges] ckw = dict([(k, dict(color=colors[i], linewidth=weights[j] / 3)) for j, k in enumerate(edges)]) gd.draw(fg, p0, edges, ckw=ckw, scatter_nodes=[], cktype='simple')
def show_brain_flows(g,ngs,fgs, communities): centers,volumes, voxels = aba.brain_regions(len(communities), return_voxels = True) p0 = {} n_communities = {} for i, c in enumerate(communities): nv = len(voxels[i]) for j, n in enumerate(c): p0[n] = voxels[i][int(floor(random.rand()*nv))][:2] + random.rand()*.4 n_communities[n] = i comm_ct = mycolors.getct(len(n_communities)) nodelist = g.nodes() ckw = dict([(k,dict(facecolor = 'gray', alpha = 1, linewidth = .5, arrowstyle = '-|>', edgecolor = 'black', color = comm_ct[n_communities[k[0]]], shrinkA = 0, shrinkB = 0)) for k in g.edges() ]) skw =dict(facecolor = 'none', edgecolor = [comm_ct[n_communities[n]] for n in nodelist], s = 1) gd.draw(g,p0,g.edges()[::10], scatter_nodes = nodelist, ckw = ckw, skw = skw, ckalpha = .8, cktype = 'simple') return colors = mycolors.getct(len(fgs)) for i,fg in enumerate(fgs): edges = fg.edges() weights = [fg[e[0]][e[1]]['weight'] for e in edges] ckw = dict([(k, dict(color = colors[i], linewidth = weights[j]/3)) for j, k in enumerate(edges) ]) gd.draw(fg, p0, edges, ckw = ckw, scatter_nodes = [], cktype = 'simple', ckalpha = .25, )
def show_brain_flows(g, ngs, fgs, communities): centers, volumes, voxels = aba.brain_regions(len(communities), return_voxels=True) p0 = {} n_communities = {} for i, c in enumerate(communities): nv = len(voxels[i]) for j, n in enumerate(c): p0[n] = voxels[i][int(floor( random.rand() * nv))][:2] + random.rand() * .4 n_communities[n] = i comm_ct = mycolors.getct(len(n_communities)) nodelist = g.nodes() ckw = dict([(k, dict(facecolor='gray', alpha=1, linewidth=.5, arrowstyle='-|>', edgecolor='black', color=comm_ct[n_communities[k[0]]], shrinkA=0, shrinkB=0)) for k in g.edges()]) skw = dict(facecolor='none', edgecolor=[comm_ct[n_communities[n]] for n in nodelist], s=1) gd.draw(g, p0, g.edges()[::10], scatter_nodes=nodelist, ckw=ckw, skw=skw, ckalpha=.8, cktype='simple') return colors = mycolors.getct(len(fgs)) for i, fg in enumerate(fgs): edges = fg.edges() weights = [fg[e[0]][e[1]]['weight'] for e in edges] ckw = dict([(k, dict(color=colors[i], linewidth=weights[j] / 3)) for j, k in enumerate(edges)]) gd.draw( fg, p0, edges, ckw=ckw, scatter_nodes=[], cktype='simple', ckalpha=.25, )
def show_flows(g, ngs, fgs): p0 = gd.getpos(g) ckw = dict([(k,dict(facecolor = 'gray', alpha = 1, linewidth = .5, arrowstyle = '-|>', edgecolor = 'black', color = 'gray', shrinkA = 0, shrinkB = 0)) for k in g.edges() ]) skw =dict(facecolor = 'none', edgecolor = 'black', s = 20) gd.draw(g,p0,g.edges(), ckw = ckw, skw = skw, cktype = 'simple') colors = mycolors.getct(len(fgs)) for i,fg in enumerate(fgs): edges = fg.edges() weights = [fg[e[0]][e[1]]['weight'] for e in edges] ckw = dict([(k, dict(color = colors[i], linewidth = weights[j]/3)) for j, k in enumerate(edges) ]) gd.draw(fg, p0, edges, ckw = ckw, scatter_nodes = [], cktype = 'simple')
def scatter_array(arr, params): geo = params['computed']['geometry'] if geo['name'] == 'square': return False name = geo['name'] sxs = True if name == 'star': f = plt.gcf() ax = f.add_subplot(111) star_k = geo['k'] d = geo['dim'] ofs = 0 xs, ys, cs = [],[],[] all_vals = reshape(transpose(arr,(1,0,2)), (shape(arr)[0]*shape(arr)[1], 3)) nl = star_k; nodes = {}; for l in range(star_k): layer_count = pow(d,l) layer_ofs = 0 if l == 0: nodes[(0,0)] = {'r':0., 't':0., 'x':0, 'y':0, 'c':all_vals[ofs]} ofs += 1 else: parent_keys = [ key for key in nodes.keys() if key[0] == l -1]; for key in parent_keys: p = nodes[key] pt = p['t'] pr = p['r'] for i in range(d): rthis = 5/sqrt(l) open_angle = pi * 2 if l != 1 : open_angle = open_angle *.5 x0 = cos(pt) * pr y0 = sin(pt) * pr else: if divmod(i,2)[1] == 2: rthis *= 2 x0 = 0 y0 = 0 angle_0 = pt - open_angle /2 theta = angle_0 + open_angle * (float(i) / d) x = x0 + cos(theta) * rthis y = y0 + sin(theta) * rthis t = angle(complex(x,y)) r = absolute(complex(x,y)) nodes[(l,layer_ofs)] ={'r':r, 't':t, 'c':all_vals[ofs], 'x':x, 'y':y, 'ps':[key]} layer_ofs += 1; ofs+= 1; nodes[(0,0)]['ps'] = [k for k in nodes.keys() if k[0] == star_k-1] cheap = False if cheap: xs,ys,cs = zip(*[[v['x'],v['y'],v['c']] for v in nodes.values()]) ax.scatter(xs, ys, 50,color = cs) else: import networkx as nx import cb.utils.graphs.draw as gd g = nx.DiGraph() edges = [(k, p) for k,v in nodes.iteritems() for p in v['ps']]; g.add_edges_from(edges) pos = dict([(k, [v['x'] , v['y']]) for k,v in nodes.iteritems()]) nl = g.nodes() ects = dict([(k,len(g[k]) ) for k in nl]) arrows = False if arrows: ckw = dict([(k,dict(facecolor = 'gray' if ects[k[0]] == 1 else 'gray', alpha = 1, linewidth = 3, arrowstyle = '-|>', edgecolor = 'black', shrinkA = 30, shrinkB = 30)) for k in g.edges() if ects[k[0]] == 1]) else: ckw = {} gd.draw(g, pos, g.edges(), skw = {'s':500, 'edgecolor':'black', 'facecolor':[nodes[k]['c'] for k in nl], 'alpha':.5 }, scatter_nodes = nl, ckw = ckw ) plt.gca().set_xticks([]) plt.gca().set_yticks([]) #raise Exception() # #xs = [v['r'] * cos(v['t']) for v in nodes.values()] #ys = [v['r'] * sin(v['t']) for v in nodes.values()] #cs = [v['c'] for v in nodes.values()] # return sxs
def view0(modules, data_src = 'bdtnp', net_src = 'fRN', max_rank = 4, module_type = 'doubles'): ''' A routine to view the sign of interaction coefficients for a given transcription factor split per-cluster and per-module size. Designed to be run on the output of view_output.modules() ''' #COMPUTE BULK STATISTICS FOR EACH TF bd_data = nio.getBDTNP() genes = bd_data.keys() tfs =sorted(set(it.chain(*[k for k in modules.keys()]))) tf_net = nx.Graph() tf_net.add_nodes_from(tfs) tf_edges = it.chain(*[[(e0, e1) for e0 in term for e1 in term if e0 != e1] for term in modules.keys()]) tf_net.add_edges_from(tf_edges) pos = nx.graphviz_layout(tf_net) fig = myplots.fignum(1, (8,8)) tfnodes = tf_net.nodes() tfnames = tfnodes all_coefs = \ list(it.chain(*[t['coefs'] for t in modules.values()])) cstd = std(all_coefs) def colorfun(coefs): coef = median(coefs) arr = array([1.,0.,0.]) if coef < 0\ else array([0.,0.,1.]) return arr*min([1, abs(coef/cstd*2)]) def widthfun(coefs, maxwid): return max([1,5.* len(coefs) /maxwid]) for tf in tfs: fig.clf() ax = fig.add_subplot(111) ecols,ewids, estyles, ealphas =\ [{} for i in range(4)] edges = [] tf_doublet_terms = [(k, v) for k, v in modules.iteritems() if tf in k and len(set(k)) == 2 ] tf_triplet_terms = [(k, v) for k, v in modules.iteritems() if tf in k and len(set(k)) == 3 ] isdub = dict([(k,0.) for k in tfnames]) istrip =dict([(k,0.) for k in tfnames]) coflens = [len(e[1]['coefs']) for e in tf_triplet_terms + tf_doublet_terms] max_l = max(coflens) for tt,v in sorted(tf_triplet_terms, key = lambda x: len(x[1]['genes']))[::-1][:max_rank]: partners =tuple( [t for t in set(tt) if not t==tf]) for p in partners: istrip[p] = 1 #istrip[[tfnodes.index(p) for p in partners]] = 1 edge = partners ecols[edge] = colorfun(modules[tt]['coefs']) ewids[edge] = widthfun(modules[tt]['coefs'],max_l) ealphas[edge] = 1 if module_type in ['triples','all'] \ else .1 estyles[edge] = 'dotted' edges.append(edge) for td,v in sorted(tf_doublet_terms, key = lambda x: len(x[1]['genes']))[::-1][:max_rank]: partners = tuple([t for t in set(td) if not t==tf]) for p in partners: isdub[p] = 1 edge = (tuple([tf] + list(partners))) ecols[edge] = colorfun(modules[td]['coefs']) ewids[edge] = widthfun(modules[td]['coefs'], max_l) ealphas[edge] = 1 if module_type in ['doubles','all'] \ else .1 estyles[edge] = 'solid' edges.append(edge) tf_graph = nx.DiGraph() tf_graph.add_nodes_from(tfnodes) tf_graph.add_edges_from(edges) ckw = dict([ (k, dict(color = ecols[k], #array([1,0,0])*isdub[k] +\ # array([0,0,1])*istrip[k], alpha = ealphas[k], linestyle = estyles[k], linewidth = ewids[k], arrowstyle = '-')) for k in tf_graph.edges()]) circlepoints = dict([ (k, dict(facecolor ='white', #array([1,0,0])*isdub[k] +\ # array([0,0,1])*istrip[k], alpha = round(ealphas[k],2), edgecolor = ecols[k], linestyle = estyles[k], linewidth = 3,)) for k in tf_graph.edges()]) ax.set_title('Top modules for TF: {0}'.format(tf)) myplots.padded_limits(ax, *zip(*pos.values())) nodes = tf_graph.nodes() gd.draw(tf_graph,pos,edges, scatter_nodes =tf_graph.nodes(), skw = {'s':[200 if n == tf else 2 for n in nodes], 'facecolor':[colorfun(modules[tuple([n])]['coefs']) if n == tf else 'black' for n in nodes], 'edgecolor':'black', 'linewidth':2, 'alpha':1},#[1 if n == tf else .1 for n in nodes]}, ckw = {}) colors,alphas,tripoints = [{} for i in range(3)] for e in edges: colors[e] = 'black' alphas[e] = .2 tripoints[e] = array(pos[tf]) plot_tri = False plot_circ = True if plot_tri: gd.overlay(tf_graph, pos, edges, tripoints = tripoints, colors = colors, alphas = alphas) if plot_circ: gd.overlay(tf_graph, pos, edges, circlepoints =circlepoints) ax2 = fig.add_axes([.05,.05,.2,.2]) ax2.set_xticks([]) ax2.set_yticks([]) coefs = modules[tuple([tf])]['coefs'] l = len(coefs) sx = sy = ceil(sqrt(l)) xs = mod(arange(l), sx) ys = floor( arange(l) / sx) cs = [colorfun([c/2]) for c in sorted(coefs)] ss = 100 ax2.scatter(xs, ys, s = ss, color = cs) fig.savefig(figtemplate.format('tf_{0}_net_rank{1}_{2}'.\ format(tf,max_rank,module_type)))