Plot graph with nodes (iterable) into filename
771923
def plotGraph(self,mode="plain",nodes=None,filename="tgraph.png"):
        
        if nodes==None:
            nodes=self.nodes
        else:
            nodes=[i for i in self.nodes if i in nodes]
        for node in self.nodes:
            n_=self.A.get_node(node)
            if mode=="plain":
                nmode=1
            else:
                nmode=-1
            pos="{},{}".format(self.xi[::nmode][self.nm.nodes_.index(node)],self.yi[::nmode][self.nm.nodes_.index(node)])
            n_.attr["pos"]=pos
            n_.attr["pin"]=True
            color='#%02x%02x%02x' % tuple([255*i for i in self.cm[int(self.clustering[n_]*255)][:-1]])
            n_.attr['fillcolor']= color
            n_.attr['fixedsize']=True
            n_.attr['width']=  abs(.1*(self.nm.degrees[n_]+  .5))
            n_.attr['height']= abs(.1*(self.nm.degrees[n_]+.5))
            n_.attr["label"]=""
            if node not in nodes:
                n_.attr["style"]="invis"
            else:
                n_.attr["style"]="filled"
        for e in self.edges:
            e.attr['penwidth']=3.4
            e.attr["arrowsize"]=1.5
            e.attr["arrowhead"]="lteeoldiamond"
            e.attr["style"]=""
            if sum([i in nodes for i in (e[0],e[1])])==2:
                e.attr["style"]=""
            else:
                e.attr["style"]="invis"
        tname="{}{}".format(self.basedir,filename)
        print(tname)
        self.A.draw(tname,prog="neato")
663898
def format_file_node(import_graph, node, indent):
    """"""
    f = import_graph.provenance[node]
    if isinstance(f, resolve.Direct):
        out = '+ ' + f.short_path
    elif isinstance(f, resolve.Local):
        out = '  ' + f.short_path
    elif isinstance(f, resolve.System):
        out = ':: ' + f.short_path
    elif isinstance(f, resolve.Builtin):
        out = '(%s)' % f.module_name
    else:
        out = '%r' % node
    return '  '*indent + out
1190945
def jsonGraph(fdefs,calls,outfile='nout.json'):
    '''
    '''
    outpath = os.path.join('data',outfile)
    data = dict()
    ids = dict()
    nodelist = []
    for fnlist in fdefs.values():
        for fn in fnlist:
            if isInCalls(fn,calls):
                tagged_node = getTaggedNode(fn,ids)
                nodelist.append(tagged_node)
            else:
                #print("omitted")
                pass
    linklist = [] #list of links, NOT a linked list ;D
    for call in calls:
        for link in linklist:
            if call.source.id == link["source"]:
                if call.target.id == link["target"]:
                    link["value"] += 1
                    break
        else:
            link = dict()
            link["source"] = call.source.id
            link["target"] = call.target.id
            link["value"]  = 1
            linklist.append(link)
    
    data["links"] = linklist
    data["nodes"] = nodelist
    with open(outpath, 'w+') as f:
        f.write(json.dumps(data, indent=2))
    return
78278
def get_outfile(self, outfile, goids=None):
        """"""
        # 1. Use the user-specfied output filename for the GO Term plot
        if outfile != self.dflt_outfile:
            return outfile
        # 2. If only plotting 1 GO term, use GO is in plot name
        if goids is not None and len(goids) == 1:
            goid = next(iter(goids))
            goobj = self.gosubdag.go2obj[goid]
            fout = "GO_{NN}_{NM}".format(NN=goid.replace("GO:", ""), NM=goobj.name)
            return ".".join([re.sub(r"[\s#'()+,-./:<=>\[\]_}]", '_', fout), 'png'])
        # 3. Return default name
        return self.dflt_outfile
1350850
def save_graph(graphdef):
    ''''''
    if graphdef.filename is None:
        if 'HOME' in os.environ:
            dname = os.path.join(os.environ['HOME'], '.mavproxy')
            if os.path.exists(dname):
                mp_util.mkdir_p(dname)
                graphdef.filename = os.path.join(dname, 'mavgraphs.xml')
        elif 'LOCALAPPDATA' in os.environ:
            dname = os.path.join(os.environ['LOCALAPPDATA'], 'MAVProxy')
            if os.path.exists(dname):
                mp_util.mkdir_p(dname)
                graphdef.filename = os.path.join(dname, 'mavgraphs.xml')
        else:
            graphdef.filename = 'mavgraphs.xml'
    if graphdef.filename is None:
        print("No file to save graph to")
        return
    try:
        graphs = load_graph_xml(open(graphdef.filename).read(), graphdef.filename, load_all=True)
    except Exception:
        graphs = []
    found_name = False
    for i in range(len(graphs)):
        if graphs[i].name == graphdef.name:
            graphs[i] = graphdef
            found_name = True
            break
    if not found_name:
        graphs.append(graphdef)
    pipe_console_input.send("Saving %u graphs to %s" % (len(graphs), graphdef.filename))
    f = open(graphdef.filename, "w")
    f.write("<graphs>\n\n")
    for g in graphs:
        f.write(" <graph name='%s'>\n" % g.name.strip())
        if g.description is None:
            g.description = ''
        f.write("  <description>%s</description>\n" % g.description.strip())
        for e in g.expressions:
            f.write("  <expression>%s</expression>\n" % e.strip())
        f.write(" </graph>\n\n")
    f.write("</graphs>\n")
    f.close()
753659
def _process_graph(self):
        
        all_nodes = [x.name for x in self.graph.as_graph_def().node]
        nodes = [x for x in all_nodes if x in self.possible_output_nodes]
        logger.info('List of nodes to export for brain :' + self.brain.brain_name)
        for n in nodes:
            logger.info('\t' + n)
        return nodes
255698
def graph_from_dot_file(path, encoding=None):
    
    with io.open(path, 'rt', encoding=encoding) as f:
        s = f.read()
    if not PY3:
        s = unicode(s)
    graphs = graph_from_dot_data(s)
    return graphs
900034
def to_string(self):
        
        
        
        graph = list()
        
        if self.obj_dict.get('strict', None) is not None:
        
            if self==self.get_parent_graph() and self.obj_dict['strict']:
            
                graph.append('strict ')

        if self.obj_dict['name'] == '':
            if 'show_keyword' in self.obj_dict and self.obj_dict['show_keyword']:
                graph.append( 'subgraph {\n' )
            else:
                graph.append( '{\n' )
        else:
            graph.append( '%s %s {\n' % (self.obj_dict['type'], self.obj_dict['name']) )


        for attr in self.obj_dict['attributes'].iterkeys():
        
            if self.obj_dict['attributes'].get(attr, None) is not None:
       
                val = self.obj_dict['attributes'].get(attr)
                if val is not None:
                    graph.append( '%s=%s' % (attr, quote_if_necessary(val)) )
                else:
                    graph.append( attr )
                    
                graph.append( ';\n' )


        edges_done = set()
        
        edge_obj_dicts = list()
        for e in self.obj_dict['edges'].itervalues():
            edge_obj_dicts.extend(e)
            
        if edge_obj_dicts:
            edge_src_set, edge_dst_set = zip( *[obj['points'] for obj in edge_obj_dicts] )
            edge_src_set, edge_dst_set = set(edge_src_set), set(edge_dst_set)
        else:
            edge_src_set, edge_dst_set = set(), set()
            
        node_obj_dicts = list()
        for e in self.obj_dict['nodes'].itervalues():
            node_obj_dicts.extend(e)

        sgraph_obj_dicts = list()
        for sg in self.obj_dict['subgraphs'].itervalues():
            sgraph_obj_dicts.extend(sg)

        
        obj_list = [ (obj['sequence'], obj) for obj in (edge_obj_dicts + node_obj_dicts + sgraph_obj_dicts) ]
        obj_list.sort()
        
        for idx, obj in obj_list:
        
            if obj['type'] == 'node':

                node = Node(obj_dict=obj)
            
                if self.obj_dict.get('suppress_disconnected', False):
                
                    if (node.get_name() not in edge_src_set and
                        node.get_name() not in edge_dst_set):
                        
                        continue
                        
                graph.append( node.to_string()+'\n' )

            elif obj['type'] == 'edge':

                edge = Edge(obj_dict=obj)
                
                if self.obj_dict.get('simplify', False) and edge in edges_done:
                    continue
                
                graph.append( edge.to_string() + '\n' )
                edges_done.add(edge)
                
            else:
            
                sgraph = Subgraph(obj_dict=obj)
                
                graph.append( sgraph.to_string()+'\n' )

        graph.append( '}\n' )
        
        return ''.join(graph)
322531
def nodes_dump(self):
        """"""
        self._flush_nodes()
        for (graph, node, branch, turn,tick, extant) in self.sql('nodes_dump'):
            yield (
                self.unpack(graph),
                self.unpack(node),
                branch,
                turn,
                tick,
                bool(extant)
            )
1150609
def save_graph(graphdef):
    ''''''
    if graphdef.filename is None:
        if 'HOME' in os.environ:
            dname = os.path.join(os.environ['HOME'], '.mavproxy')
            mp_util.mkdir_p(dname)
            graphdef.filename = os.path.join(dname, 'mavgraphs.xml')
        else:
            graphdef.filename = 'mavgraphs.xml'
    if graphdef.filename is None:
        mestate.console.writeln("No file to save graph to", fg='red')
        return
    graphs = load_graph_xml(open(graphdef.filename).read(), graphdef.filename, load_all=True)
    found_name = False
    for i in range(len(graphs)):
        if graphs[i].name == graphdef.name:
            graphs[i] = graphdef
            found_name = True
            break
    if not found_name:
        graphs.append(graphdef)
    mestate.console.writeln("Saving %u graphs to %s" % (len(graphs), graphdef.filename))
    f = open(graphdef.filename, "w")
    f.write("<graphs>\n\n")
    for g in graphs:
        f.write(" <graph name='%s'>\n" % g.name.strip())
        if g.description is None:
            g.description = ''
        f.write("  <description>%s</description>\n" % g.description.strip())
        for e in g.expressions:
            f.write("  <expression>%s</expression>\n" % e.strip())
        f.write(" </graph>\n\n")
    f.write("</graphs>\n")
    f.close()
284271
def load_graph_xml(xml, filename, load_all=False):
    ''''''
    ret = []
    try:
        root = objectify.fromstring(xml)
    except Exception:
        return []
    if root.tag != 'graphs':
        return []
    if not hasattr(root, 'graph'):
        return []
    for g in root.graph:
        name = g.attrib['name']
        expressions = [e.text for e in g.expression]
        if load_all:
            ret.append(GraphDefinition(name, e, g.description.text, expressions, filename))
            continue
        if have_graph(name):
            continue
        for e in expressions:
            if expression_ok(e):
                ret.append(GraphDefinition(name, e, g.description.text, expressions, filename))
                break
    return ret
1019817
def create_copy_without_data(G):
    """"""
    H = nx.Graph()
    for i in H.nodes_iter():
        H.node[i] = {}
    return H
234951
def save_graph_to_file(graph_file_name, module_spec, class_count):
  """"""
  sess, _, _, _, _, _ = build_eval_session(module_spec, class_count)
  graph = sess.graph

  output_graph_def = tf.graph_util.convert_variables_to_constants(
      sess, graph.as_graph_def(), [FLAGS.final_tensor_name])

  with tf.gfile.GFile(graph_file_name, 'wb') as f:
    f.write(output_graph_def.SerializeToString())
714452
def graphdata(data):
    """"""
    data = jh.get_ratings(data)
    num = 1
    rating_final = []
    episode_final = []
    for k,v in data.iteritems():
        rating=[]
        epinum=[]
        for r in v:
            if r != None:
                rating.append(float(r))
                epinum.append(num)
                num+=1
        rating_final.append(rating)
        episode_final.append(epinum)
    return rating_final,episode_final
278801
def hicexplorer_create_plot(self, pKeyList, pTitle, pId):
        """"""

        keys = OrderedDict()

        for i, key_ in enumerate(pKeyList):
            keys[key_] = {'color': self.colors[i]}

        data = {}

        for data_ in self.mod_data:
            data['{}'.format(self.mod_data[data_]['File'][0])] = {}
            for key_ in pKeyList:
                data['{}'.format(self.mod_data[data_]['File'][0])][key_] = self.mod_data[data_][key_][0]

        config = {
            'id': 'hicexplorer_' + pId + '_plot',
            'title': pTitle,
            'ylab': 'Number of Reads',
            'cpswitch_counts_label': 'Number of Reads'
        }

        return bargraph.plot(data, keys, config)
107801
def get_new_nodes(fname):
    

    with open(fname, 'rU') as infile:
        infile = (line for line in infile if not line.startswith('#'))
        reader = list(csv.DictReader(infile))
        rows = (d for d in reader if d['tax_id'])

    # for now, children are provided as a semicolon-delimited list
    # within a cell (yes, yuck). We need to convert thit into a list
    # if present.
    for d in rows:
        if 'children' in d:
            if d['children']:
                d['children'] = [x.strip() for x in d['children'].split(';')]
            else:
                del d['children']
        yield d
1214897
def input_data(self):
        
        ordererd = np.sort(np.asarray(list(self.plot_info.keys())).astype(int))

        trans_cont_dict = OrderedDict()
        for i in ordererd:
            trans_cont_dict[str(i)] = self.plot_info[str(i)]

        self.plot_info = trans_cont_dict

        # set empty lists for x,y,z
        x = [[]for i in np.arange(len(self.plot_info.keys()))]
        y = [[] for i in np.arange(len(self.plot_info.keys()))]
        z = [[] for i in np.arange(len(self.plot_info.keys()))]

        # read in base files/data
        for k, axis_string in enumerate(self.plot_info.keys()):

            if 'file' not in self.plot_info[axis_string].keys():
                continue
            for j, file_dict in enumerate(self.plot_info[axis_string]['file']):
                data_class = ReadInData(**{**self.general, **file_dict,
                                           **self.plot_info[axis_string]['limits']})

                x[k].append(data_class.x_append_value)
                y[k].append(data_class.y_append_value)
                z[k].append(data_class.z_append_value)

            # print(axis_string)

        # add data from plots to current plot based on index
        for k, axis_string in enumerate(self.plot_info.keys()):

            # takes first file from plot
            if 'indices' in self.plot_info[axis_string]:
                if type(self.plot_info[axis_string]['indices']) == int:
                    self.plot_info[axis_string]['indices'] = (
                        [self.plot_info[axis_string]['indices']])

                for index in self.plot_info[axis_string]['indices']:

                    index = int(index)

                    x[k].append(x[index][0])
                    y[k].append(y[index][0])
                    z[k].append(z[index][0])

        # read or append control values for ratio plots
        for k, axis_string in enumerate(self.plot_info.keys()):
            if 'control' in self.plot_info[axis_string]:
                if ('name' in self.plot_info[axis_string]['control'] or
                        'label' in self.plot_info[axis_string]['control']):
                    file_dict = self.plot_info[axis_string]['control']
                    if 'limits' in self.plot_info[axis_string].keys():
                        liimits_dict = self.plot_info[axis_string]['limits']

                    data_class = ReadInData(**{**self.general, **file_dict,
                                               **self.plot_info[axis_string]['limits']})
                    x[k].append(data_class.x_append_value)
                    y[k].append(data_class.y_append_value)
                    z[k].append(data_class.z_append_value)

                elif 'index' in self.plot_info[axis_string]['control']:
                    index = int(self.plot_info[axis_string]['control']['index'])

                    x[k].append(x[index][0])
                    y[k].append(y[index][0])
                    z[k].append(z[index][0])

            # print(axis_string)

        # transfer lists in PlotVals class.
        value_classes = []
        for k in range(len(x)):
            value_classes.append(PlotVals(x[k], y[k], z[k]))

        self.value_classes = value_classes
        return