Ejemplo n.º 1
0
def drawSmallMultiple(graph, line, column, bBox, layout):
    """ Function to compute the translation to be applied on the nodes and edges of the graph passing in parameters. 

  This function permits to apply a translation to each coordinates of each node of the graph. Also, we need
  to changes the control points of the edges, so the translation will be applied there too. At the end of this
  function the small multiple is drawn and placed in the right coordinate in the grid.

  Args:
    graph (tlp.Graph) : the future small multiple 
    line (integer) : the corresponding line of the grid to draw the small multiple
    column (integer) : the corresponding column of the grid to draw the small multiple
    bBox (tlp.BoundingBox) : class to represents the 3D bounding box of the small multiple graph
    layout (tlp.LayoutProperty) : a property linked to the "viewLayout" of the graph

  Returns:
    None
  """
    width = bBox.width()
    height = bBox.height()
    for node in graph.getNodes():
        layout[node] = tlp.Coord((column * width) + layout[node].getX(),
                                 (line * -height) + layout[node].getY(), 0)
    for edge in graph.getEdges():
        newControlPoints = []
        for controlPoint in layout[edge]:
            controlPoint = tlp.Coord((column * width) + controlPoint.getX(),
                                     (line * -height) + controlPoint.getY(), 0)
            newControlPoints.append(controlPoint)
        layout.setEdgeValue(edge, newControlPoints)
Ejemplo n.º 2
0
def placeSmallMultiples(smallMultiplesTree, nbCol):
    bb = tlp.computeBoundingBox(smallMultiplesTree)
    #Multiply by 2 to have a shift between all the graphs
    xmax = bb[1][0] * 2
    ymax = bb[1][1] * 2

    #Shifts all the graphs according to the number of their associated timepoint, the number of columns choosen and the bounding box
    for sg in smallMultiplesTree.getSubGraphs():
        smallLayout = sg.getLayoutProperty("viewLayout")
        sgNames = sg.getName().split(" ")
        sgName = sgNames[0]
        nbSG = int(sgName[2:len(sgName)])

        for i in range(0, nbCol + 1):
            if (nbSG <= nbCol * (i + 1) and nbSG > nbCol * i):
                for node in sg.getNodes():
                    newPos = tlp.Coord(
                        smallLayout[node][0] + xmax * (nbSG - nbCol * i),
                        smallLayout[node][1] - ymax * i, smallLayout[node][2])
                    smallLayout.setNodeValue(node, newPos)

                for edge in sg.getEdges():
                    newEdgePos = []
                    for pos in smallLayout[edge]:
                        newPos = tlp.Coord(pos[0] + xmax * (nbSG - nbCol * i),
                                           pos[1] - ymax * i, pos[2])
                        newEdgePos.append(newPos)
                    smallLayout.setEdgeValue(edge, newEdgePos)
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
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
    def run(self):

        # compute a spanning tree of the input graph
        spanningTree = tlp.TreeTest.computeTree(self.graph)

        # get edges to use an input for the H3 layout implementation from buzzfeed
        # and reverse their orientation as it does not use the same direction as in Tulip graphs
        edges = [self.graph.ends(e)[::-1] for e in spanningTree.getEdges()]

        # compute the layout
        tree = Tree(edges)

        # copy result to Tulip layout property
        self.result.setAllEdgeValue([])
        for n in self.graph.getNodes():
            self.result[n] = tlp.Coord(tree.nodes[n].coord.x,
                                       tree.nodes[n].coord.y,
                                       tree.nodes[n].coord.z)

        # apply some scaling factor to the layout to get a correct rendering
        # in Tulip
        scaling = 1000
        if self.dataSet:
            scaling = self.dataSet["layout scaling"]

        self.result.scale(tlp.Vec3f(scaling))

        # cleanup computed spanning tree
        tlp.TreeTest.cleanComputedTree(self.graph, spanningTree)

        return True
Ejemplo n.º 6
0
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([])
Ejemplo n.º 7
0
def align_generalized_ns(graph):
    root = graph.getRoot()

    meta_ns = {
        n
        for n in graph.getNodes() if graph.isMetaNode(n)
        and root[TYPE][n] in [TYPE_SPECIES, TYPE_REACTION]
    }
    meta_sps = {n for n in meta_ns if TYPE_SPECIES == root[TYPE][n]}
    meta_rs = {n for n in meta_ns - meta_sps if TYPE_REACTION == root[TYPE][n]}

    depends_on = {}
    our_sps, our_rs = set(), set()
    for s in meta_sps:
        rs = set(graph.getInOutNodes(s)) & meta_rs
        sps = set()
        for r in rs:
            sps |= set(graph.getInOutNodes(r)) & meta_sps
        depends_on[s] = sps - {s}
        our_sps |= set(root[VIEW_META_GRAPH][s].getNodes())
    for r in meta_rs:
        our_rs |= set(root[VIEW_META_GRAPH][r].getNodes())

    node2key = {}
    while meta_sps:
        n = min(meta_sps, key=lambda s: len(depends_on[s] & meta_sps))
        meta_sps -= {n}
        for s in root[VIEW_META_GRAPH][n].getNodes():
            rs = set(root.getInOutNodes(s)) & our_rs
            sps = set()
            for r in rs:
                sps |= set(root.getInOutNodes(r)) & our_sps
            sps -= {s}
            node2key[s] = (root[ID][n], root.deg(s), root[ID][s])
            for ss in sps:
                if ss in node2key:
                    node2key[s] = node2key[ss]
    for n in meta_rs:
        for r in root[VIEW_META_GRAPH][n].getNodes():
            node2key[r] = sorted(
                node2key[it] for it in set(root.getInOutNodes(r)) & our_sps)

    for n in meta_ns:
        ns = sorted(root[VIEW_META_GRAPH][n].getNodes(),
                    key=lambda it: node2key[it] if it in node2key else
                    (root[ID][it], 0, ''))  # root[ID][it])
        s = root[VIEW_SIZE][n].getH()
        x0, y0 = s / 2, 0
        x, y = x0, y0
        for m in ns:
            m_h = root[VIEW_SIZE][m].getH() / 2
            y += m_h
            root[VIEW_LAYOUT][m] = tlp.Coord(x, y)
            y += m_h
Ejemplo n.º 8
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)
Ejemplo n.º 9
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
Ejemplo n.º 10
0
 def get_bend_coord(species):
     sample_species = next(
         (s for s in species if not ub_or_single(s, graph)), None)
     if sample_species:
         s_x, s_y = root[VIEW_LAYOUT][sample_species].getX(
         ), root[VIEW_LAYOUT][sample_species].getY()
     else:
         cs_x, cs_y = [root[VIEW_LAYOUT][s].getX() for s in species], \
                      [root[VIEW_LAYOUT][s].getY() for s in species]
         s_x, s_y = (min(cs_x) + max(cs_x)) / 2, (min(cs_y) +
                                                  max(cs_y)) / 2
     r_species_angle = atan2(s_y - r_y, s_x - r_x)
     return tlp.Coord(r_x + r_r * cos(r_species_angle),
                      r_y + r_r * sin(r_species_angle))
Ejemplo n.º 11
0
def bend_ubiquitous_edges(graph, nodes):
    root = graph.getRoot()
    for r in (r for r in nodes if TYPE_REACTION == root[TYPE][r]):
        r_x, r_y = root[VIEW_LAYOUT][r].getX(), root[VIEW_LAYOUT][r].getY()
        r_r = REACTION_SIZE * sqrt(2) / 2 + UBIQUITOUS_SPECIES_SIZE
        for s in (s for s in graph.getInOutNodes(r)
                  if root[UBIQUITOUS][s] or not graph.isMetaNode(s)):
            s_x, s_y = root[VIEW_LAYOUT][s].getX(), root[VIEW_LAYOUT][s].getY()
            alpha = atan2(s_y - r_y, s_x - r_x)
            x0, y0 = r_x + r_r * cos(alpha), r_y + r_r * sin(alpha)
            for m in root[VIEW_META_GRAPH][r].getNodes():
                for e in root.getInOutEdges(m):
                    if s == root.target(e) or s == root.source(e):
                        root[VIEW_LAYOUT][e] = [tlp.Coord(x0, y0)]
Ejemplo n.º 12
0
def straighten_edges_inside_compartments(graph, c_id2borders):
    root = graph.getRoot()
    for n in graph.getNodes():
        c_id = root[COMPARTMENT_ID][n]
        if c_id not in c_id2borders:
            continue
        (c_left_x, c_bottom_y, c_right_x, c_top_y) = c_id2borders[c_id]
        n_x, n_y = root[VIEW_LAYOUT][n].getX(), root[VIEW_LAYOUT][n].getY()
        for e in graph.getInOutEdges(n):
            v = graph.opposite(e, n)
            v_x, v_y = root[VIEW_LAYOUT][v].getX(), root[VIEW_LAYOUT][v].getY()
            if root[VIEW_LAYOUT][e]:
                xy = root[VIEW_LAYOUT][e][0] if n == root.source(
                    e) else root[VIEW_LAYOUT][e][-1]
                v_x, v_y = xy[0], xy[1]
            # if the node v is outside of the n's compartment (c_id)
            if v_x > c_right_x or v_x < c_left_x or v_y > c_top_y or v_y < c_bottom_y:
                # if v is closer to the bottom/top than to the left/right border of the compartment
                if c_left_x < v_x and v_x < c_right_x or \
                        (v_y > c_top_y or v_y < c_bottom_y) and \
                                        min(abs(v_x - c_right_x), abs(v_x - c_left_x)) \
                                        > min(abs(v_y - c_top_y), abs(v_y - c_bottom_y)):
                    # then keep n's x coordinate and set y to the v's y
                    bend = tlp.Coord(n_x, v_y)
                else:
                    bend = tlp.Coord(v_x, n_y)
                if [bend.getX(), bend.getY()] != [v_x, v_y] and [
                        bend.getX(), bend.getY()
                ] != [n_x, n_y]:
                    if n == root.source(e):
                        root[VIEW_LAYOUT][e] = (
                            [bend] + root[VIEW_LAYOUT][e]
                        ) if root[VIEW_LAYOUT][e] else [bend]
                    else:
                        root[VIEW_LAYOUT][e] = (
                            root[VIEW_LAYOUT][e] +
                            [bend]) if root[VIEW_LAYOUT][e] else [bend]
Ejemplo n.º 13
0
def gen_grid(G,nb_points) :
  layout = G.getLayoutProperty("viewLayout")
  for i in range(nb_points) :
    c=tlp.Coord(random.random()*10.,random.random()*10.);
    n=G.addNode();
    layout[n]=c;
  
  G.applyAlgorithm("Delaunay triangulation");
  length=G.getDoubleProperty("length");
  for e in G.getEdges() :
    length[e]=layout[G.source(e)].dist(layout[G.target(e)]);
  is_road=G.getBooleanProperty("is_road");
  is_road.setAllEdgeValue(False);
  for e in G.getEdges() :
    is_road[e]=True;
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
Ejemplo n.º 15
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)
Ejemplo n.º 16
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
Ejemplo n.º 17
0
def apply_layout(graph, onto):
    root = graph.getRoot()
    view_layout = root.getLayoutProperty(VIEW_LAYOUT)
    ubiquitous = root.getBooleanProperty(UBIQUITOUS)

    # before = len(key2coord)
    for n in graph.getNodes():
        if ubiquitous[n]:
            continue
        # if not graph.deg(n):
        # 	continue
        # r = graph.getInOutNodes(n).next()
        # k = get_keys(n, graph, onto, True)[0]
        # keys = ["{0}+{1}".format(k, l) for l in get_keys(r, graph, onto, True)]
        else:
            keys = get_keys(n, graph, onto, True)
        if not keys:
            continue
        coord = next((key2coord[key] for key in keys if key in key2coord), None)
        if coord:
            view_layout[n] = tlp.Coord(coord[0], coord[1])
        else:
            for key in keys:
                key2coord[key] = view_layout[n]
def buildMultiScaleHeatmap(heatmap,
                           clusters,
                           all_tp,
                           lvl,
                           ancestor_node,
                           step_branch,
                           yi,
                           maximum,
                           minimum,
                           stepx,
                           stepy,
                           nb_gene_min=1):
    """
  Recusrsivité
  lancer pour chaque groupe la creation du heatmap ou bien  si il est composé de sous groupe  se relance sur chaque sous groupe
  Gere egalement la création des noeuds et arretes de l'arbre
  """
    viewLayout = graph.getLayoutProperty("viewLayout")

    distance = len(
        all_tp
    ) * stepx - step_branch * lvl  #distance en X des neouds de niveau de partionnement courant

    #  if lvl >= lvl_max: #si on a atteint le niveau de partionnement maximal on transforme cluster en list pour pas avoir de niveau superieur
    #    flat_dico = {}
    #    flat_dico[0] = getFlatList(clusters)
    #    flat_dico['len'] =  clusters['len']
    #    clusters = flat_dico
    #    print(clusters[c])

    for c in clusters:

        #Passer la clé 'len'
        if c == 'len':
            continue

        #Si le cluster est une liste de neouds et non un nouveau dico
        if type(clusters[c]) == list:
            #Si le nombre de gene est inferieur au threshold on passe à la clusteriation suivante
            if nb_gene_min > len(clusters[c]):
                continue

            yinext = yi + len(clusters[c]) * stepy
            #      print(lvl*'    '+"affichage dans le heatmap du cluster groupe"+ str(c)+ " level "+ str(lvl)+"  yi "+str(yi)+"  nb gene" +str(len(clusters[c])) )
            # dans ce cas il n'y pas de niveau supplémentaire on affiche donc les neouds de c dans le heatmap
            displayClusterToHeatmap(heatmap, clusters[c], all_tp, yi, maximum,
                                    minimum, stepx, stepy)

            #creer neouds au niveau de yi et yi +nbneouds * stepy   correspondant au feuilles extrem de chaque groupes
            first_leaf = heatmap.addNode()
            last_leaf = heatmap.addNode()

            viewLayout[first_leaf] = tlp.Coord(0 - stepx / 2, yi, 0)
            viewLayout[last_leaf] = tlp.Coord(0 - stepx / 2, yinext - stepy, 0)

            #creer un neouds à distance d de xi et à distance y0 + yi/2 # et donner le label correspondant au numéro du cluster

            current_node = createTreeNode(heatmap, distance, yi, yinext,
                                          str(int(c)))

            #relier les neouds precedent à ancestor link
            heatmap.addEdge(ancestor_node, current_node)
            heatmap.addEdge(current_node, first_leaf)
            heatmap.addEdge(current_node, last_leaf)

            #
            yi = yinext
        else:  #il y a un nouveau niveau à afficher
            yinext = yi + clusters[c]['len'] * stepy
            current_node = createTreeNode(heatmap, distance, yi, yinext,
                                          str(int(c)))
            heatmap.addEdge(ancestor_node, current_node)

            print(lvl * '    ' + "nouveau niveau de cluster groupe" + str(c) +
                  " level " + str(lvl))
            #creation de ancestor link
            buildMultiScaleHeatmap(heatmap, clusters[c], all_tp, lvl + 1,
                                   current_node, step_branch, yi, maximum,
                                   minimum, stepx, stepy, nb_gene_min)
            yi = yinext
def createHeatmap(graph, heatmap_name, all_tp, lvls_clusters):
    """
  creatHeatmap
  Prépare les paremetre pour lancer la fonction récursive de création de heatmap
  """

    # heatmap_root graph va donner le grpah parent du heatmap

    viewLayout = graph.getLayoutProperty("viewLayout")

    heatmap_root = graph.getSubGraph("heatmap_root")
    if heatmap_root is None:
        print('Creation de heatmap_root')
        heatmap_root = graph.addCloneSubGraph("heatmap_root")

    heatmap = heatmap_root.getSubGraph(heatmap_name)
    if heatmap is None:
        print('Creation de {}'.format(heatmap_name))
        heatmap = heatmap_root.addCloneSubGraph(heatmap_name)
    heatmap.clear()
    #Pour construire le heatmap on part d'un graph vierge

    #Parametre de la carte de chaleur
    nb_gene = lvls_clusters['len']  # nombre d'element en Y
    nb_tp = len(all_tp)  # nombre d'element en X
    stepx = 10  # valeur en dure arbitraire
    ratio = 0.5  # ratio largeur/hauteur du heatmap
    stepy = (
        (nb_tp * stepx) / (ratio * nb_gene)
    )  #determination de stepy en fonction du reste des parametre afin de respecter le ratio
    nb_gene_min = 1  # nombre minimal de gene dans un cluster que la heatmap doit afficher
    #  lvl_max=float('inf') #nombre de niveau de partionnement maximal qu'on souhaite afficher

    #Calcul de la distance en x des nouds de l'arbre
    nb_lvl = getNumberOfLevel(lvls_clusters, lvl=1)
    #  if lvl_max < nb_lvl:
    #    nb_lvl = lvl_max
    print('Il y a {} niveau de partionnement'.format(nb_lvl))
    # step branch correspond a la longuer des branche de l'arbre entre deux niveau partionnemnts
    step_branch = (nb_tp * stepx) / (
        nb_lvl + 1
    )  #largeur du heatmap / nombre de pas (donc ici largeur de l'arbre == largeur heatmap)

    yi = 0
    minimum = all_tp[0].getNodeMin(graph)
    maximum = all_tp[0].getNodeMax(graph)

    for tp in all_tp:
        minimum = tp.getNodeMin(
            graph) if tp.getNodeMin(graph) < minimum else minimum
        maximum = tp.getNodeMax(
            graph) if tp.getNodeMax(graph) > maximum else maximum

    ynode = lvls_clusters["len"] * stepy / 2
    xnode = -step_branch * (nb_lvl + 1)
    ancestor_node = heatmap.addNode(
    )  #noeud correspondant à l'origine de l'arbre
    viewLayout[ancestor_node] = tlp.Coord(
        xnode, ynode, 0
    )  # distant du heatmap d'une largeur de heatmap en X et se situant au milieu du heatmap en Y

    buildMultiScaleHeatmap(heatmap,
                           lvls_clusters,
                           all_tp,
                           lvl=1,
                           ancestor_node=ancestor_node,
                           step_branch=step_branch,
                           yi=yi,
                           maximum=maximum,
                           minimum=minimum,
                           stepx=stepx,
                           stepy=stepy,
                           nb_gene_min=nb_gene_min)
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
Ejemplo n.º 21
0
def random_coord():
    return tlp.Coord(rand_c_float(), rand_c_float(), rand_c_float())
Ejemplo n.º 22
0
def main(graph): 
  Acronyme = graph.getStringProperty("Acronyme")
  Annee_de_financement = graph.getIntegerProperty("Année de financement")
  Code_du_programme = graph.getStringProperty("Code du programme")
  Code_du_projet = graph.getStringProperty("Code du projet")
  Code_du_type_de_partenaire = graph.getStringVectorProperty("Code du type de partenaire")
  Coordinateur_du_projet = graph.getStringProperty("Coordinateur du projet")
  Date_de_debut = graph.getIntegerProperty("Date de début")
  Duree_en_mois = graph.getIntegerProperty("Durée en mois")
  Identifiant_de_partenaire = graph.getStringVectorProperty("Identifiant de partenaire")
  Libelle_de_partenaire = graph.getStringVectorProperty("Libellé de partenaire")
  Lien_Programme = graph.getStringProperty("Lien Programme")
  Lien_Projet = graph.getStringProperty("Lien Projet")
  Montant = graph.getDoubleProperty("Montant")
  Perspectives = graph.getStringProperty("Perspectives")
  Programme = graph.getStringProperty("Programme")
  Publications_et_brevets = graph.getStringProperty("Publications et brevets")
  Resultats = graph.getStringProperty("Résultats")
  Resume = graph.getStringProperty("Résumé")
  Resume_de_la_soumission = graph.getStringProperty("Résumé de la soumission")
  Sigle_de_partenaire = graph.getStringVectorProperty("Sigle de partenaire")
  Titre = graph.getStringProperty("Titre")
  Type_didentifiant = graph.getStringVectorProperty("Type d'identifiant")
  Type_de_partenaire = graph.getStringVectorProperty("Type de partenaire")
  viewBorderColor = graph.getColorProperty("viewBorderColor")
  viewBorderWidth = graph.getDoubleProperty("viewBorderWidth")
  viewColor = graph.getColorProperty("viewColor")
  viewFont = graph.getStringProperty("viewFont")
  viewFontSize = graph.getIntegerProperty("viewFontSize")
  viewIcon = graph.getStringProperty("viewIcon")
  viewLabel = graph.getStringProperty("viewLabel")
  viewLabelBorderColor = graph.getColorProperty("viewLabelBorderColor")
  viewLabelBorderWidth = graph.getDoubleProperty("viewLabelBorderWidth")
  viewLabelColor = graph.getColorProperty("viewLabelColor")
  viewLabelPosition = graph.getIntegerProperty("viewLabelPosition")
  viewLayout = graph.getLayoutProperty("viewLayout")
  viewMetric = graph.getDoubleProperty("viewMetric")
  viewRotation = graph.getDoubleProperty("viewRotation")
  viewSelection = graph.getBooleanProperty("viewSelection")
  viewShape = graph.getIntegerProperty("viewShape")
  viewSize = graph.getSizeProperty("viewSize")
  viewSrcAnchorShape = graph.getIntegerProperty("viewSrcAnchorShape")
  viewSrcAnchorSize = graph.getSizeProperty("viewSrcAnchorSize")
  viewTexture = graph.getStringProperty("viewTexture")
  viewTgtAnchorShape = graph.getIntegerProperty("viewTgtAnchorShape")
  viewTgtAnchorSize = graph.getSizeProperty("viewTgtAnchorSize")

  start_time = time.time()

  partenaire=tlp.newGraph()
  list=[]
  print ('Cr�ation des noeuds:')
  
  for n in graph.getNodes():    
    libPart=Libelle_de_partenaire[n]     
    for i in range (0,len(libPart)):     
      if "Universit�" in libPart[i]:          
        if libPart[i] not in list :        #si on rencontre ce partenaire pour la première fois       
          list.append(libPart[i])
          node=partenaire.addNode()
          x=random.randrange(1,1025,1)
          y=random.randrange(1, 1025, 1)
          projet=[Acronyme[n]]
          communs=[]
          for j in range (0,len(libPart)):      
            if libPart[j]!=libPart[i] and libPart[j] not in communs and "Universit�" in libPart[j]:
              communs.append(libPart[j])    
          dict={"Libell� de partenaire": libPart[i], "Projet" : projet ,"Partenaires communs": communs ,"viewColor":(200,150,80,230) ,"viewLayout":tlp.Coord(x,y,0)}
          partenaire.setNodePropertiesValues(node,dict)
          
        else :  #ce partenaire a déjà un noeud, on le cherche alors parmi tous les noeuds du nouveau graphe, et on ajoute dans ses paramètres le projet n et les partenaires communs 
          for o in partenaire.getNodes():            
            if libPart[i] == partenaire.getStringProperty("Libell� de partenaire")[o] and Acronyme[n] not in partenaire.getStringVectorProperty("Projet")[o] : 
              communs=[]              
              for j in range (0,len(libPart)):      
                if libPart[j]!=libPart[i] and libPart[j] not in communs and libPart[j] not in partenaire.getStringVectorProperty("Partenaires communs")[o] and "Universit�" in libPart[j]:
                  communs.append(libPart[j])
              dict={"Libell� de partenaire": partenaire.getStringProperty("Libell� de partenaire")[o] ,  "Projet" : partenaire.getStringVectorProperty("Projet")[o]+[Acronyme[n]] , "Partenaires communs": partenaire.getStringVectorProperty("Partenaires communs")[o]+communs, "viewColor":(200,150,80,230)}
              partenaire.setNodePropertiesValues(o,dict) 
  
  print ("Cr�ation des ar�tes")
  
  node1=0
  for p in partenaire.getNodes():    
    node2=0
    for q in partenaire.getNodes():      
      for i in partenaire.getStringVectorProperty("Projet")[p] :
        if i in partenaire.getStringVectorProperty("Projet")[q] and partenaire.getStringProperty("Libell� de partenaire")[q] in partenaire.getStringVectorProperty("Partenaires communs")[p] and p!=q and node2>=node1 :     #node1 et node2 pour éviter que les arêtes soient en double     
          e=partenaire.addEdge(p,q)
          dict={"Projet":[i],"Partenaires" :[partenaire.getStringProperty("Libell� de partenaire")[p],partenaire.getStringProperty("Libell� de partenaire")[q]]}
          partenaire.setEdgePropertiesValues(e,dict) 
      node2+=1
    node1+=1
    
    
  print ("Louvain")
  params = tlp.getDefaultPluginParameters('Louvain', partenaire)
  partenaire.applyDoubleAlgorithm('Louvain', params)
  
  tlp.saveGraph(partenaire,"univlouv.tlp")
  interval = time.time() - start_time 
  print ('Total time in seconds:', interval) 
Ejemplo n.º 23
0
def layout_inner_elements(graph, c_id, c_left_x, c_bottom_y, c_right_x,
                          c_top_y):
    root = graph.getRoot()

    neighbours_outside_comp = lambda r: [
        n for n in graph.getInOutNodes(r) if root[COMPARTMENT_ID][n] != c_id
    ]
    neighbours_inside_comp = lambda r: [
        n for n in graph.getInOutNodes(r)
        if root[COMPARTMENT_ID][n] == c_id and not ub_or_single(n, graph)
    ]

    rs = sorted([
        r for r in graph.getNodes() if root[COMPARTMENT_ID][r] == c_id
        and not neighbours_inside_comp(r) and neighbours_outside_comp(r)
    ],
                key=lambda r: -get_n_length(root, r))

    coords = set()
    h_jump, v_jump = True, True
    for r in rs:
        r_w, r_h = root[VIEW_SIZE][r].getW(), root[VIEW_SIZE][r].getH()
        outside_r_metabolites = neighbours_outside_comp(r)
        outside_r_metabolites_not_ub = [
            s for s in outside_r_metabolites if not ub_or_single(s, graph)
        ]
        if outside_r_metabolites_not_ub:
            outside_r_metabolites = outside_r_metabolites_not_ub
        avg_outside_r_metabolite_x, avg_outside_r_metabolite_y = \
            sum(root[VIEW_LAYOUT][s].getX() for s in outside_r_metabolites) / len(outside_r_metabolites), \
            sum(root[VIEW_LAYOUT][s].getY() for s in outside_r_metabolites) / len(outside_r_metabolites)

        inside_y = c_bottom_y + r_h <= avg_outside_r_metabolite_y <= c_top_y - r_h
        inside_x = c_left_x + r_w <= avg_outside_r_metabolite_x <= c_right_x - r_w

        closer_to_the_compartment_bottom = \
            abs(avg_outside_r_metabolite_y - c_bottom_y) < abs(avg_outside_r_metabolite_y - c_top_y)
        closer_to_the_left_comp_border = \
            abs(avg_outside_r_metabolite_x - c_left_x) < abs(avg_outside_r_metabolite_x - c_right_x)
        if inside_x:
            # stay above/below outside metabolites
            r_x = avg_outside_r_metabolite_x
            r_y = c_bottom_y + r_h if closer_to_the_compartment_bottom else c_top_y - r_h
            while (r_x - r_x % REACTION_SIZE,
                   r_y - r_y % REACTION_SIZE) in coords:
                if closer_to_the_left_comp_border:
                    r_x += 3 * r_w
                else:
                    r_x -= 3 * r_w
                if v_jump:
                    r_y += -r_w if closer_to_the_compartment_bottom else r_w
                v_jump = not v_jump
        elif inside_y:
            # stay to the left/right of the outside metabolites
            r_y = avg_outside_r_metabolite_y
            r_x = c_left_x + r_w if closer_to_the_left_comp_border else c_right_x - r_w
            while (r_x - r_x % REACTION_SIZE,
                   r_y - r_y % REACTION_SIZE) in coords:
                if closer_to_the_compartment_bottom:
                    r_y += 3 * r_h
                else:
                    r_y -= 3 * r_h
                if h_jump:
                    r_x += -r_h if closer_to_the_left_comp_border else r_h
                h_jump = not h_jump
        else:
            i = 1
            while True:
                r_x = max(c_left_x + i * r_w,
                          min(avg_outside_r_metabolite_x, c_right_x - i * r_w))
                r_y = max(c_bottom_y + i * r_h,
                          min(avg_outside_r_metabolite_y, c_top_y - i * r_h))
                if (r_x - r_x % REACTION_SIZE,
                        r_y - r_y % REACTION_SIZE) in coords:
                    i += 1
                else:
                    break
        coords.add((r_x - r_x % REACTION_SIZE, r_y - r_y % REACTION_SIZE))

        root[VIEW_LAYOUT][r] = tlp.Coord(r_x, r_y)

    layout_ub_sps(graph, rs, c_id)

    # open_meta_ns(graph, (r for r in graph.getNodes() if root[FAKE][r]))
    root[VIEW_LAYOUT].setAllEdgeValue([])
Ejemplo n.º 24
0
def layout_ub_sps(graph, r_ns=None, c_id=None):
    root = graph.getRoot()
    view_layout = root.getLayoutProperty(VIEW_LAYOUT)
    view_size = root.getSizeProperty(VIEW_SIZE)

    if not r_ns:
        r_ns = (n for n in graph.getNodes() if TYPE_REACTION == root[TYPE][n])

    for r in r_ns:
        x1, y1 = view_layout[r].getX(), view_layout[r].getY()
        for (get_reactants, get_reaction_edges, get_products, direction) \
                in [(graph.getInNodes, graph.getOutEdges, graph.getOutNodes, 1),
                    (graph.getOutNodes, graph.getInEdges, graph.getInNodes, -1)]:

            ubiquitous_reactants = [
                n for n in get_reactants(r) if ub_or_single(n, graph) and (
                    not c_id or root[COMPARTMENT_ID][n] == c_id)
            ]
            ub_reactants_len = len(ubiquitous_reactants)
            if not ub_reactants_len:
                continue
            if ub_reactants_len % 2 == 1:
                ub_reactants_len += 1

            specific_reactants = [
                n for n in get_reactants(r) if not ub_or_single(n, graph)
            ]
            r_radius = get_reaction_r(r, root)
            size = sum(
                root[VIEW_SIZE][ub].getW()
                for ub in ubiquitous_reactants) / len(ubiquitous_reactants)
            if specific_reactants:
                specific_reactant_example = specific_reactants[0]
                x2, y2 = view_layout[specific_reactant_example].getX(
                ), view_layout[specific_reactant_example].getY()
            else:
                specific_products = [
                    n for n in get_products(r) if not ub_or_single(n, graph)
                ]
                if specific_products:
                    specific_product_example = specific_products[0]
                    x3, y3 = view_layout[specific_product_example].getX(
                    ), view_layout[specific_product_example].getY()
                    x2, y2 = x1 - (x3 - x1), y1 - (y3 - y1)
                else:
                    x2, y2 = x1 + view_size[r].getW(
                    ) + size * ub_reactants_len * direction, y1

            # beta is the max angle between the ubiquitous and the specific edges
            gap = 2 * min(60, max(22.5, ub_reactants_len * 20))
            beta = radians(gap / 2)
            d_beta = radians(gap / (ub_reactants_len - 1))

            # alpha is the angle between the horizontal line and the reaction-specific-species edge
            alpha = atan2(y2 - y1, x2 - x1)

            # length of an ubiquitous edge
            ub_edge_r = size * 1.5 + r_radius
            d_ub_edge_r = size

            for ub in ubiquitous_reactants:
                # point (ub_edge_r, 0)
                # rotate alpha - beta
                # move x1, y1
                x3, y3 = x1 + ub_edge_r * cos(
                    alpha - beta), y1 + ub_edge_r * sin(alpha - beta)
                view_layout[ub] = tlp.Coord(x3, y3)
                if beta < 0 or (beta - d_beta > 0):
                    ub_edge_r += (d_ub_edge_r if beta > 0 else -d_ub_edge_r)
                beta -= d_beta
                if beta == 0:
                    beta -= d_beta
Ejemplo n.º 25
0
def main(graph):

    Locus = graph.getStringProperty("Locus")

    Negative = graph.getBooleanProperty("Negative")

    Positive = graph.getBooleanProperty("Positive")

    tp1_s = graph.getDoubleProperty("tp1 s")

    tp10_s = graph.getDoubleProperty("tp10 s")

    tp11_s = graph.getDoubleProperty("tp11 s")

    tp12_s = graph.getDoubleProperty("tp12 s")

    tp13_s = graph.getDoubleProperty("tp13 s")

    tp14_s = graph.getDoubleProperty("tp14 s")

    tp15_s = graph.getDoubleProperty("tp15 s")

    tp16_s = graph.getDoubleProperty("tp16 s")

    tp17_s = graph.getDoubleProperty("tp17 s")

    tp2_s = graph.getDoubleProperty("tp2 s")

    tp3_s = graph.getDoubleProperty("tp3 s")

    tp4_s = graph.getDoubleProperty("tp4 s")

    tp5_s = graph.getDoubleProperty("tp5 s")

    tp6_s = graph.getDoubleProperty("tp6 s")

    tp7_s = graph.getDoubleProperty("tp7 s")

    tp8_s = graph.getDoubleProperty("tp8 s")

    tp9_s = graph.getDoubleProperty("tp9 s")

    viewBorderColor = graph.getColorProperty("viewBorderColor")

    viewBorderWidth = graph.getDoubleProperty("viewBorderWidth")

    viewColor = graph.getColorProperty("viewColor")

    viewFont = graph.getStringProperty("viewFont")

    viewFontSize = graph.getIntegerProperty("viewFontSize")

    viewIcon = graph.getStringProperty("viewIcon")

    viewLabel = graph.getStringProperty("viewLabel")

    viewLabelBorderColor = graph.getColorProperty("viewLabelBorderColor")

    viewLabelBorderWidth = graph.getDoubleProperty("viewLabelBorderWidth")

    viewLabelColor = graph.getColorProperty("viewLabelColor")

    viewLabelPosition = graph.getIntegerProperty("viewLabelPosition")

    viewLayout = graph.getLayoutProperty("viewLayout")

    viewMetric = graph.getDoubleProperty("viewMetric")

    viewRotation = graph.getDoubleProperty("viewRotation")

    viewSelection = graph.getBooleanProperty("viewSelection")

    viewShape = graph.getIntegerProperty("viewShape")

    viewSize = graph.getSizeProperty("viewSize")

    viewSrcAnchorShape = graph.getIntegerProperty("viewSrcAnchorShape")

    viewSrcAnchorSize = graph.getSizeProperty("viewSrcAnchorSize")

    viewTexture = graph.getStringProperty("viewTexture")

    viewTgtAnchorShape = graph.getIntegerProperty("viewTgtAnchorShape")

    viewTgtAnchorSize = graph.getSizeProperty("viewTgtAnchorSize")

    viewWeight = graph.getDoubleProperty("viewWeight")

    tp = [
        tp1_s, tp2_s, tp3_s, tp4_s, tp5_s, tp6_s, tp7_s, tp8_s, tp9_s, tp10_s,
        tp11_s, tp12_s, tp13_s, tp14_s, tp15_s, tp16_s, tp17_s
    ]

    defineGraph(graph, Locus, viewLabel, viewColor, viewSize, Positive,
                Negative)
    # algoGraph(graph, viewLayout)
    # completeGraph(graph)
    deleteZero(graph, tp)
    # filtrateEdges(graph, tp, viewWeight)

    #heat map
    listeNodes = []
    for i in graph.getNodes():
        listeNodes.append(i)

    myMap = graph.addSubGraph("map")
    viewBorderColor = myMap.getColorProperty("viewBorderColor")
    viewBorderWidth = myMap.getDoubleProperty("viewBorderWidth")
    viewColor = myMap.getColorProperty("viewColor")
    viewLayout = myMap.getLayoutProperty("viewLayout")
    viewShape = myMap.getIntegerProperty("viewShape")
    viewSize = myMap.getSizeProperty("viewSize")
    viewShape.setAllNodeValue(4)  #des rectangles
    viewBorderWidth.setAllNodeValue(1.)  # avec une bordure d'epaisseur 1
    viewBorderColor.setAllNodeValue(tlp.Color(0, 0, 0))
    Locus = myMap.getStringProperty("Locus")
    Expression = myMap.getDoubleProperty("Expression")

    nodes_map = {}
    #inverser lignes et colonnes + ajouter couleur
    for i in range(0, 1105):
        nodes_map[i] = {}
        for j in range(0, 17):
            monLocus = Locus[listeNodes[i]]
            monTp = tp[j]
            monExpression = monTp[listeNodes[i]]
            myProperties = {}
            myProperties["Locus"] = monLocus
            myProperties["Expression"] = monExpression
            #print(monLocus, " - ", monExpression)
            nodes_map[i][j] = myMap.addNode(propertiesValues=myProperties)
    for i in range(0, 1105):
        for j in range(0, 17):
            n = nodes_map[i][j]
            if (i != 0):
                myMap.addEdge(nodes_map[i - 1][j], n)
            if (j != 0):
                myMap.addEdge(nodes_map[i][j - 1], n)

    params = tlp.getDefaultPluginParameters("FM^3 (OGDF)", myMap)
    params["Egde Length Property"] = 2
    success = myMap.applyLayoutAlgorithm('FM^3 (OGDF)', viewLayout, params)

    X = -1
    for ligne in nodes_map:
        X += 1
        Y = 0
        for n in nodes_map[ligne]:
            viewLayout[nodes_map[ligne][n]] = tlp.Coord(X * 2, Y * 2, 0)
            Y += 1
Ejemplo n.º 26
0
def layout_outer_elements(graph):
    root = graph.getRoot()

    comps = [c for c in graph.getNodes() if TYPE_COMPARTMENT == root[TYPE][c]]
    for c in comps:
        c_left_x, c_bottom_y, c_right_x, c_top_y = get_comp_borders(c, root)
        c_w, c_h = (c_right_x - c_left_x) / 2, (c_top_y - c_bottom_y) / 2
        rs = sorted([
            r for r in graph.getInOutNodes(c) if len([
                s
                for s in graph.getInOutNodes(r) if not ub_or_single(s, graph)
            ]) == 1
        ],
                    key=lambda r: -get_n_length(root, r))
        comp_mg = root[VIEW_META_GRAPH][c]
        min_inner_node_x = min(root[VIEW_LAYOUT][s].getX() -
                               root[VIEW_SIZE][s].getW() / 2
                               for s in comp_mg.getNodes())
        min_inner_node_y = min(root[VIEW_LAYOUT][s].getY() -
                               root[VIEW_SIZE][s].getH() / 2
                               for s in comp_mg.getNodes())
        coords = set()
        h_jump, v_jump = True, True
        for r in rs:
            r_w, r_h = root[VIEW_SIZE][r].getW() * 3, root[VIEW_SIZE][r].getH(
            ) * 3
            inner_r_metabolite_ns = [
                s for s in root.getInOutNodes(r) if comp_mg.isElement(s)
            ]
            inner_r_metabolite_ns_not_ub = [
                s for s in inner_r_metabolite_ns
                if not ub_or_single(s, comp_mg)
            ]
            if inner_r_metabolite_ns_not_ub:
                inner_r_metabolite_ns = inner_r_metabolite_ns_not_ub
            else:
                inner_r_metabolite_ns_not_ub = [
                    s for s in inner_r_metabolite_ns if not root[UBIQUITOUS][s]
                ]
                if inner_r_metabolite_ns_not_ub:
                    inner_r_metabolite_ns = inner_r_metabolite_ns_not_ub
            avg_inner_r_metabolite_x, avg_inner_r_metabolite_y = \
                sum(root[VIEW_LAYOUT][s].getX() - min_inner_node_x for s in inner_r_metabolite_ns) / len(inner_r_metabolite_ns), \
                sum(root[VIEW_LAYOUT][s].getY() - min_inner_node_y for s in inner_r_metabolite_ns) / len(inner_r_metabolite_ns)
            x = c_left_x - r_w if avg_inner_r_metabolite_x < c_w else c_right_x + r_h
            y = c_bottom_y - r_h if avg_inner_r_metabolite_y < c_h else c_top_y + r_h

            # if we are closer to the compartment from bottom or top rather than from left or right
            if abs(c_left_x + avg_inner_r_metabolite_x -
                   x) > abs(c_bottom_y + avg_inner_r_metabolite_y - y):
                # stay below/above of the inner metabolites
                r_x = c_left_x + avg_inner_r_metabolite_x
                r_y = y
                while (r_x - r_x % REACTION_SIZE,
                       r_y - r_y % REACTION_SIZE) in coords:
                    r_x += 3 * r_w if avg_inner_r_metabolite_x < c_w else -3 * r_w
                    if v_jump:
                        r_y -= r_h if avg_inner_r_metabolite_y < c_h else r_h
                    v_jump = not v_jump
            # we are closer to the compartment from left or right rather than from bottom or top
            else:
                # stay to the left/right of the inner metabolites
                r_y = c_bottom_y + avg_inner_r_metabolite_y
                r_x = x
                while (r_x - r_x % REACTION_SIZE,
                       r_y - r_y % REACTION_SIZE) in coords:
                    r_y += 3 * r_h if avg_inner_r_metabolite_y < c_h else -3 * r_h
                    if h_jump:
                        r_x -= r_w if avg_inner_r_metabolite_x < c_w else r_w
                    h_jump = not h_jump
            coords.add((r_x - r_x % REACTION_SIZE, r_y - r_y % REACTION_SIZE))
            root[VIEW_LAYOUT][r] = tlp.Coord(r_x, r_y)
Ejemplo n.º 27
0
def bend_edges_around_compartments(graph, es):
    root = graph.getRoot()
    comps = sorted(
        (c for c in graph.getNodes() if TYPE_COMPARTMENT == root[TYPE][c]),
        key=lambda c: max(root[VIEW_SIZE][c].getW(), root[VIEW_SIZE][c].getH()
                          ))
    for e in es:
        s, t = graph.source(e), graph.target(e)
        s_x, s_y = root[VIEW_LAYOUT][s].getX(), root[VIEW_LAYOUT][s].getY()
        t_x, t_y = root[VIEW_LAYOUT][t].getX(), root[VIEW_LAYOUT][t].getY()

        max_x = max(s_x, t_x)
        min_x = min(s_x, t_x)
        max_y = max(s_y, t_y)
        min_y = min(s_y, t_y)
        w = max(root[VIEW_SIZE][s].getW(), root[VIEW_SIZE][t].getW())
        h = max(root[VIEW_SIZE][s].getH(), root[VIEW_SIZE][t].getH())
        for c in comps:
            if s == c or t == c:
                continue
            c_left_x, c_bottom_y, c_right_x, c_top_y = get_comp_borders(
                c, root)
            if max_x <= c_left_x + w or min_x >= c_right_x - w \
                    or max_y <= c_bottom_y + h or min_y >= c_top_y - h:
                continue
            alpha = atan2(t_y - s_y, t_x - s_x)
            c_alphas = [atan2(c_y - s_y, c_x - s_x) for (c_x, c_y) in \
                        [(c_left_x + w, c_bottom_y + h), (c_left_x + w, c_top_y - h),
                         (c_right_x - w, c_top_y - h), (c_right_x - w, c_bottom_y + h)]]
            if min(c_alphas) < alpha < max(c_alphas):
                bends = []
                if c_left_x < min_x <= max_x < c_right_x:
                    if (min_x - c_left_x) < (c_right_x - max_x):
                        min_x = c_left_x - w * 2
                    else:
                        max_x = c_right_x + w * 2
                elif c_bottom_y < min_y <= max_y < c_top_y:
                    if (min_y - c_bottom_y) < (c_top_y - max_y):
                        min_y = c_bottom_y - h * 2
                    else:
                        max_y = c_top_y + h * 2

                for (x, y) in [(min_x, min_y), (min_x, max_y), (max_x, max_y),
                               (max_x, min_y)]:
                    if (x < c_left_x or x > c_right_x) and (y < c_bottom_y
                                                            or y > c_top_y):
                        if (x, y) != (s_x, s_y) and (x, y) != (t_x, t_y):
                            bends.append((x, y))
                if len(bends) == 2:
                    bends = sorted(bends,
                                   key=lambda x, y: 0
                                   if (s_x == x or s_y == y) else 1)
                if bends:
                    root[VIEW_LAYOUT][e] = [
                        tlp.Coord(x, y) for (x, y) in bends
                    ]
                break

    for r in (r for r in graph.getNodes() if TYPE_REACTION == root[TYPE][r]):
        r_x, r_y = root[VIEW_LAYOUT][r].getX(), root[VIEW_LAYOUT][r].getY()
        r_r = get_reaction_r(r, root) + UBIQUITOUS_SPECIES_SIZE / 2
        reactants, products = list(graph.getInNodes(r)), list(
            graph.getOutNodes(r))

        def get_bend_coord(species):
            sample_species = next(
                (s for s in species if not ub_or_single(s, graph)), None)
            if sample_species:
                s_x, s_y = root[VIEW_LAYOUT][sample_species].getX(
                ), root[VIEW_LAYOUT][sample_species].getY()
            else:
                cs_x, cs_y = [root[VIEW_LAYOUT][s].getX() for s in species], \
                             [root[VIEW_LAYOUT][s].getY() for s in species]
                s_x, s_y = (min(cs_x) + max(cs_x)) / 2, (min(cs_y) +
                                                         max(cs_y)) / 2
            r_species_angle = atan2(s_y - r_y, s_x - r_x)
            return tlp.Coord(r_x + r_r * cos(r_species_angle),
                             r_y + r_r * sin(r_species_angle))

        if len(products) > 1:
            product_lo = get_bend_coord(products)
            for e in graph.getOutEdges(r):
                root[VIEW_LAYOUT][e] = [product_lo] + root[VIEW_LAYOUT][e]

        if len(reactants) > 1:
            reactant_lo = get_bend_coord(reactants)
            for e in graph.getInEdges(r):
                root[VIEW_LAYOUT][e] = root[VIEW_LAYOUT][e] + [reactant_lo]
Ejemplo n.º 28
0
    if target is not None and source is not None:
        e = graph.existEdge(source, target, True)

        if not e.isValid():
            graph.addEdge(source, target)

tlp.getDoubleAlgorithmPluginsList()

tlp.getDefaultPluginParameters('Degree')

for i in range(10):
    print(graph["viewMetric"][graph.nodes()[i]])

for n in graph.nodes():
    if graph.deg(n) == 0:
        graph.delNode(n)

for n in graph.nodes():
    graph['LongDouble'][n] = float(graph['Long'][n])
    graph['LatDouble'][n] = float(graph['Lat'][n])

for n in graph.nodes():
    graph['viewLayout'][n] = tlp.Coord(graph['LongDouble'][n],
                                       graph['LatDouble'][n], 0)

# tlp.saveGraph(graph, 'save/airport.tlpbz')
# nodeLinkView = tlpgui.createView("Node Link Diagram view", graph, {}, True)
# nodeLinkView.centerView()
f.close()
f1.close()