def custom_plot(self, X, Y): """Plot the Y as a function of X. X and Y can be chosen in the keys of self.observables. Args: seed (int): number of the seed to look at X (str): x-axis observable Y (list): list (or string) of y-axis observable """ x_val = self.observables[X]() if isinstance(Y, str): Y = [Y] Y_val = {y: self.observables[y]() for y in Y} NUM_COLORS = len(Y) color_l = { Y[i]: col for i, col in zip(range(NUM_COLORS), palette.color_generate(NUM_COLORS)) } fig = plt.figure() ax = fig.gca() for label, y_val in Y_val.items(): if y_val is not None: ax.plot(x_val, y_val, lw=2, color=color_l[label], label=label) ax.set_xlabel(X) ax.set_ylabel(Y[0]) ax.legend() fig.show() return fig
def Plot_Profile(self, trial_index, time=0, no_popup=False): """ Searches in the data last stored in the Simulation buffer for the cell profile corresponding to the time point "time" and plot the profile. Args: trial_index: index of the trial you. Refere to run_dynamics to know how many trials there are. time: Index of the time point to plot Return: figure """ data = [] nstep = self.inits.prmt['nstep'] nSpecies = self.buffer_data[trial_index][0].shape[1] nCell = len(self.buffer_data[trial_index]) cells = list(range(nCell)) self.buffer_data[trial_index][0] profiles = np.array( [self.buffer_data[trial_index][cc][time, :] for cc in range(nCell)]).T species_labels = ["Species {}".format(i) for i in range(nSpecies)] for ind in self.buffer_data["outputs"]: species_labels[ind] = species_labels[ind].replace("Species", "Output") for ind in self.buffer_data["inputs"]: species_labels[ind] = species_labels[ind].replace("Species", "Inputs") dt = self.inits.prmt["dt"] colors = palette.color_generate(nSpecies) for i in range(nSpecies): trace = go.Scatter(x=cells, y=profiles[i, :], name=species_labels[i], line=dict(color=colors[i], width=linewidth)) data.append(trace) layout = go.Layout( title="Cell profile", xaxis=dict(title="Cell, time={}".format(time)), yaxis=dict(title="Concentration"), autosize=True, hovermode='closest', ) fig = go.Figure(data=data, layout=layout) if not no_popup: plotfunc(fig) return fig
def Plot_TimeCourse(self, trial_index, cell=0, no_popup=False): """ Searches in the data last stored in the Simulation buffer for the time course corresponding to the trial_index and the cell and plot the gene time series Args: trial_index: index of the trial you. Refere to run_dynamics to know how many trials there are. cell: Index of the cell to plot Return: figure """ data = [] nstep = self.inits.prmt['nstep'] time_course = self.buffer_data[trial_index][cell] nSpecies = time_course.shape[1] species_labels = ["Species {}".format(i) for i in range(nSpecies)] for ind in self.buffer_data["outputs"]: species_labels[ind] = species_labels[ind].replace("Species", "Output") for ind in self.buffer_data["inputs"]: species_labels[ind] = species_labels[ind].replace("Species", "Inputs") dt = self.inits.prmt["dt"] nstep = self.inits.prmt["nstep"] time_axis = np.arange(0, nstep * dt, dt) colors = palette.color_generate(nSpecies) for i in range(nSpecies): trace = go.Scatter(x=time_axis, y=time_course[:, i], name=species_labels[i], line=dict(color=colors[i], width=linewidth)) data.append(trace) layout = go.Layout( title="Time course", xaxis=dict(title="Time, cell={}".format(cell)), yaxis=dict(title="Concentration"), autosize=True, hovermode='closest', ) fig = go.Figure(data=data, layout=layout) if not no_popup: plotfunc(fig) return fig
def plot_lineage_fitness(self, line, formula="{}", highlighted_mutations=[]): from phievo.AnalysisTools import plotly_graph generations = [net_inf["gen"] for net_inf in line] fitness = [eval(formula.format(net_inf["fit"])) for net_inf in line] generate_hoverinfo = lambda net: "net #{}\nmutations:{}".format( net["ind"], "-".join(net["las"] if net["las"] else [])) hover_info = [generate_hoverinfo(net_inf) for net_inf in line] colors = palette.color_generate(len(highlighted_mutations) + 1) trace = plotly_graph.go.Scatter( x=generations, y=fitness, text=hover_info, mode="markers+lines", marker=dict(color=colors[0]), ) data_to_plot = [trace] if highlighted_mutations: dict_highlighted = { mut: plotly_graph.go.Scatter( x=[], y=[], text=[], mode="markers", marker=dict(color=colors[i + 1]), ) for i, mut in enumerate(highlighted_mutations) } for net_inf in line: try: ind = "-".join(net_inf["las"]) if net_inf["las"] else "" trace = dict_highlighted[ind] except KeyError: continue trace["x"].append(net_inf["gen"]) trace["y"].append(eval(formula.format(net_inf["fit"]))) trace["text"].append(generate_hoverinfo(net_inf)) data_to_plot += list(dict_highlighted.values()) plotly_graph.py.plot(data_to_plot)
def PlotData(self, data, xlabel, ylabel, select_genes=[], no_popup=False, legend=True, lw=1, ax=None): """ Function in charge of the call to matplotlib for both Plot_TimeCourse and Plot_Profile. """ fig = plt.figure() if not ax: ax = fig.gca() Ngene = data.shape[1] colors = palette.color_generate(Ngene) for gene in range(Ngene): if select_genes != [] and gene not in select_genes: continue ls = "--" label = "Species {}" if gene in self.buffer_data["outputs"]: ls = "-" label = "Output {}" if gene in self.buffer_data["inputs"]: ls = "-" label = "Input {}" ax.plot(data[:, gene], ls=ls, label=label.format(gene), lw=lw, color=colors[gene]) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if legend: ax.legend() return fig
def pretty_graph(net,extended=False,layout=None): """ Take a Network instance and return a nice pydot graph with only species as nodes and interactions as edges. Just outline of code here, many display items to fiddle Best Doc on pydot is http://dkbza.org/pydot/pydot.html For attributes see http://www.graphviz.org/doc/info """ net.__build_dict_types__() size=len(net.dict_types['Species'])+len(net.dict_types['pMHC'])+1 colors=palette.color_generate(size) # compose a short species label from selected types and their values, Other types inferred from interactions #(NB TF might be dispensed with, and its activity recorded in arrow shape # complete list of protein_types= ['Output','Input','Ligand','Receptor'] def short_label(species): label = ' ' for k in species.types: if k == 'Output': label += ' Output' elif k == 'Input': label += ' Input' elif protein_types.count(k): label += k else: pass return label # Collect display options for types of Nodes, use as eg pydot.Node(name, **attribute_dict['TF'] ) attribute_dict = {} for tt in protein_types: attribute_dict[tt] = {} attribute_dict['Output']['shape'] = 'triangle' attribute_dict['Input']['shape'] = 'invtriangle' attribute_dict['Ligand']['shape'] = 'house' attribute_dict['Receptor']['shape'] = 'invhouse' attribute_dict['Default'] = {} # incase none of protein_types found # there are many different edge-arrow types available see the graphviz web site above. # unclear how to get key with shapes/colores, create subgraph? nodes only? # define graph with title graph = pydot.Dot(graph_type='digraph') #try: # graph.set_label('species graph: ' + net.title) #except: # graph.set_label('species graph: ') # for compatability with old code or if change input net->net.graph #graph.set_fontcolor('red') #graph.set_labelloc('t') # create pydot nodes for all species nodes in net and store in dictionary map_species = {} for nn in net.dict_types['Node']: if not nn.isinstance('Species'): continue #name = '%i'%nn.int_id() + short_label(nn) name = '%i'%nn.int_id() # chose the protein type for node display, , order in protein_types list maters for kk in protein_types: if nn.types.count(kk): break else: kk = 'Default' # customize attributes. attribute_dict[kk]['style']="filled" attribute_dict[kk]['fillcolor']=colors[nn.int_id()] attribute_dict[kk]['fontsize']=25 attribute_dict[kk]['width']=0.6 attribute_dict[kk]['height']=0.8 attribute_dict[kk]['fontcolor']='#FFFFFF' attribute_dict[kk]['fixedsize']='true' map_species[nn] = pydot.Node(name, **attribute_dict[kk] ) graph.add_node( map_species[nn] ) # find the species connected by interactions and create pydot.Edges # NB pydot has no delete node methods, so can not eliminate just interactions, build new graph # and then go back and eliminate the TModules (phys object) attribute={} attribute['repression']={} attribute['repression']['color']='0 1 1' attribute['activation']={} attribute['activation']['color']='0.3 1 0.5' attribute['generic']={} attribute['generic']['color']='0.6 1 1' for nn in net.dict_types['Node']: if isinstance(nn, ceds2.TModule): for pre in net.graph.list_predecessors(nn): pre_species = net.graph.list_predecessors(pre)[0] #only one species input to TFHill activity=pre.activity if (flag<1): pre_dot_name = map_species[pre_species].name else: pre_dot_name = map_species[pre_species].obj_dict['name'] for post in net.graph.list_successors(nn): post_species = net.graph.list_successors(post)[0] #only one species out from CorePromoter if (flag<1): post_dot_name = map_species[post_species].name else: post_dot_name = map_species[post_species].obj_dict['name'] ee = pydot.Edge(pre_dot_name, post_dot_name, label='Transcription' ) if hasattr(net,"fixed_activity_for_TF"): #if (net.fixed_activity_for_TF==0): if (activity==1): ee = pydot.Edge(pre_dot_name, post_dot_name,**attribute['activation']) else: ee = pydot.Edge(pre_dot_name, post_dot_name,**attribute['repression'] ) ee.set_arrowhead('tee') ee.set_arrowsize(2) graph.add_edge( ee ) elif isinstance(nn, ceds2.Interaction): if isinstance(nn,Initial_Concentration): continue if isinstance(nn,Simple_Phosphorylation): name = nn.label [catalyst,listIn,listOut]=net.catal_data(nn) ee = pydot.Edge(map_species[listIn[0]].compute_name(),map_species[listOut[0]].compute_name(), label=map_species[catalyst[0]].compute_name()) graph.add_edge( ee ) continue if isinstance(nn,Simple_Dephosphorylation): name = nn.label [catalyst,listIn,listOut]=net.catal_data(nn) ee = pydot.Edge(map_species[listIn[0]].compute_name(),map_species[listOut[0]].compute_name(), label=map_species[catalyst[0]].compute_name()) graph.add_edge( ee ) continue if isinstance(nn,KPR_Binding): name = 'LR' Complex=net.graph.list_successors(nn)[0] PPI_components=net.graph.list_predecessors(nn) #nppi=pydot.Node('PPI',label='PPI',style='filled',fillcolor='0.6 1 1',width=0.6,height=0.8) nameLR='LR%i'%nn.int_id() nppi=pydot.Node(nameLR,label='LR',style='filled',fillcolor='0.6 1 1',radius=0.1,fontcolor='#FFFFFF',shape='circle',fixedsize='true', width=0.3,height=0.3) graph.add_node(nppi) for k in range(len(PPI_components)): ee = pydot.Edge(map_species[PPI_components[k]].compute_name(),nameLR, **attribute['generic'] ) graph.add_edge( ee ) ee = pydot.Edge(nameLR,map_species[Complex].compute_name(), **attribute['generic'] ) graph.add_edge( ee ) continue if isinstance(nn,KPR_Unbinding): name = 'KPRU' Complex=net.graph.list_predecessors(nn)[0] [P1,P2]=net.graph.list_successors(nn) if P1.isinstance('Ligand'): L=P1 R=P2 else: R=P1 L=P2 #nppi=pydot.Node('PPI',label='PPI',style='filled',fillcolor='0.6 1 1',width=0.6,height=0.8) ee = pydot.Edge(map_species[Complex].compute_name(),map_species[L].compute_name(), label="1/τ",**attribute['generic'] ) graph.add_edge( ee ) continue name = nn.label print(name) for pre in net.graph.list_predecessors(nn): pre_dot_name = map_species[pre].compute_name for post in net.graph.list_successors(nn): post_dot_name = map_species[post].compute_name() ee = pydot.Edge(pre_dot_name, post_dot_name,**attribute['generic'] ) # color code interaction types? graph.add_edge( ee ) else: pass # end of loop to eliminate interaction nodes. return graph
def plot_pareto_fronts(self, generations, max_rank=1, with_indexes=False, legend=False, xlim=[], ylim=[], colors=[], gradient=[], xlabel="F_1", ylabel="F_2", s=50, no_popup=False): """ Plot every the network of the selected generations in the (F_1,F_2) fitness space. Args: generations (list): list of the selected generations max_rank (int): In given population plot only the network of rank <=max_rank with_indexes(bool): NotImplemented legend(bool): NotImplemented xlim (list): [xmax,xmin] ylim (list): [ymax,ymin] colors (list): List of html colors, one for each generation gradient (list): List of colors to include in the gradient xlabel(str): Label of the xaxis ylabel(str): Label of the yaxis s (float): marker size no_popup(bool): prevents the popup of the plot windows Returns: plotly figure """ net_info, fitnesses = self.pareto_generate_fit_dict(generations, max_rank) if not colors and not gradient: colors = { gen: col for gen, col in zip(fitnesses.keys(), palette.color_generate(len(fitnesses))) } if gradient: colors = { gen: col for gen, col in zip( generations, palette.generate_gradient(generations, gradient)) } shapes = ["circle", "square", "triangle-up"] data = [] for gen, ranks in sorted(fitnesses.items(), key=lambda x: x[1]): for ind, rank in enumerate(ranks): if not rank: continue F1, F2 = zip(*rank) trace = go.Scatter(x=F1, y=F2, mode='markers', name="G{0}-rank {1}".format(gen, ind), marker=dict(size=14, color=colors[gen], symbol=shapes[ind]), hoverinfo="text", legendgroup="group{}".format(gen)) infos = net_info[gen][ind] label_template = Template( "Generation: $gen<br>net: $net<br>rank: $rank<br>fitness: ($F1 , $F2)" ) trace["text"] = [label_template.substitute(inf) for inf in infos] data.append(trace) layout = go.Layout( title="Pareto fronts", xaxis=dict(title="Fitness 1"), yaxis=dict(title="Fitness 2"), autosize=True, hovermode='closest', ) fig = go.Figure(data=data, layout=layout) plotfunc(fig) return fig
def Plot_pMHC(Name, ncelltot, total_size, ntau, list_ligands, position='best', list_species=[], list_AP=[], list_output=[]): """ Plot profile of all proteins as function of ligand concentration (list_ligands) contain the list, for the differeent taus (number ntau)""" result = numpy.zeros( (total_size, ncelltot, ntau), dtype=float ) # creates a table result to store data, results[i,j] will contain the concentration of protein i in cell j at time defined by nline colors = palette.color_generate(total_size) pylab.clf() legendkey = [] linestyle = ['-', '--', ':', '-.'] cursor = 0 # cursor will be the index of the column linecache.clearcache() print(Name) line = linecache.getline(Name, 1) # get the line we want to plot s = line.split() if list_species == []: list_toplot = range(total_size) else: list_toplot = list_species for index in s: # takes each variable in the line if (cursor > 0): ncell = int( (cursor - 1) / (ntau * total_size) ) #computes the index of corresponding initial condition : column 1 to size*tau corresponds to CI 0, size*tau+1 to 2*size*tau corresponds to CI 2 idtau = int((cursor - 1 - total_size * ntau * ncell) / total_size) #computes the corresponding tau ngene = cursor - 1 - total_size * ntau * ncell - total_size * idtau try: result[ngene, ncell, idtau] = eval(index) #assigns it to the table result except: print(ngene, ncell, idtau) print(eval(index)) print("Error in Plot_Profile") cursor += 1 n_position = numpy.zeros((ncelltot), dtype=float) # print "Tab filled" gs = gridspec.GridSpec(1, 2) gs.update(left=0.2, right=0.8, wspace=0.0) for k in range(ntau): #pylab.subplot(1,ntau,k+1) #pylab.rc('axes', linewidth=2) ax = pylab.subplot(gs[0, k]) #ax = pylab.gca() ax.set_yscale('log') pylab.ylim([0.01, 1000]) for i in range(total_size): style = '--' #print i if i in list_output: style = '-' if i in list_toplot: pylab.plot(result[i, :, k], style, color=colors[i], lw=4.0) legendkey.append("%i" % i) fontsize = 20 for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) tick.label1.set_fontweight('bold') for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) tick.label1.set_fontweight('bold') if (k == 0): pylab.xlabel('Ligand #, 3s', fontsize=20, fontweight='bold') if (k == 1): pylab.xlabel('Ligand #, 10s', fontsize=20, fontweight='bold') if (k == 0): pylab.ylabel('Output', fontsize=20, fontweight='bold') else: ax.axes.get_yaxis().set_visible(False) pylab.xlim(0, 19) sublist = [0, 4, 8, 12, 16] sublist_ligands = [list_ligands[index] for index in sublist] pylab.xticks(sublist, sublist_ligands) pylab.legend(legendkey, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) pylab.show()
def Plot_Profile(Name, ncelltot, size, nline, position='best', list_species=[], list_AP=[], list_output=[], no_popup=False): """ Plot profile of all proteins at time nline, size is the number of variables (proteins) in the cell, ncelltot the total number of cells in the embryo""" result = numpy.zeros( (size, ncelltot), dtype=float ) # creates a table result to store data, results[i,j] will contain the concentration of protein i in cell j at time defined by nline colors = palette.color_generate(size) legendkey = [] linestyle = ['-', '--', ':', '-.'] cursor = 0 # cursor will be the index of the column linecache.clearcache() line = linecache.getline(Name, nline - 1) # get the line we want to plot plt.rc('axes', linewidth=2) fig = plt.figure() ax = fig.gca() s = line.split() if list_species == []: list_toplot = range(size) else: list_toplot = list_species list_toplot = range(size) for index in s: # takes each variable in the line if (cursor > 0): ncell = int( (cursor - 1) / size ) #computes the corresponding cell : column 1 to size corresponds to cell 0, size+1 to 2*size corresponds to cell 1, ... ngene = cursor - 1 - size * ncell #computes the corresponding gene try: result[ngene, ncell] = float(index) #assigns it to the table result except Exception: display_error( str(ngene) + str(ncell) + str(index) + "Error in Plot_Profile") cursor += 1 n_position = numpy.zeros((ncelltot), dtype=float) # print "Tab filled" for i in range(size): style = '--' #print i if i in list_output: style = '-' if i in list_toplot: ax.plot(result[i], style, color=colors[i], lw=4.0) legendkey.append("Species %i" % i) fontsize = 20 # for tick in ax.xaxis.get_major_ticks(): # tick.label1.set_fontsize(fontsize) # tick.label1.set_fontweight('bold') # for tick in ax.yaxis.get_major_ticks(): # tick.label1.set_fontsize(fontsize) # tick.label1.set_fontweight('bold') ax.set_xlabel('Position', fontsize=20, fontweight='bold') ax.set_ylabel('Concentration', fontsize=20, fontweight='bold') #plt.legend(loc=0) ax.legend(legendkey) #ax.set_yscale('log') if not no_popup: plt.show() return fig
def Plot_Data(Name, ncell, size, nstep, list_species=[], list_time=[], list_output=[], npoints=500, no_popup=False): """ Plot the concentrations of all proteins in one cell vs time ncell = which cell [0.,,) size = number of proteins nstep = number of time steps (beginning from 0) to plot npoints= number of points for each curve """ colors = palette.color_generate(size) data = open(Name, "r") legendkey = [] if list_species == []: list_toplot = range(size) else: list_toplot = list_species result = numpy.zeros( (size, npoints), dtype=float ) # creates a table result to store data, results[i,j] will contain the concentration of protein i at time j in the cell ncell given as an argument linecache.clearcache() fig = plt.figure() ax = fig.gca() for indexstep in range(npoints): line = linecache.getline(Name, int(indexstep * nstep / npoints)) # reads a line s = line.split() # splits each line and puts it in an array for index in s: for ngene in range(size): try: result[ngene, indexstep] = float(s[1 + ncell * size + ngene]) # with previous convention s[1+ncell*size+ngene] contains P_ngene_Cell_ncell except Exception: msg = "Error in Plot_data, on string {}, unable to reach index {}" msg = msg.format(s, 1 + ncell * size + ngene) display_error(msg) for i in range(size): style = '-' if i in list_output: style = '-' if i in list_toplot: plt.plot(result[i], style, color=colors[i], lw=4.0) # plt.ylim(ymax=1.2) if (len(list_time) > 0) and (list_time[i] >= 0): position = float(list_time[i]) ax.text(position - 15, result[i][list_time[i]] + 0.1, str(i), fontsize=20, fontweight='bold', color=colors[i]) legendkey.append("Species %i" % i) fontsize = 20 # for tick in ax.xaxis.get_major_ticks(): # tick.label1.set_fontsize(fontsize) # tick.label1.set_fontweight('bold') # for tick in ax.yaxis.get_major_ticks(): # tick.label1.set_fontsize(fontsize) # tick.label1.set_fontweight('bold') ax.set_xlabel('Time, Cell=' + str(ncell), fontsize=20, fontweight='bold') ax.set_ylabel('Concentration', fontsize=20, fontweight='bold') ax.legend(legendkey, loc='best') if not no_popup: plt.show() return fig
def Plot_pMHC(Name, ncelltot, size, ntau, position='best', list_species=[], list_AP=[], list_output=[]): """ Plot profile of all proteins at time nline, size is the number of variables (proteins) in the cell, ncelltot the total number of cells in the embryo""" result = numpy.zeros( (size, ncelltot, ntau), dtype=float ) # creates a table result to store data, results[i,j] will contain the concentration of protein i in cell j at time defined by nline colors = palette.color_generate(size) plt.clf() plt.hold(True) legendkey = [] linestyle = ['-', '--', ':', '-.'] cursor = 0 # cursor will be the index of the column linecache.clearcache() line = linecache.getline(Name, 1) # get the line we want to plot s = line.split() if list_species == []: list_toplot = range(size) else: list_toplot = list_species for index in s: # takes each variable in the line if (cursor > 0): ncell = int( (cursor - 1) / (ntau * size) ) #computes the index of corresponding initial condition : column 1 to size*tau corresponds to CI 0, size*tau+1 to 2*size*tau corresponds to CI 2 idtau = int((cursor - 1 - size * ntau * ncell) / size) #computes the corresponding tau ngene = cursor - 1 - size * ntau * ncell - size * idtau #ngene = int((cursor - 1 - size * ntau*ncell)/ntau) #computes the corresponding species #idtau=cursor-1-size * ntau*ncell-ngene*ntau #computes the corresponding tau #print ngene,ncell,idtau try: result[ngene, ncell, idtau] = float(index) #assigns it to the table result except Exception: display_error( str(ngene) + ' ' + str(ncell) + ' ' + str(idtau) + ' ' + str(index) + "\nError in Plot_Profile") cursor += 1 n_position = numpy.zeros((ncelltot), dtype=float) # print "Tab filled" for k in range(ntau): plt.subplot(1, ntau, k + 1) plt.rc('axes', linewidth=2) ax = plt.gca() ax.set_yscale('log') plt.ylim([0.01, 100000]) for i in range(size): style = '-' #print i if i in list_output: style = '-' if i in list_toplot: plt.plot(result[i, :, k], style, color=colors[i], lw=4.0) legendkey.append("Species %i" % i) fontsize = 20 for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) tick.label1.set_fontweight('bold') for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) tick.label1.set_fontweight('bold') plt.xlabel('Position', fontsize=20, fontweight='bold') plt.ylabel('Concentration', fontsize=20, fontweight='bold') plt.xlim(0, 20) plt.legend(legendkey, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.show()
def plot_mutation_fitness_deviation(self, only_one_mutation=True, networks=None, ploted_ratio=1): """ Plot the deviation of fitness in the fitness space caused by a generation's mutation. Arg: only_one_mutation (bool): If True, plot only the networks that undergone only a single mutation durign a generation. """ from phievo.AnalysisTools import plotly_graph dict_data = {} if networks: if type(networks) == list: networks = {net["ind"]: net for net in networks} else: networks = self.networks for net_ind, net_inf in networks.items(): if net_inf["las"] is None or (only_one_mutation and len(net_inf["las"]) != 1): continue label = "-".join(net_inf["las"]) try: parent = networks[net_inf["par"]] except KeyError: ## Parent not provided in the dict continue diff = [ net_inf["fit"][0] - parent["fit"][0], net_inf["fit"][1] - parent["fit"][1] ] data = { "diff": diff, "label": "Net #{}\nparent #{}\nmutation: {}\nfitness change:{}".format( net_inf["ind"], parent["ind"], label, str(diff)) } dict_data[label] = dict_data.get(label, []) + [data] plot_list = [] colors = palette.color_generate(len(dict_data)) for mut_ind, mut_name in enumerate(dict_data.keys()): mutation = dict_data[mut_name] x_val = [mut["diff"][0] for mut in mutation] y_val = [mut["diff"][1] for mut in mutation] hover_info = [mut["label"] for mut in mutation] L = len(x_val) if ploted_ratio != 1: selected_indexes = np.random.choice(range(L), int(L * ploted_ratio), replace=False) x_val = np.array(x_val)[selected_indexes] y_val = np.array(y_val)[selected_indexes] hover_info = np.array(hover_info)[selected_indexes] trace = plotly_graph.go.Scatter( x=x_val, y=y_val, mode='markers', name=mutation, marker=dict(size=14, color=colors[mut_ind]), hoverinfo="text", text=hover_info, ) plot_list.append(trace) plotly_graph.py.plot(plot_list)
def plot_pareto_fronts(self, generations, max_rank=1, with_indexes=False, legend=False, xlim=[], ylim=[], colors=[], gradient=[], xlabel="F_1", ylabel="F_2", s=50, no_popup=False): """ Plot every the network of the selected generations in the (F_1,F_2) fitness space. Args: generations (list): list of the selected generations max_rank (int): In given population plot only the network of rank <=max_rank with_indexes(bool): NotImplemented legend(bool): NotImplemented xlim (list): [xmax,xmin] ylim (list): [ymax,ymin] colors (list): List of html colors, one for each generation gradient (list): List of colors to include in the gradient xlabel(str): Label of the xaxis ylabel(str): Label of the yaxis s (float): marker size no_popup(bool): prevents the popup of the plot windows Returns: matplotlib figure """ net_info, fitnesses = self.pareto_generate_fit_dict( generations, max_rank) if not colors and not gradient: colors = { gen: col for gen, col in zip(fitnesses.keys(), palette.color_generate(len(fitnesses))) } if gradient: colors = { gen: col for gen, col in zip( generations, palette.generate_gradient(generations, gradient)) } shapes = ["o", "s", "^"] fig = plt.figure() ax = fig.gca() for gen, ranks in sorted(fitnesses.items(), key=lambda x: x[1]): for ind, rank in enumerate(ranks): if not rank: continue F1, F2 = zip(*rank) ax.scatter(F1, F2, s=s, color=colors[gen], marker=shapes[ind]) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if xlim: ax.set_xlim(xlim) if ylim: ax.set_ylim(ylim) if not no_popup: plt.show() return fig
def pretty_graph(net,extended=True,layout="graphviz"): """ Creates a ready-to-plot graph object from a network. Args: net (:class:`Mutable_Network <phievo.Networks.mutation.Mutable_Network>`) Return: returns a :class:`PlotGraph graph <phievo.Networks.PlotGraph.Graph.Graph>` """ net.__build_dict_types__() size=len(net.dict_types['Species']) colors=palette.color_generate(size) graph = PlotGraph.Graph(layout) # create pydot nodes for all species nodes in net and store in dictionary map_species = {} ## Add the nodes to the graph for nn in net.dict_types['Node']: if not nn.isinstance('Species'): continue name = produce_species_name(nn) node_type = gettype(nn,node_types) node_attributes = dict(global_node_attribute[node_type]) node_attributes["color"] = colors[nn.int_id()] graph.add_node(name,**node_attributes) for nn in net.dict_types['Node']: if isinstance(nn, TModule): succ = net.graph.list_successors(net.graph.list_successors(nn)[0])[0] succ_name = produce_species_name(succ) if extended: ## include TModule to the graph post_species = nn post_name = produce_TModule_name(nn) graph.add_node(post_name,**global_node_attribute['TModule']) param = dict(**global_edge_attribute['Default']) param["label"] = produce_CorePromoter_name(net.graph.list_successors(nn)[0]) ee = graph.add_edge(post_name, succ_name,**param) else: post_species = succ post_name = succ_name for pre in net.graph.list_predecessors(nn): pre_species = net.graph.list_predecessors(pre)[0] #only one species input to TFHill pre_name = produce_species_name(pre_species) if hasattr(net,"fixed_activity_for_TF"): if (pre.activity==1): param = dict(**global_edge_attribute['activation']) param["label"] = produce_TFHill_name(pre) ee = graph.add_edge(pre_name, post_name,**param) else: param = dict(**global_edge_attribute['repression']) param["label"] = produce_TFHill_name(pre) ee = graph.add_edge(pre_name, post_name,**param ) else: param = dict(**global_edge_attribute['Default']) param["label"] = produce_TFHill_name(pre) ee = graph.add_edge(pre_name,post_name,**param) elif isinstance(nn,Interaction): if isinstance(nn, TFHill) or isinstance(nn, CorePromoter): continue elif isinstance(nn,Phosphorylation): namePhospho = nn.label [cataList,listIn,listOut]=net.catal_data(nn) param = dict(**global_edge_attribute['Phospho']) param["label"] = produce_Phospho_name(nn) graph.add_edge(produce_species_name(listIn[0]),produce_species_name(listOut[0]), **param) param["arrowstyle"] = "-|>" param["label"] = produce_Phospho_name(nn,cat=True) graph.add_edge(produce_species_name(cataList[0]),produce_Phospho_name(nn),**param) elif isinstance(nn,PPI): namePPI = produce_PPI_name(nn) PPI_components = net.graph.list_predecessors(nn) PPI_complex=net.graph.list_successors(nn)[0] graph.add_node(namePPI,**global_node_attribute["PPI"]) param = dict(**global_edge_attribute['PPI']) param["label"] = produce_PPI_name(nn) graph.add_edge(namePPI,produce_species_name(PPI_complex),**param) for compo in PPI_components: param["label"] = "" param["arrowstyle"]="-" graph.add_edge(produce_species_name(compo),namePPI,**param) elif isinstance(nn,Degradation): nameDegrad = produce_Degradation_name(nn) shreder = net.graph.list_predecessors(nn)[0] degraded = net.graph.list_successors(nn)[0] graph.add_edge(produce_species_name(shreder),produce_species_name(degraded), label=nameDegrad,**global_edge_attribute["Degradation"]) elif nn.label == "Simple_Phosphorylation": namePhospho = nn.label [listCata,listIn,listOut]=net.catal_data(nn) param = dict(**global_edge_attribute['Phospho']) param["color"] = "#B42B3C" param["label"] = produce_Phospho_name(nn) graph.add_edge(produce_species_name(listIn[0]),produce_species_name(listOut[0]), **param) param["arrowstyle"] = "-|>" param["label"] = produce_Phospho_name(nn,cat=True) graph.add_edge(produce_species_name(listCata[0]),produce_Phospho_name(nn),**param) elif nn.label == "Simple_Dephosphorylation": namePhospho = nn.label [listCata,listIn,listOut]=net.catal_data(nn) param = dict(**global_edge_attribute['Phospho']) param["color"] = "#2B39B4" param["label"] = produce_Phospho_name(nn) graph.add_edge(produce_species_name(listIn[0]),produce_species_name(listOut[0]), **param) param["arrowstyle"] = "-|>" param["label"] = produce_Phospho_name(nn,cat=True) graph.add_edge(produce_species_name(listCata[0]),produce_Phospho_name(nn),**param) elif nn.label == "KPR_Binding": binding_name = 'LR' binding_components = net.graph.list_predecessors(nn) binding_complex=net.graph.list_successors(nn)[0] graph.add_node(binding_name,**global_node_attribute["Binding"]) param = dict(**global_edge_attribute['Binding']) param["label"] = binding_name graph.add_edge(binding_name,produce_species_name(binding_complex),**param) for compo in binding_components: param["label"] = "" param["arrowstyle"]="-" graph.add_edge(produce_species_name(compo),binding_name,**param) elif nn.label == "Initial_Concentration": name_conc = nn.id spec = net.graph.list_successors(nn)[0] graph.add_node(name_conc,**global_node_attribute["PPI"]) param = dict(**global_edge_attribute['PPI']) param["label"] = "" param["arrowstyle"]="-" graph.add_edge(produce_species_name(spec),name_conc,**param) elif nn.label == "KPR_Unbinding": continue else: inputs = net.graph.list_predecessors(nn) outputs = net.graph.list_successors(nn) for inp in inputs: for out in outputs: graph.add_edge(produce_species_name(inp),produce_species_name(out), label=nn.id,**global_edge_attribute["Default"]) return graph