Beispiel #1
0
def visu_node_edge(gr, size, color, viewBorderColor, viewBorderWidth):
    """
  Input : The graph, the viewSize, the viewColor property, the viewBorderColor and the viewBorderWidth properties
  Function : Applies a style with the help of a dictionary "aspect" on the nodes and the edges regarding their properties
  Output : NONE
  """
    interaction = gr["Interaction"]
    expression = gr["Expression"]
    aspect = {
        "node": {
            "up": [tlp.Color(0, 255, 0),
                   tlp.Size(2, 2, 2)],
            "down": [tlp.Color(255, 0, 0),
                     tlp.Size(2, 2, 2)],
            "stable": [tlp.Color(105, 105, 105),
                       tlp.Size(1, 1, 1)],
            "intergenic": [tlp.Color(200, 200, 200),
                           tlp.Size(1, 1, 1)],
            "nan": [tlp.Color(255, 255, 255),
                    tlp.Size(1, 1, 1)]
        },
        "edge": {
            "gain": [tlp.Color.Blue, 10],
            "loss": [tlp.Color.Yellow, 10],
            "stable": [tlp.Color.Gray, 0]
        }
    }
    for node in gr.getNodes():
        color[node] = aspect["node"][expression[node]][0]
        size[node] = aspect["node"][expression[node]][1]
    for edge in gr.getEdges():
        viewBorderColor[edge] = aspect["edge"][interaction[edge]][0]
        viewBorderWidth[edge] = aspect["edge"][interaction[edge]][1]
        color[edge] = aspect["edge"][interaction[edge]][0]
Beispiel #2
0
def Graphism(graph, viewShape, viewColor, viewLabel, Locus, viewBorderColor,
             viewBorderWidth, viewSize, Negative, Positive):
    """ Prétraitement colorant les arêtes et les noeuds """
    for n in graph.getEdges():
        viewShape[n] = tlp.EdgeShape.BezierCurve
        if (Negative[n] == False and Positive[n] == True):
            viewColor[n] = tlp.Color.Jade
        if (Negative[n] == True and Positive[n] == False):
            viewColor[n] = tlp.Color.Salmon
        if (Negative[n] == True and Positive[n] == True):
            viewColor[n] = tlp.Color.Lilac
        if (Negative[n] == False and Positive[n] == False):
            viewColor[n] = tlp.Color.Black

    for n in graph.getNodes():
        viewLabel[n] = Locus[n]
        viewShape[n] = tlp.NodeShape.RoundedBox
        viewColor[n] = tlp.Color.BlueGreen
        viewBorderColor[n] = tlp.Color.Black
        viewBorderWidth[n] = 3
        viewSize[n] = tlp.Size(1, 0.3, 1)
        if (n.id == 1307):
            viewLabel[n] = " LacZ "
            viewColor[n] = tlp.Color.Red
            viewSize[n] = tlp.Size(20, 8, 20)
Beispiel #3
0
def main(graph):
    #graph.applyAlgorithm("Incremental")
    pos = graph.getLayoutProperty("viewLayout")
    previous_pos = tlp.LayoutProperty(graph)
    color = graph.getColorProperty("viewColor")
    size = graph.getSizeProperty("viewSize")
    it = 0
    steps = 100
    for g in graph.getSubGraphs():
        print(g)
        sg_pos = g.getLocalLayoutProperty("viewLayout")
        is_new_node = g.getLocalBooleanProperty("isNewNode")
        is_new_edge = g.getLocalBooleanProperty("isNewEdge")
        sg_color = g.getLocalColorProperty("viewColor")
        for n in graph.getNodes():
          if not n in g.getNodes():
            color[n] = tlp.Color(0, 0, 0, 0) 
            pos[n] = sg_pos[g.getOneNode()]
          else:
            color[n] = sg_color[n]
            pos[n] = sg_pos[n]
        for e in graph.getEdges():
          if not e in g.getEdges():
            color[e] = tlp.Color(0, 0, 0, 0) 
          else:
            color[e] = sg_color[e]
        if it > 0:
            for n in is_new_node.getNodesEqualTo(True):
                pos[n] = sg_pos[n]
                color[n].setA(0)
                size[n] = tlp.Size(6)
            for e in is_new_edge.getEdgesEqualTo(True):
                color[e].setA(0)   
            for i in range(1, steps + 1):
                t = 1.0 * i / steps # "/" operator <=> integer division in python 2.7, hence the float constant
                for n in g.getNodes():
                    if is_new_node[n]:
                        alpha = lerp(0, 255, t)
                        c = color[n]
                        color[n] = tlp.Color(c.getR(), c.getG(), c.getB(), int(alpha))
                    else:
                        pos[n] = lerp(previous_pos[n], sg_pos[n], t)
                for e in g.getEdges():
                    if is_new_edge[e]:
                        alpha = lerp(0, 255, t)
                        c = color[e]
                        color[e] = tlp.Color(c.getR(), c.getG(), c.getB(), int(alpha))
                updateVisualization(True)
            for n in is_new_node.getNodesEqualTo(True):
                size[n] = tlp.Size(1)              
        updateVisualization(True) 
        #pauseScript()         
        #time.sleep(0.1)    
        previous_pos.copy(sg_pos)
        it += 1
def displayClusterToHeatmap(heatmap,
                            nodes,
                            all_tp,
                            yi,
                            maximum,
                            minimum,
                            stepx,
                            stepy,
                            display_gene_name=False):
    """
  Fonction d'écriture du heatmap en lui même
  Pour chaque gene du groupe crée une ligne avec ces valeur d'expression
  """

    viewSize = heatmap.getSizeProperty("viewSize")
    viewColor = heatmap.getColorProperty("viewColor")
    viewLayout = heatmap.getLayoutProperty("viewLayout")
    viewBorderColor = heatmap.getColorProperty("viewBorderColor")
    viewLabel = graph.getStringProperty("viewLabel")
    Locus = graph.getStringProperty("Locus")
    viewFontSize = graph.getIntegerProperty("viewFontSize")

    heatmap_color = tlp.ColorScale(
        [tlp.Color.Green, tlp.Color.Black, tlp.Color.Red])

    for n in nodes:

        xi = 0
        for tpi, tp in enumerate(all_tp):

            new_n = heatmap.addNode()
            viewSize[new_n] = tlp.Size(stepx, stepy, 1)
            viewLayout[new_n] = tlp.Coord(xi, yi, 0)

            pos = (tp[n] - minimum) / (maximum - minimum)

            viewColor[new_n] = heatmap_color.getColorAtPos(pos)
            viewBorderColor[new_n] = heatmap_color.getColorAtPos(pos)
            xi += stepx

        ## ne marche pas encore
        if display_gene_name:
            new_n = heatmap.addNode()
            viewSize[new_n] = tlp.Size(1, 1, 1)
            viewLayout[new_n] = tlp.Coord(xi, yi, 0)

            viewLabel[new_n] = Locus[n]
            viewFontSize[new_n] = stepy
            viewColor[new_n] = tlp.Color.White
            viewBorderColor[new_n] = tlp.Color.White

        yi += stepy
def visGraph(G) :
  flow=G.getDoubleProperty("flow");
  color=G.getColorProperty("viewColor");
  color.setAllNodeValue(tlp.Color(0,0,0,0));
  size=G.getSizeProperty("viewSize");
  
  for u in G.getNodes() :
    if flow[u]>0 :
      color[u]=tlp.Color(255,0,0,255);
      u_s = (flow[u]-flow.getNodeMin())/(flow.getNodeMax()-flow.getNodeMin())*1.+0.05;
      size[u]=tlp.Size(u_s,u_s,1.);
    else :
      size[u]=tlp.Size(0.001,0.001,1.);
Beispiel #6
0
def construireGrille(distance, gr):
    '''
  Crée une grille où les gènes sont présents en ordonnée, et en abscisse les valeurs d'expression pour un gène.
  Les gènes sont ordonnés en fonction du partitionnement du graphe, quelque soit le niveau.
  '''
    computeY(distance)
    positionY = distance.getDoubleProperty("PositionY")

    layout = gr.getLayoutProperty("viewLayout")
    tps = gr.getDoubleProperty("Tps")
    viewSize = gr.getSizeProperty("viewSize")
    decalageX = 100
    decalageY = 1.5
    Locus = distance.getStringProperty("Locus")
    locusToY = {}
    for node in distance.getNodes():
        locusToY[Locus[node]] = positionY[node]
    Locus = gr.getStringProperty("Locus")
    count = {}
    for n in gr.getNodes():
        currentLocus = Locus[n]
        viewSize[n] = tlp.Size(decalageX, decalageY, 1)
        x = tps[n]
        y = locusToY[Locus[n]]
        layout[n] = tlp.Coord(x * decalageX, y * decalageY, 0)
Beispiel #7
0
    def run(self):

        scaling = 1000
        if self.dataSet:
            scaling = self.dataSet["layout scaling"]

        params = tlp.getDefaultPluginParameters('H3', self.graph)
        success, errmsg = self.graph.applyLayoutAlgorithm("H3", params)
        if not success:
            if self.pluginProgress:
                self.pluginProgress.setError(errmsg)
                return False

        self.graph['viewBorderWidth'].setAllNodeValue(0)
        self.graph['viewShape'].setAllNodeValue(tlp.NodeShape.Sphere)
        self.graph['viewTgtAnchorShape'].setAllEdgeValue(
            tlp.EdgeExtremityShape.Cone)

        for n in self.graph.getNodes():
            w = self.graph['viewSize'][n][0]
            h = self.graph['viewSize'][n][1]
            s = min(w, h)
            self.graph['viewSize'][n] = tlp.Size(s)

        if tulipGuiOk:
            for v in tlpgui.getViewsOfGraph(self.graph):
                if isinstance(v, tlpgui.NodeLinkDiagramComponent):
                    rp = v.getRenderingParameters()
                    rp.setEdge3D(True)
                    rp.setViewArrow(True)
                    rp.setLabelsAreBillboarded(True)
                    v.setRenderingParameters(rp)

            return True
Beispiel #8
0
def layout_components(graph,
                      cycle_number_threshold=40,
                      node_number_threshold=300,
                      margin=5):
    root = graph.getRoot()
    comp_list = tlp.ConnectedTest.computeConnectedComponents(graph)
    followers_rev_or_gen = lambda n, gr: (
        gr.opposite(e, n) for e in gr.getInOutEdges(n)
        if n == gr.source(e) or gr[REVERSIBLE][e] or gr.isMetaNode(
            n) and gr.isMetaNode(gr.opposite(e, n)))
    followers_rev = lambda n, gr: (gr.opposite(e, n)
                                   for e in gr.getInOutEdges(n)
                                   if n == gr.source(e) or gr[REVERSIBLE][e])
    followers_irrev = lambda n, gr: gr.getOutNodes(n)
    followers_irrev_gen_only = lambda n, gr: (m for m in gr.getOutNodes(n)
                                              if gr.isMetaNode(m))

    def process_cc(gr, ns, meta_ns, follower_method_iterator):
        try:
            follower_method = next(follower_method_iterator)
        except StopIteration:
            if len(ns) < node_number_threshold:
                mn = gr.createMetaNode(ns, False)
                cc_graph = root[VIEW_META_GRAPH][mn]
                layout_hierarchically(cc_graph)
                meta_ns.append(mn)
            return
        # iterate over strongly connected components
        for cc in tarjan_iter({n: list(follower_method(n, gr)) for n in ns}):
            if len(cc) > 3:
                if dfs(cc[0], gr, set(), None, cycle_number_threshold, follower_method) \
                        <= cycle_number_threshold:
                    mn = gr.createMetaNode(cc, False)
                    cc_graph = root[VIEW_META_GRAPH][mn]
                    layout_circle(cc_graph, margin)
                    meta_ns.append(mn)
                else:
                    process_cc(gr, cc, meta_ns, follower_method_iterator)

    for ns in comp_list:
        gr = graph.inducedSubGraph(ns)
        meta_ns = []
        process_cc(
            gr, (n for n in gr.getNodes() if gr[TYPE][n] != TYPE_COMPARTMENT),
            meta_ns,
            iter((followers_rev_or_gen, followers_rev, followers_irrev,
                  followers_irrev_gen_only)))
        for mn in meta_ns:
            root[VIEW_SHAPE][mn] = COMPARTMENT_SHAPE
            w, h = get_mn_size(mn, root)
            root[VIEW_SIZE][mn] = tlp.Size(w, h)
        if gr.numberOfNodes() < node_number_threshold and \
                not next((n for n in gr.getNodes() if root[TYPE][n] == TYPE_COMPARTMENT), False):
            layout_hierarchically(gr)
        else:
            layout_force(gr, margin)
        for mn in meta_ns:
            gr.openMetaNode(mn)
def apply_node_coordinates(graph, n2xy):
    root = graph.getRoot()
    for n in graph.getNodes():
        n_id = root[ID][n]
        if n_id in n2xy:
            xywh = n2xy[n_id]
            if isinstance(xywh, dict):
                for r_id, ((x, y), (w, h)) in xywh.items():
                    if root[CLONE_ID][n].find(r_id) != -1:
                        root[VIEW_LAYOUT][n] = tlp.Coord(x, y)
                        root[VIEW_SIZE][n] = tlp.Size(w, h)
                        break
            else:
                (x, y), (w, h) = xywh
                root[VIEW_LAYOUT][n] = tlp.Coord(x, y)
                root[VIEW_SIZE][n] = tlp.Size(w, h)
        elif graph.isMetaNode(n):
            x, y = 0, 0
            w, h = 0, 0
            count = 0
            for m in root[VIEW_META_GRAPH][n].getNodes():
                if root[ID][m] in n2xy:
                    xywh_ = n2xy[root[ID][m]]
                    if isinstance(xywh_, dict):
                        for r_id, ((x_, y_), (w_, h_)) in xywh_.items():
                            if root[CLONE_ID][m].find(r_id) != -1:
                                x += x_
                                y += y_
                                w += w_
                                h += h_
                                count += 1
                                break
                    else:
                        (x_, y_), (w_, h_) = xywh_
                        count += 1
                        x += x_
                        y += y_
                        w += w_
                        h += h_
            if count:
                root[VIEW_LAYOUT][n] = tlp.Coord(x / count, y / count)
                root[VIEW_SIZE][n] = tlp.Size(w, h)
    root[VIEW_LAYOUT].setAllEdgeValue([])
def preTraitementVisualisation(graph):
    """
  Pré-traitement & première visualisation du graph
  """

    # Partie 1

    viewLabel = graph.getStringProperty("viewLabel")
    Locus = graph.getStringProperty("Locus")
    viewSize = graph.getSizeProperty("viewSize")
    viewFontSize = graph.getIntegerProperty("viewFontSize")
    viewColor = graph.getColorProperty("viewColor")
    viewTgtAnchorShape = graph.getIntegerProperty("viewTgtAnchorShape")
    viewTgtAnchorSize = graph.getSizeProperty("viewTgtAnchorSize")

    node_size = tlp.Size(100000, 30000, 1)

    for n in graph.getNodes():

        #Ajoute des labels issu de Locus aux neouds du graph
        viewLabel[n] = Locus[n]
        viewFontSize[n] = 1

        #Affection d'une taille non null à chaque sommet afin de pouvoir visualiser correctement les étiquettes
        viewSize[n] = node_size

    # Affectation des couleurs des arretes et la forme des extremités selon le type de régulation (positive ou negative)
    Negative = graph.getBooleanProperty("Negative")
    blue = tlp.Color(58, 95, 205)
    square = tlp.EdgeExtremityShape.Square

    Positive = graph.getBooleanProperty("Positive")
    green = tlp.Color(69, 139, 0)
    arrow = tlp.EdgeExtremityShape.Arrow

    for e in graph.getEdges():

        if Negative[e] is True:
            #Regulation negatif
            viewColor[e] = blue
            viewTgtAnchorShape[e] = square

        elif Positive[e] is True:
            #regulation poistive
            viewColor[e] = green
            viewTgtAnchorShape[e] = arrow

            viewTgtAnchorSize[e] = node_size

    #Affectation des positions aux sommets du graphe par l'application un model de force "FM^3 (OGDF)"
    viewLayout = graph.getLayoutProperty("viewLayout")

    fm3pParams = tlp.getDefaultPluginParameters("FM^3 (OGDF)", graph)
    fm3pParams["Unit edge length"] = 400
    graph.applyLayoutAlgorithm("FM^3 (OGDF)", viewLayout, fm3pParams)
Beispiel #11
0
def Heatmap(heatmap, graph, TP, viewColor, viewSize, viewMCLMetric, viewMean,
            viewStd):
    """ Permet la création de la heatmap """
    maxCluster = 0
    count = 1.0

    for n in graph.getNodes():
        if viewMCLMetric[n] > maxCluster:
            maxCluster = int(viewMCLMetric[n])

    for j in range(maxCluster):
        for n in graph.getNodes():
            if viewMCLMetric[n] == j:
                for i in range(len(TP)):
                    tpValue = (TP[i][n] - viewMean[n]) / viewStd[n]
                    if (tpValue >= 0):
                        heatmap.addNode({
                            "viewLayout":
                            tlp.Coord(i, count / 20.0, 0),
                            "viewColor":
                            tlp.Color(0, int(255 / 2 * tpValue), 0),
                            "viewSize":
                            tlp.Size(1, 0.05, 1),
                            "viewMCLMetric":
                            j
                        })
                    else:
                        heatmap.addNode({
                            "viewLayout":
                            tlp.Coord(i, count / 20.0, 0),
                            "viewColor":
                            tlp.Color(-int(255 / 2 * tpValue), 0, 0),
                            "viewSize":
                            tlp.Size(1, 0.05, 1),
                            "viewMCLMetric":
                            j
                        })
                count += 1
Beispiel #12
0
def pretraitement(graph, Locus, Negative, Positive, viewBorderColor, viewLabel,
                  viewLayout, viewSize):
    size = 1000
    for n in graph.getNodes():
        viewSize[n] = tlp.Size(10000, 3000, 10)
        viewLabel[n] = Locus[n]
    for n in graph.getEdges():
        if Negative[n] == True:
            if Positive[n] == True:
                viewBorderColor[n] = tlp.Color.Black
            else:
                viewBorderColor[n] = tlp.Color(0, 0, 225)
        elif Positive[n] == True:
            viewBorderColor[n] = tlp.Color(0, 200, 0)
Beispiel #13
0
def pretraitement(graph, Locus, Negative, Positive, viewBorderColor, viewLabel, viewLayout, viewSize):
  '''
  Change la taille et la couleur des éléments du graphe afin qu'il soit plus lisible
  '''
  size = 1000
  for n in graph.getNodes():
    viewSize[n] = tlp.Size(10000,3000,10)
    viewLabel[n] = Locus[n]
  for n in graph.getEdges():
    if Negative[n] == True:
      if Positive[n] == True:
        viewBorderColor[n] = tlp.Color.Black
      else:
        viewBorderColor[n] = tlp.Color(0,0,225)
    elif Positive[n] == True:
      viewBorderColor[n] = tlp.Color(0,200,0)
Beispiel #14
0
def defineGraph(graph, Locus, viewLabel, viewColor, viewSize, Positive,
                Negative):
    for n in graph.getNodes():

        viewLabel[n] = str(Locus[n])
        #viewShape[n] =
        viewSize[n] = tlp.Size(1, 2, 3)

    for n in graph.getEdges():
        if ((Positive[n] == True) and (Negative[n] == False)):
            viewColor[n] = tlp.Color.Blush
        elif ((Positive[n] == False) and (Negative[n] == True)):
            viewColor[n] = tlp.Color.Sapphire
        elif ((Positive[n] == True) and (Negative[n] == True)):
            viewColor[n] = tlp.Color.Orange
        elif ((Positive[n] == False) and (Negative[n] == False)):
            viewColor[n] = tlp.Color.Green
def createTreeNode(heatmap, dx, yi, yinext, label):
    """
  Gere la creation d'un neouds du cluster
  """
    viewLayout = graph.getLayoutProperty("viewLayout")
    viewLabel = graph.getStringProperty("viewLabel")
    viewColor = heatmap.getColorProperty("viewColor")
    viewSize = heatmap.getSizeProperty("viewSize")

    ynode = yi + (yinext - yi) / 2.0
    xnode = -dx
    node = heatmap.addNode()
    viewLayout[node] = tlp.Coord(xnode, ynode, 0)
    viewLabel[node] = label
    viewColor[node] = tlp.Color.White
    viewSize[node] = tlp.Size(1, 1, 0)
    return node
Beispiel #16
0
def construireGrille(distance, gr):
    increment = getIncrement(distance, distance)
    positionY = distance.getDoubleProperty("PositionY")

    layout = gr.getLayoutProperty("viewLayout")
    tps = gr.getDoubleProperty("Tps")
    viewSize = gr.getSizeProperty("viewSize")
    decalageX = 100
    decalageY = 1.5
    Locus = distance.getStringProperty("Locus")
    locusToY = {}
    for node in distance.getNodes():
        locusToY[Locus[node]] = positionY[node]
    Locus = gr.getStringProperty("Locus")
    count = {}
    for n in gr.getNodes():
        currentLocus = Locus[n]
        viewSize[n] = tlp.Size(decalageX, decalageY, 1)
        x = tps[n]
        y = locusToY[Locus[n]]
        layout[n] = tlp.Coord(x * decalageX, y * decalageY, 0)
Beispiel #17
0
def preProcess(graph,locus,label,size,color,regPositive,regNegative,layout,labelColor,labelBorderColor):
  """ Function for preprocessing the root graph before applying main algorithms.

  This function permits to get the first vizualisation of the root graph. It will apply
  labels corresponding to the locus at each nodes. A size to each nodes in order to be able to 
  see the labels. A color to each edges of the root graph in function of their regulation type.
  And finally, a layout algorithm, here the "Random Layout", to store a position for each nodes.

  Args:
    rootGraph (tlp.Graph) : the graph to preprocess and visualize
    locus (tlp.StringProperty) : a property linked to the loci of a gene, or a node
    label (tlp.StringProperty) : a property linked to the "viewLayout" of the root graph 
    size (tlp.DoubleProperty) : a property linked to the "viewSize" of the root graph 
    color (tlp.ColorProperty) : a property linked to the "viewColor" of the root graph 
    regPositive (tlp.BooleanProperty) : a property linked to the positive regulation of a gene, represented by the edges
    regPositive (tlp.BooleanProperty) : a property linked to the negative regulation of a gene, represented by the edges
    layout (tlp.LayoutProperty) : a property linked to the "viewLayout" of the root graph
    labelColor (tlp.ColorProperty) : a property linked to the "viewLabelColor" of the root graph 
    labelBorderColor (tlp.ColorProperty) : a property linked to the "viewLabelBorderColor" of the root graph

  Returns:
    None
  """
  tlpgui.closeAllViews()
  createView(graph)
  for edge in graph.getEdges():
    if(regNegative[edge] == True and regPositive[edge] == False):
      color[edge] = tlp.Color.Red
    elif(regNegative[edge] == False and regPositive[edge] == True):
      color[edge] = tlp.Color.Green
    elif(regNegative[edge] == True and regPositive[edge] == True):
      color[edge] = tlp.Color.Blue
    else:
      color[edge] = tlp.Color.Amber
  label.copy(locus)
  color.setAllNodeValue(tlp.Color.Gray)
  labelColor.setAllNodeValue(tlp.Color.SlateGray)
  labelBorderColor.setAllNodeValue(tlp.Color.SlateGray)
  size.setAllNodeValue(tlp.Size(5,5,5))  
  graph.applyLayoutAlgorithm("Random layout",layout)
Beispiel #18
0
def pretraitement(graph, Locus, Negative, Positive, viewBorderColor, viewLabel,
                  viewLayout, viewSize):
    for n in graph.getNodes():
        print(n)

    size = 1000
    for n in graph.getNodes():
        x = random.random() * size
        y = random.random() * size
        viewLayout[n] = tlp.Coord(x, y, 0)
        viewSize[n] = tlp.Size(10, 10, 10)
        viewLabel[n] = Locus[n]
    for n in graph.getEdges():
        if Negative[n] == True:
            if Positive[n] == True:
                viewBorderColor[n] = tlp.Color.Blue
            else:
                viewBorderColor[n] = tlp.Color.Green
        elif Positive[n] == True:
            viewBorderColor[n] = tlp.Color.Red
        else:
            viewBorderColor[n] = tlp.Color.Violet
Beispiel #19
0
def rotate_generalized_ns(graph):
    root = graph.getRoot()
    view_layout = root.getLayoutProperty(VIEW_LAYOUT)
    for n in (n for n in graph.getNodes() if graph.isMetaNode(n)
              and root[TYPE][n] in [TYPE_REACTION, TYPE_SPECIES]):
        lo = view_layout[n]
        meta_neighbours = lambda nodes: sorted(
            (t for t in nodes if root.isMetaNode(t)),
            key=lambda t: -root[VIEW_META_GRAPH][t].numberOfNodes())
        o_n_1 = meta_neighbours(graph.getInNodes(n))
        o_n_2 = meta_neighbours(graph.getOutNodes(n))
        if not o_n_1:
            alpha = get_alpha(lo, view_layout[o_n_2[0]]) if o_n_2 else 0
        elif not o_n_2:
            alpha = get_alpha(view_layout[o_n_1[0]], lo)
        else:
            alpha = get_alpha(view_layout[o_n_1[0]], view_layout[o_n_2[0]])

        # if the nodes are aligned horizontally, the labels overlap,
        # so let's avoid such a situation
        if abs(alpha % 180) == 90:
            alpha += 45

        mg = root[VIEW_META_GRAPH][n]

        # the diagonal length is larger than the side for squares
        if abs(alpha % 90) == 45 and TYPE_SPECIES != root[TYPE][n]:
            n_h = root[VIEW_SIZE][n].getH() / 2
            view_layout.translate(tlp.Coord(0, n_h * (1 - sqrt(2))), mg)
            view_layout.scale(tlp.Coord(0, sqrt(2)), mg)

        view_layout.rotateZ(-alpha, mg)

        # as Tulip considers everything to be a square when opening meta nodes,
        # and spreads the nodes along the diagonal,
        # we'd rather pretend that our node was slightly smaller
        if TYPE_SPECIES == root[TYPE][n] and abs(alpha % 90) != 0:
            r = root[VIEW_SIZE][n].getW() / sqrt(2)
            root[VIEW_SIZE][n] = tlp.Size(r, r)
Beispiel #20
0
def setNodesSize(g, size):
    nodeSize = tlp.Size(NODE_WIDTH, NODE_HEIGHT, 0)
    for node in g.getNodes():
        size[node] = nodeSize
def buildHeatMap(graph, heatmap, all_tp, cluster_metric):

    viewSize = graph.getSizeProperty("viewSize")
    viewColor = graph.getColorProperty("viewColor")
    viewLayout = graph.getLayoutProperty("viewLayout")
    viewBorderColor = graph.getColorProperty("viewBorderColor")

    clusters = getClusters(graph, cluster_metric)
    print(clusters)
    # Recherche de la valeur d'expression min et max pour l'intensité de couleur du heatmap
    # On met graph en parametre pour bien prendre en compte seulement les niveaux d'expression du graph pour lequel on fait le heatmap
    # Si jamais on a filtré ce graph là , le max ou min peut différer du graph original
    minimum = all_tp[0].getNodeMin(graph)
    maximum = all_tp[0].getNodeMax(graph)

    for tp in all_tp:
        minimum = all_tp[0].getNodeMin(
            graph) if all_tp[0].getNodeMin(graph) < minimum else minimum
        maximum = all_tp[0].geNodetMax(
            graph) if all_tp[0].getNodeMax(graph) < maximum else maximum

    print(minimum)
    print(maximum)
    heatmap.clear()  # Remove all nodes, edges and sub-graphs from the graph
    heatmap_color = tlp.ColorScale(
        [tlp.Color.Green, tlp.Color.Black, tlp.Color.Red])
    y_step = 2
    x_step = 100

    print("start")
    yi = 0

    for c in clusters:
        yi += 20
        for n in clusters[c]:
            yi += y_step

            xi = 0
            for tp in all_tp:
                xi += x_step
                new_n = heatmap.addNode()
                viewSize[new_n] = tlp.Size(x_step, y_step, 1)
                viewLayout[new_n] = tlp.Coord(xi, yi, 0)
                #
                pos = (tp[n] - minimum) / (maximum - minimum)

                viewColor[new_n] = heatmap_color.getColorAtPos(pos)
                viewBorderColor[new_n] = heatmap_color.getColorAtPos(pos)

    # Ajout de la legende tp dans le heatmap
    viewLabel = heatmap.getStringProperty("viewLabel")
    viewLabelPosition = heatmap.getIntegerProperty("viewLabelPosition")
    viewFontSize = heatmap.getIntegerProperty("viewFontSize")
    xi = 0
    yi = -y_step * 40
    print(yi)

    # display number of TP at the bottom of the heatmap
    for i in range(len(all_tp)):
        xi += x_step
        new_n = heatmap.addNode()
        viewLabel[new_n] = str(i + 1)
        viewLayout[new_n] = tlp.Coord(xi, yi, 1)
        viewFontSize[new_n] = 400
        viewSize[new_n] = tlp.Size(x_step, y_step * 40, 1)
        viewColor[new_n] = tlp.Color.White
        viewBorderColor[new_n] = tlp.Color.White
            def draw():
                """Draw all the methods of the list in subgraphs and color
                 its nodes accordingly to their expression status.
                 Assemble all the subgraphs in one parallel view
                 """
                # Check if all the methods are complete to draw them
                for method in Method.methodLines:
                    if not method.is_complete():
                        return False

                # Copy the original graph in a subgraph to keep it intact
                source = self.graph.addSubGraph("Source")
                copy_graph(source, self.graph)

                # Create a sibling graph of source which will get all the duplicated subgraphs
                parallel_multi_graph = self.graph.addSubGraph(
                    "Parallel Methods Analysis")

                for method in Method.methodLines:
                    # Create a duplicated subgraph
                    subgraph = parallel_multi_graph.addSubGraph(
                        name=str(method))
                    copy_graph(subgraph, source)

                    name_to_node = {
                    }  # Dictionary to associate a gene name to its node

                    # Set all nodes and edges of the subgraph to a neutral color
                    viewColor = subgraph.getColorProperty('viewColor')
                    viewSize = subgraph.getSizeProperty("viewSize")
                    viewColor.setAllEdgeValue(tlp.Color(128, 128, 128, 50))
                    for node in subgraph.getNodes():
                        viewColor[node] = tlp.Color(128, 128, 128, 50)
                        name_to_node[subgraph.getNodePropertiesValues(node)
                                     ["name"]] = node

                    # Get up regulated gene names described by the current method by a cypher query
                    up_regulated = [
                        result["name"] for result in neo_graph.run(
                            "MATCH " + method.cypher +
                            "--(:Group {name:'up'})--(a) RETURN a.name as name"
                        )
                    ]
                    # Emphasize the up regulated nodes
                    for name in up_regulated:
                        if name in name_to_node:  # If the current graph have this gene
                            viewColor[name_to_node[name]] = tlp.Color(
                                0, 204, 0, 255)  # Set the node green
                            viewSize.setNodeValue(name_to_node[name],
                                                  tlp.Size(
                                                      10, 10,
                                                      10))  # Make it bigger

                    # Get down regulated gene names described by the current method by a cypher query
                    down_regulated = [
                        result["name"] for result in neo_graph.run(
                            "MATCH " + method.cypher +
                            "--(:Group {name:'down'})--(a) RETURN a.name as name"
                        )
                    ]
                    # Emphasize the up regulated nodes
                    for name in down_regulated:
                        if name in name_to_node:  # If the current graph have this gene
                            viewColor[name_to_node[name]] = tlp.Color(
                                204, 0, 0, 255)  # Set the node red
                            viewSize.setNodeValue(name_to_node[name],
                                                  tlp.Size(
                                                      10, 10,
                                                      10))  # Make it bigger

                # Align the different sub graphs on a grid layout
                subgraph_grid(parallel_multi_graph, self.dataSet["# Columns"])

                # Set a view of the parallel multi graph and get its parameters
                node_link_view = tlpgui.createNodeLinkDiagramView(
                    parallel_multi_graph)
                rendering_parameters = node_link_view.getRenderingParameters()
                background = node_link_view.state()
                scene = background['scene']

                rendering_parameters.setEdgeColorInterpolate(
                    True)  # Set edge color interpolating from the node ones
                rendering_parameters.setLabelsDensity(
                    -100)  # Don't show any label
                scene = scene.replace(
                    "<background>(255,255,255,255)</background>",  # Set the background to black
                    "<background>(0,0,0,255)</background>")

                # Apply the changed parameters
                background['scene'] = scene
                node_link_view.setState(background)
                node_link_view.setRenderingParameters(rendering_parameters)

                # Finish the plugin execution
                root.destroy()
Beispiel #23
0
def random_size():
    return tlp.Size(rand_c_float(), rand_c_float(), rand_c_float())
Beispiel #24
0
def initLayout(graph, size, layout):  
  new_size = tlp.Size(1.0,1.0,1.0)
  size.setAllNodeValue(new_size, graph)
  
  graph.applyLayoutAlgorithm('Circular', layout)