Esempio n. 1
0
   def copy_node(node_index, net_index):
       '''
 Creates a new node, translated 300 px down and to the right.
 Parameters: node index
 Returns: index of new node
 '''
       node = api.get_node_by_index(net_index, node_index)
       try:
           inx = api.add_node(net_index,
                              id='copy_{}'.format(node.id),
                              shape_index=node.shape_index,
                              size=Vec2(node.size[0] + 60, node.size[1]),
                              position=Vec2(node.position[0] + 300,
                                            node.position[1] + 300))
       except IDRepeatError:
           # find a unique id
           all_ids = []
           ns = api.get_nodes(net_index)
           for n in ns:
               all_ids.append(n.id)
           c = 1
           new_id = 'copy_{}_{}'.format(node.id, c)
           while new_id in all_ids:
               c += 1
               new_id = 'copy_{}_{}'.format(node.id, c)
           inx = api.add_node(net_index,
                              id=new_id,
                              shape_index=node.shape_index,
                              size=Vec2(node.size[0] + 60, node.size[1]),
                              position=Vec2(node.position[0] + 300,
                                            node.position[1] + 300))
       return inx
Esempio n. 2
0
        def generateGraph():
            # add nodes and centroids as "nodes" for networkX
            nodes = np.array(list(api.get_node_indices(0)))
            #reactionsInd =  np.array(list(api.get_reaction_indices(0)))
            cStr = np.empty_like(reactionsInd, dtype=str)
            cStr[:,] = "c"
            centroidId = np.char.add(cStr, reactionsInd.astype(str))
            G.add_nodes_from(centroidId)
            nStr = np.empty_like(nodes, dtype=str)
            nStr[:,] = "n"
            nodesId = np.array(list(np.char.add(nStr, nodesInd.astype(str))))
            G.add_nodes_from(nodesId)
            '''
            for n in nodes:
                centroidsTo = np.array(list(api.get_reactions_as_product(0, n))) # Gets the reactions in which it is a product -> TO 
                cStr = np.empty_like(centroidsTo, dtype=str)
                cStr[:,] = "c"
                centroidsToIn = np.char.add(cStr, centroidsTo.astype(str)) # centroids from which the node is product
                centroidsFrom = np.array(list(api.get_reactions_as_reactant(0, n))) # reactions in which it is a reactanr -> FROM
                cStr = np.empty_like(centroidsFrom, dtype=str)
                cStr[:,] = "c"
                centroidsFromIn = np.char.add(cStr, centroidsFrom.astype(str)) # centroids to which the node is reactant
                nS = np.empty_like(centroidsToIn, dtype = str)
                nS[:,] = "n"
                numS = np.empty_like(centroidsToIn, dtype = int)
                numS[:,] = n
                nodeIndArrayTo = np.char.add(nS, numS.astype(str))
                nS = np.empty_like(centroidsFromIn, dtype = str)
                nS[:,] = "n"
                numS = np.empty_like(centroidsFromIn, dtype = int)
                numS[:,] = n
                nodeIndArrayFrom = np.char.add(nS, numS.astype(str))
                edgesTo = np.array(list(zip(centroidsToIn, nodeIndArrayTo)))
                edgesFrom = np.array(list(zip(nodeIndArrayFrom, centroidsFromIn)))
                G.add_edges_from(edgesTo)
                G.add_edges_from(edgesFrom)
            '''

            # Add edges from reactant to centroid and centroid to product (undirected)
            edges = list()
            for reaction in api.get_reactions(0):
                for s in reaction.sources:
                    edges.append(('n' + str(s), 'c' + str(reaction.index)))
                for t in reaction.targets:
                    edges.append(('c' + str(reaction.index), 'n' + str(t)))
                        
            G.add_edges_from(edges)
            cn = 0
            for rea in api.get_reactions(0):
                cent = api.compute_centroid(0, rea.sources, rea.targets)
                #originalPos[centroidId[cn]] = list([cent.x, cent.y])
                originalPos['c' + str(rea)] = list([random.randint(0,600), random.randint(0,600)])
                cn = cn + 1
            
            for nod in api.get_nodes(0):
                #originalPos[nodesId[cn]] = list([nod.position.x, nod.position.y])
                # random.randint(0,500), nod.position.y+random.randint (0,500)])
                originalPos['n' + str(nod)] = list([random.randint(0,600), random.randint (0,600)])
                cn = cn + 1
Esempio n. 3
0
    def test_add_alias(self):
        size = Vec2(60, 60)
        nodei = api.add_node(self.neti, id='Hookie', size=size)
        api.add_alias(self.neti, nodei, size=size)

        nodes = api.get_nodes(self.neti)
        self.assertEqual(2, len(nodes))
        original = NodeData(net_index=self.neti, id='Hookie', index=0, original_index=-1, size=size)
        alias = NodeData(net_index=self.neti, id='Hookie', index=1, original_index=0, size=size)
        self.assertEqual(original, nodes[0])
        self.assertEqual(alias, nodes[1])
Esempio n. 4
0
    def test_delete_items(self):
        api.add_reaction(self.neti, 'AB', [0], [1])

        with self.assertRaises(NodeNotFreeError):
            api.delete_node(self.neti, 0)
        with self.assertRaises(NodeNotFreeError):
            api.delete_node(self.neti, 1)

        api.delete_reaction(self.neti, 0)
        api.delete_node(self.neti, 0)
        api.delete_node(self.neti, 1)
        api.delete_node(self.neti, 2)

        self.assertEqual(list(), api.get_reactions(self.neti))
        self.assertEqual(list(), api.get_nodes(self.neti))
Esempio n. 5
0
 def test_add_basic(self):
     node = Node('Charles',
                 self.neti,
                 pos=Vec2(50, 50),
                 size=Vec2(50, 30))
     api.add_node(self.neti, id=node.id,
                     position=node.position,
                     size=node.size,
                     # fill_color=api._to_color(wx.RED),  # HACK using API private methods
                     # border_color=api._to_color(wx.BLUE),
                     # border_width=2,
                     )
     nodes = api.get_nodes(self.neti)
     self.assertEqual(len(nodes), 1)
     self.assertEqual(0, nodes[0].index)
     expected = NodeData(id='Charles', net_index=self.neti, position=Vec2(50, 50), size=Vec2(50, 30), index=0)
     self.assertEqual(str(expected), str(nodes[0]))
     self.assertEqual(expected, nodes[0])
Esempio n. 6
0
    def Show(self, evt):
        """
        Handler for the "Export" button.
        Get the network on canvas and change it to an Antimony string.
        """
        isReversible = True
        netIn = 0
        numNodes = api.node_count(netIn)

        if numNodes == 0:
            wx.MessageBox("Please import a network on canvas", "Message",
                          wx.OK | wx.ICON_INFORMATION)
        else:
            allNodes = api.get_nodes(netIn)
            numReactions = api.reaction_count(netIn)
            antStr = ''
            allReactions = api.get_reactions(netIn)
            for i in range(numReactions):
                antStr = antStr + 'J' + str(i) + ': '
                rct_num = len(allReactions[i].sources)
                prd_num = len(allReactions[i].targets)
                for j in range(rct_num - 1):
                    antStr = antStr + allNodes[allReactions[i].sources[j]].id
                    antStr = antStr + ' + '
                antStr = antStr + allNodes[allReactions[i].sources[rct_num -
                                                                   1]].id
                antStr = antStr + ' -> '
                for j in range(prd_num - 1):
                    antStr = antStr + allNodes[allReactions[i].targets[j]].id
                    antStr = antStr + ' + '
                antStr = antStr + allNodes[allReactions[i].targets[prd_num -
                                                                   1]].id
                antStr = antStr + '; E' + str(i) + '*(k' + str(i)
                for j in range(rct_num):
                    antStr = antStr + '*' + allNodes[
                        allReactions[i].sources[j]].id
                if isReversible:
                    antStr = antStr + ' - k' + str(i) + 'r'
                    for j in range(prd_num):
                        antStr = antStr + '*' + allNodes[
                            allReactions[i].targets[j]].id
                antStr = antStr + ')'
                antStr = antStr + ';\n'
            self.antimonyText.SetValue(antStr)
Esempio n. 7
0
    def Compute(self, evt):
        """
        Handler for the "Compute" button.
        Get the network on canvas.
        Calculate the Stoichiometry Matrix and Conservation Matrix for the randon network.
        """
        def nullspace(A, atol=1e-13, rtol=0):
            A = _np.atleast_2d(A)
            u, s, vh = _np.linalg.svd(A)
            tol = max(atol, rtol * s[0])
            nnz = (s >= tol).sum()
            ns = vh[nnz:].conj().T
            return ns

        #https://gist.github.com/sgsfak/77a1c08ac8a9b0af77393b24e44c9547
        def rref(B, tol=1e-8, debug=False):
            A = B.copy()
            rows, cols = A.shape
            r = 0
            pivots_pos = []
            row_exchanges = _np.arange(rows)
            for c in range(cols):
                if debug:
                    print("Now at row", r, "and col", c, "with matrix:")
                    print(A)

                ## Find the pivot row:
                pivot = _np.argmax(_np.abs(A[r:rows, c])) + r
                m = _np.abs(A[pivot, c])
                if debug: print("Found pivot", m, "in row", pivot)
                if m <= tol:
                    ## Skip column c, making sure the approximately zero terms are
                    ## actually zero.
                    A[r:rows, c] = _np.zeros(rows - r)
                    if debug:
                        print("All elements at and below (", r, ",", c,
                              ") are zero.. moving on..")
                else:
                    ## keep track of bound variables
                    pivots_pos.append((r, c))

                    if pivot != r:
                        ## Swap current row and pivot row
                        A[[pivot, r], c:cols] = A[[r, pivot], c:cols]
                        row_exchanges[[pivot, r]] = row_exchanges[[r, pivot]]

                        if debug:
                            print("Swap row", r, "with row", pivot, "Now:")
                            print(A)

                    ## Normalize pivot row
                    A[r, c:cols] = A[r, c:cols] / A[r, c]

                    ## Eliminate the current column
                    v = A[r, c:cols]
                    ## Above (before row r):
                    if r > 0:
                        ridx_above = _np.arange(r)
                        A[ridx_above,
                          c:cols] = A[ridx_above, c:cols] - _np.outer(
                              v, A[ridx_above, c]).T
                        if debug:
                            print("Elimination above performed:")
                            print(A)
                    ## Below (after row r):
                    if r < rows - 1:
                        ridx_below = _np.arange(r + 1, rows)
                        A[ridx_below,
                          c:cols] = A[ridx_below, c:cols] - _np.outer(
                              v, A[ridx_below, c]).T
                        if debug:
                            print("Elimination below performed:")
                            print(A)
                    r += 1
                ## Check if done
                if r == rows:
                    break
            return (A, pivots_pos, row_exchanges)

        netIn = 0
        numNodes = api.node_count(netIn)

        if numNodes == 0:
            wx.MessageBox("Please import a network on canvas", "Message",
                          wx.OK | wx.ICON_INFORMATION)
        else:
            allNodes = api.get_nodes(netIn)
            #id = allNodes[0].id[0:-2]
            node = allNodes[0]
            try:
                primitive, transform = node.shape.items[0]
                self.default_color = primitive.fill_color
            except:
                self.default_color = api.Color(255, 204,
                                               153)  #random network node color

            largest_node_index = 0
            for i in range(numNodes):
                if allNodes[i].index > largest_node_index:
                    largest_node_index = allNodes[i].index
            row = largest_node_index + 1
            numReactions = api.reaction_count(netIn)
            #print("numReactions:", numReactions)
            col = numReactions
            self.st = _np.zeros((row, col))
            allReactions = api.get_reactions(netIn)
            for i in range(numReactions):
                for j in range(len(allReactions[i].sources)):
                    #print(allReactions[i].sources[j])
                    for m in range(row):
                        if allReactions[i].sources[j] == m:
                            self.st.itemset((m, i), -1)
                for j in range(len(allReactions[i].targets)):
                    #print(allReactions[i].targets[j])
                    for m in range(row):
                        if allReactions[i].targets[j] == m:
                            self.st.itemset((m, i), 1)

            stt = _np.transpose(self.st)
            m = _np.transpose(nullspace(stt))
            moi_mat = rref(m)[0]

            # set all the values of non-existing nodes to zero
            for i in range(moi_mat.shape[0]):
                for j in range(moi_mat.shape[1]):
                    if _np.array_equal(self.st[j, :],
                                       _np.zeros(self.st.shape[1])):
                        moi_mat.itemset((i, j), 0.)

            for i in range(self.st.shape[1]):
                self.tab1.grid_st.SetColLabelValue(i, "J" + str(i))
            for i in range(self.st.shape[0]):
                #self.tab1.grid_st.SetRowLabelValue(i, id + "_" + str(i))
                id = allNodes[i].id
                self.tab1.grid_st.SetRowLabelValue(i, id)

            for row in range(self.st.shape[0]):
                for col in range(self.st.shape[1]):
                    self.tab1.grid_st.SetCellValue(
                        row, col, "%d" % self.st.item(row, col))

            for i in range(moi_mat.shape[1]):
                #self.tab2.grid_moi.SetColLabelValue(i, id + "_" + str(i))
                id = allNodes[i].id
                self.tab2.grid_moi.SetColLabelValue(i, id)

            CSUM_id = 0

            for i in range(moi_mat.shape[0]):
                a = moi_mat[i, :]
                a = [0. if abs(a_) < 0.005 else a_
                     for a_ in a]  # some elements are very small
                if _np.array_equal(
                        a, _np.zeros(moi_mat.shape[1])
                ):  # delete the row if all the elements are zero
                    CSUM_id = CSUM_id
                else:
                    self.tab2.grid_moi.SetRowLabelValue(
                        CSUM_id, "CSUM" + str(CSUM_id))

                    for j in range(moi_mat.shape[1]):
                        #self.tab2.grid_moi.SetCellValue(CSUM_id, j, format (moi_mat[i][j], ".2f"))
                        self.tab2.grid_moi.SetCellValue(
                            CSUM_id, j, format(a[j], ".2f"))
                    CSUM_id += 1
Esempio n. 8
0
    def DisplayModel(self, sbmlStr, showDialogues, useSeed):
        """
        Visualize an SBML string as a network shown on the canvas.
        Args:
          self
          document: SBMLDocument object created from the sbml string
          sbmlStr: sbml string to display
          showDialogues: if false, hides pop-up windows
          useSeed: if true, constant seed for random number generation used,
                   ensuring that different visualizations created from the same
                   file will always have the same layout
        """
        if useSeed:
            _random.seed(13)

        def hex_to_rgb(value):
            value = value.lstrip('#')
            return tuple(int(value[i:i + 2], 16) for i in (0, 2, 4))

        if len(sbmlStr) == 0:
            if showDialogues:
                wx.MessageBox("Please import an SBML file.", "Message",
                              wx.OK | wx.ICON_INFORMATION)
        else:
            net_index = 0
            api.clear_network(net_index)
            comp_id_list = []
            comp_dimension_list = []
            comp_position_list = []
            spec_id_list = []
            specGlyph_id_list = []
            spec_specGlyph_id_list = []
            spec_dimension_list = []
            spec_position_list = []

            shapeIdx = 0

            #set the default values without render info:
            comp_fill_color = (158, 169, 255)
            comp_border_color = (0, 29, 255)
            comp_border_width = 2.0
            spec_fill_color = (255, 204, 153)
            spec_border_color = (255, 108, 9)
            spec_border_width = 2.0
            reaction_line_color = (129, 123, 255)
            reaction_line_width = 3.0

            ### from here for layout ###
            document = readSBMLFromString(sbmlStr)
            model_layout = document.getModel()
            mplugin = (model_layout.getPlugin("layout"))

            if mplugin is None:
                if showDialogues:
                    wx.MessageBox(
                        "There is no layout information, so positions are randomly assigned.",
                        "Message", wx.OK | wx.ICON_INFORMATION)

            #
            # Get the first Layout object via LayoutModelPlugin object.
            #
            else:
                layout = mplugin.getLayout(0)
                if layout is None:
                    if showDialogues:
                        wx.MessageBox(
                            "There is no layout information, so positions are randomly assigned.",
                            "Message", wx.OK | wx.ICON_INFORMATION)
                else:
                    numCompGlyphs = layout.getNumCompartmentGlyphs()
                    numSpecGlyphs = layout.getNumSpeciesGlyphs()
                    numReactionGlyphs = layout.getNumReactionGlyphs()
                    flag_text_out = 0

                    for i in range(numCompGlyphs):
                        compGlyph = layout.getCompartmentGlyph(i)
                        temp_id = compGlyph.getCompartmentId()
                        comp_id_list.append(temp_id)
                        boundingbox = compGlyph.getBoundingBox()
                        height = boundingbox.getHeight()
                        width = boundingbox.getWidth()
                        pos_x = boundingbox.getX()
                        pos_y = boundingbox.getY()
                        comp_dimension_list.append([width, height])
                        comp_position_list.append([pos_x, pos_y])

                    # for i in range(numSpecGlyphs):
                    #     specGlyph = layout.getSpeciesGlyph(i)
                    #     spec_id = specGlyph.getSpeciesId()
                    #     spec_id_list.append(spec_id)
                    #     boundingbox = specGlyph.getBoundingBox()
                    #     height = boundingbox.getHeight()
                    #     width = boundingbox.getWidth()
                    #     pos_x = boundingbox.getX()
                    #     pos_y = boundingbox.getY()
                    #     spec_dimension_list.append([width,height])
                    #     spec_position_list.append([pos_x,pos_y])

                    reaction_id_list = []
                    kinetics_list = []
                    rct_specGlyph_list = []
                    prd_specGlyph_list = []

                    for i in range(numReactionGlyphs):
                        reactionGlyph = layout.getReactionGlyph(i)
                        reaction_id = reactionGlyph.getReactionId()
                        reaction_id_list.append(reaction_id)
                        reaction = model_layout.getReaction(reaction_id)
                        kinetics = reaction.getKineticLaw().getFormula()
                        kinetics_list.append(kinetics)
                        numSpecRefGlyphs = reactionGlyph.getNumSpeciesReferenceGlyphs(
                        )

                        rct_specGlyph_temp_list = []
                        prd_specGlyph_temp_list = []

                        for j in range(numSpecRefGlyphs):
                            specRefGlyph = reactionGlyph.getSpeciesReferenceGlyph(
                                j)
                            #specRefGlyph_id = specRefGlyph.getSpeciesReferenceGlyphId()
                            role = specRefGlyph.getRoleString()
                            specGlyph_id = specRefGlyph.getSpeciesGlyphId()
                            specGlyph = layout.getSpeciesGlyph(specGlyph_id)
                            #textGlyph = layout.getTextGlyph(textGlyph_id)
                            spec_id = specGlyph.getSpeciesId()
                            spec_boundingbox = specGlyph.getBoundingBox()
                            #text_boundingbox = textGlyph.getBoundingBox()
                            height = spec_boundingbox.getHeight()
                            width = spec_boundingbox.getWidth()
                            pos_x = spec_boundingbox.getX()
                            pos_y = spec_boundingbox.getY()
                            #text_pos_x = text_boundingbox.getX()
                            #text_pos_y = text_boundingbox.getY()
                            #if (pos_x,pos_y) !=(text_pos_x,text_pos_y):
                            #    flag_text_out = 1

                            if specGlyph_id not in specGlyph_id_list:
                                spec_id_list.append(spec_id)
                                specGlyph_id_list.append(specGlyph_id)
                                spec_specGlyph_id_list.append(
                                    [spec_id, specGlyph_id])
                                spec_dimension_list.append([width, height])
                                spec_position_list.append([pos_x, pos_y])

                            if role == "substrate":  #it is a rct
                                rct_specGlyph_temp_list.append(specGlyph_id)
                            elif role == "product":  #it is a prd
                                prd_specGlyph_temp_list.append(specGlyph_id)

                        rct_specGlyph_list.append(rct_specGlyph_temp_list)
                        prd_specGlyph_list.append(prd_specGlyph_temp_list)

                    rPlugin = layout.getPlugin("render")
                    if (rPlugin != None and
                            rPlugin.getNumLocalRenderInformationObjects() > 0):
                        #wx.MessageBox("The diversity of each graphical object is not shown.", "Message", wx.OK | wx.ICON_INFORMATION)
                        info = rPlugin.getRenderInformation(0)
                        color_list = []
                        for j in range(0, info.getNumColorDefinitions()):
                            color = info.getColorDefinition(j)
                            color_list.append(
                                [color.getId(),
                                 color.createValueString()])

                        for j in range(0, info.getNumStyles()):
                            style = info.getStyle(j)
                            group = style.getGroup()
                            typeList = style.createTypeString()
                            if 'COMPARTMENTGLYPH' in typeList:
                                for k in range(len(color_list)):
                                    if color_list[k][0] == group.getFill():
                                        comp_fill_color = hex_to_rgb(
                                            color_list[k][1])
                                    if color_list[k][0] == group.getStroke():
                                        comp_border_color = hex_to_rgb(
                                            color_list[k][1])
                                comp_border_width = group.getStrokeWidth()
                            elif 'SPECIESGLYPH' in typeList:
                                for k in range(len(color_list)):
                                    if color_list[k][0] == group.getFill():
                                        spec_fill_color = hex_to_rgb(
                                            color_list[k][1])
                                    if color_list[k][0] == group.getStroke():
                                        spec_border_color = hex_to_rgb(
                                            color_list[k][1])
                                spec_border_width = group.getStrokeWidth()
                                name_list = []
                                for element in group.getListOfElements():
                                    name = element.getElementName()
                                    name_list.append(name)
                                    try:
                                        NumRenderpoints = element.getListOfElements(
                                        ).getNumRenderPoints()
                                    except:
                                        NumRenderpoints = 0
                                if name == "ellipse":  #circel and text-outside
                                    shapeIdx = 1
                                elif name == "polygon" and NumRenderpoints == 6:
                                    shapeIdx = 2
                                elif name == "polygon" and NumRenderpoints == 2:
                                    shapeIdx = 3
                                elif name == "polygon" and NumRenderpoints == 3:
                                    shapeIdx = 4
                                elif name == "rectangle" and spec_fill_color == '#ffffff' and spec_border_color == '#ffffff':
                                    shapeIdx = 5
                                #elif name == "ellipse" and flag_text_out == 1:
                                #    shapeIdx = 6
                                else:  # name == "rectangle"/demo combo/others as default (rectangle)
                                    shapeIdx = 0

                            elif 'REACTIONGLYPH' in typeList:
                                for k in range(len(color_list)):
                                    if color_list[k][0] == group.getStroke():
                                        reaction_line_color = hex_to_rgb(
                                            color_list[k][1])
                                reaction_line_width = group.getStrokeWidth()

            model = simplesbml.loadSBMLStr(sbmlStr)

            numFloatingNodes = model.getNumFloatingSpecies()
            FloatingNodes_ids = model.getListOfFloatingSpecies()
            numBoundaryNodes = model.getNumBoundarySpecies()
            BoundaryNodes_ids = model.getListOfBoundarySpecies()
            numRxns = model.getNumReactions()
            Rxns_ids = model.getListOfReactionIds()
            numComps = model.getNumCompartments()
            Comps_ids = model.getListOfCompartmentIds()
            numNodes = numFloatingNodes + numBoundaryNodes

            for i in range(numComps):
                temp_id = Comps_ids[i]
                vol = model.getCompartmentVolume(i)
                if temp_id == "_compartment_default_":
                    api.add_compartment(net_index,
                                        id=temp_id,
                                        volume=vol,
                                        size=Vec2(3900, 2400),
                                        position=Vec2(10, 10),
                                        fill_color=api.Color(255, 255, 255),
                                        border_color=api.Color(255, 255, 255),
                                        border_width=comp_border_width)
                else:
                    if len(comp_id_list) != 0:
                        #if mplugin is not None:
                        #for j in range(numComps):
                        for j in range(numCompGlyphs):
                            if comp_id_list[j] == temp_id:
                                dimension = comp_dimension_list[j]
                                position = comp_position_list[j]

                    else:  # no layout info about compartment,
                        # then the whole size of the canvas is the compartment size
                        # modify the compartment size using the max_rec function above
                        # random assigned network:
                        # dimension = [800,800]
                        # position = [40,40]
                        # the whole size of the compartment: 4000*2500
                        dimension = [3900, 2400]
                        position = [10, 10]
                        comp_fill_color = (255, 255, 255)
                        comp_border_color = (255, 255, 255)

                    api.add_compartment(
                        net_index,
                        id=temp_id,
                        volume=vol,
                        size=Vec2(dimension[0], dimension[1]),
                        position=Vec2(position[0], position[1]),
                        fill_color=api.Color(comp_fill_color[0],
                                             comp_fill_color[1],
                                             comp_fill_color[2]),
                        border_color=api.Color(comp_border_color[0],
                                               comp_border_color[1],
                                               comp_border_color[2]),
                        border_width=comp_border_width)

            comp_node_list = [0] * numComps
            #comp_node_list = [0]*numCompGlyphs
            for i in range(numComps):
                #for i in range(numCompGlyphs):
                comp_node_list[i] = []

            #if there is layout info:
            if len(spec_id_list) != 0:
                id_list = []
                nodeIdx_list = [
                ]  #get_nodes idx do not follow the same order of add_node
                nodeIdx_specGlyph_list = []
                nodeIdx_specGlyph_alias_list = []
                numSpec_in_reaction = len(spec_specGlyph_id_list)
                #numSpecGlyphs is larger than numSpec_in_reaction if there orphan nodes
                if numSpecGlyphs > numSpec_in_reaction:
                    if showDialogues:
                        wx.MessageBox("Orphan nodes are removed.", "Message",
                                      wx.OK | wx.ICON_INFORMATION)
                for i in range(numSpec_in_reaction):
                    temp_id = spec_specGlyph_id_list[i][0]
                    tempGlyph_id = spec_specGlyph_id_list[i][1]
                    dimension = spec_dimension_list[i]
                    position = spec_position_list[i]
                    comp_id = model.getCompartmentIdSpeciesIsIn(temp_id)
                    for j in range(numFloatingNodes):
                        if temp_id == FloatingNodes_ids[j]:
                            if temp_id not in id_list:
                                nodeIdx_temp = api.add_node(
                                    net_index,
                                    id=temp_id,
                                    floating_node=True,
                                    size=Vec2(dimension[0], dimension[1]),
                                    position=Vec2(position[0], position[1]),
                                    fill_color=api.Color(
                                        spec_fill_color[0], spec_fill_color[1],
                                        spec_fill_color[2]),
                                    border_color=api.Color(
                                        spec_border_color[0],
                                        spec_border_color[1],
                                        spec_border_color[2]),
                                    border_width=spec_border_width,
                                    shape_index=shapeIdx)
                                id_list.append(temp_id)
                                nodeIdx_list.append(nodeIdx_temp)
                                nodeIdx_specGlyph_list.append(
                                    [nodeIdx_temp, tempGlyph_id])
                            else:
                                index = id_list.index(temp_id)
                                nodeIdx_temp = api.add_alias(
                                    net_index,
                                    original_index=index,
                                    size=Vec2(dimension[0], dimension[1]),
                                    position=Vec2(position[0], position[1]))
                                id_list.append(temp_id)
                                nodeIdx_list.append(nodeIdx_temp)
                                nodeIdx_specGlyph_alias_list.append(
                                    [nodeIdx_temp, tempGlyph_id])
                            #for k in range(numComps):
                            for k in range(numCompGlyphs):
                                if len(comp_id_list
                                       ) != 0 and comp_id == comp_id_list[k]:
                                    comp_node_list[k].append(nodeIdx_temp)
                    for j in range(numBoundaryNodes):
                        if temp_id == BoundaryNodes_ids[j]:
                            if temp_id not in id_list:
                                nodeIdx_temp = api.add_node(
                                    net_index,
                                    id=temp_id,
                                    floating_node=False,
                                    size=Vec2(dimension[0], dimension[1]),
                                    position=Vec2(position[0], position[1]),
                                    fill_color=api.Color(
                                        spec_fill_color[0], spec_fill_color[1],
                                        spec_fill_color[2]),
                                    border_color=api.Color(
                                        spec_border_color[0],
                                        spec_border_color[1],
                                        spec_border_color[2]),
                                    border_width=spec_border_width,
                                    shape_index=shapeIdx)
                                id_list.append(temp_id)
                                nodeIdx_list.append(nodeIdx_temp)
                                nodeIdx_specGlyph_list.append(
                                    [nodeIdx_temp, tempGlyph_id])
                            else:
                                index = id_list.index(temp_id)
                                nodeIdx_temp = api.add_alias(
                                    net_index,
                                    original_index=index,
                                    size=Vec2(dimension[0], dimension[1]),
                                    position=Vec2(position[0], position[1]))
                                id_list.append(temp_id)
                                nodeIdx_list.append(nodeIdx_temp)
                                nodeIdx_specGlyph_alias_list.append(
                                    [nodeIdx_temp, tempGlyph_id])
                            #for k in range(numComps):
                            for k in range(numCompGlyphs):
                                if len(comp_id
                                       ) != 0 and comp_id == comp_id_list[k]:
                                    comp_node_list[k].append(nodeIdx_temp)

                if len(comp_id_list) != 0:
                    for i in range(numComps):
                        temp_id = Comps_ids[i]
                        if temp_id == '_compartment_default_':
                            node_list_default = [
                                item for item in range(numNodes)
                            ]
                            for j in range(len(node_list_default)):
                                api.set_compartment_of_node(
                                    net_index=net_index,
                                    node_index=node_list_default[j],
                                    comp_index=i)
                        #for j in range(numComps):
                        for j in range(numCompGlyphs):
                            if comp_id_list[j] == temp_id:
                                node_list_temp = comp_node_list[j]
                            else:
                                node_list_temp = []
                            for k in range(len(node_list_temp)):
                                #print(node_list_temp)
                                api.set_compartment_of_node(
                                    net_index=net_index,
                                    node_index=node_list_temp[k],
                                    comp_index=i)
                else:
                    for i in range(len(nodeIdx_list)):
                        api.set_compartment_of_node(net_index=net_index,
                                                    node_index=nodeIdx_list[i],
                                                    comp_index=0)

                #handle_positions, center_pos was set as the default:
                #can not find a way from libsml to do this so far

                nodeIdx_specGlyph_whole_list = nodeIdx_specGlyph_list + nodeIdx_specGlyph_alias_list

                for i in range(numReactionGlyphs):
                    src = []
                    dst = []
                    temp_id = reaction_id_list[i]
                    kinetics = kinetics_list[i]
                    rct_num = len(rct_specGlyph_list[i])
                    prd_num = len(prd_specGlyph_list[i])

                    for j in range(rct_num):
                        temp_specGlyph_id = rct_specGlyph_list[i][j]
                        for k in range(numSpec_in_reaction):
                            if temp_specGlyph_id == nodeIdx_specGlyph_whole_list[
                                    k][1]:
                                rct_idx = nodeIdx_specGlyph_whole_list[k][0]
                        src.append(rct_idx)

                    for j in range(prd_num):
                        temp_specGlyph_id = prd_specGlyph_list[i][j]
                        for k in range(numSpec_in_reaction):
                            if temp_specGlyph_id == nodeIdx_specGlyph_whole_list[
                                    k][1]:
                                prd_idx = nodeIdx_specGlyph_whole_list[k][0]
                        dst.append(prd_idx)

                    api.add_reaction(net_index,
                                     id=temp_id,
                                     reactants=src,
                                     products=dst,
                                     rate_law=kinetics,
                                     fill_color=api.Color(
                                         reaction_line_color[0],
                                         reaction_line_color[1],
                                         reaction_line_color[2]),
                                     line_thickness=reaction_line_width)

            else:  # there is no layout information, assign position randomly and size as default
                comp_id_list = Comps_ids

                for i in range(numFloatingNodes):
                    temp_id = FloatingNodes_ids[i]
                    comp_id = model.getCompartmentIdSpeciesIsIn(temp_id)
                    nodeIdx_temp = api.add_node(
                        net_index,
                        id=temp_id,
                        size=Vec2(60, 40),
                        floating_node=True,
                        position=Vec2(40 + math.trunc(_random.random() * 800),
                                      40 + math.trunc(_random.random() * 800)),
                        fill_color=api.Color(spec_fill_color[0],
                                             spec_fill_color[1],
                                             spec_fill_color[2]),
                        border_color=api.Color(spec_border_color[0],
                                               spec_border_color[1],
                                               spec_border_color[2]),
                        border_width=spec_border_width,
                        shape_index=shapeIdx)
                    for j in range(numComps):
                        if comp_id == comp_id_list[j]:
                            comp_node_list[j].append(nodeIdx_temp)

                for i in range(numBoundaryNodes):
                    temp_id = BoundaryNodes_ids[i]
                    comp_id = model.getCompartmentIdSpeciesIsIn(temp_id)
                    nodeIdx_temp = api.add_node(
                        net_index,
                        id=temp_id,
                        size=Vec2(60, 40),
                        floating_node=False,
                        position=Vec2(40 + math.trunc(_random.random() * 800),
                                      40 + math.trunc(_random.random() * 800)),
                        fill_color=api.Color(spec_fill_color[0],
                                             spec_fill_color[1],
                                             spec_fill_color[2]),
                        border_color=api.Color(spec_border_color[0],
                                               spec_border_color[1],
                                               spec_border_color[2]),
                        border_width=spec_border_width,
                        shape_index=shapeIdx)
                    for j in range(numComps):
                        if comp_id == comp_id_list[j]:
                            comp_node_list[j].append(nodeIdx_temp)

                for i in range(numComps):
                    temp_id = Comps_ids[i]
                    for j in range(numComps):
                        if comp_id_list[j] == temp_id:
                            node_list_temp = comp_node_list[j]
                        for k in range(len(node_list_temp)):
                            api.set_compartment_of_node(
                                net_index=net_index,
                                node_index=node_list_temp[k],
                                comp_index=i)

                #handle_positions, center_pos was set as the default

                numNodes = api.node_count(net_index)
                allNodes = api.get_nodes(net_index)

                for i in range(numRxns):
                    src = []
                    dst = []
                    temp_id = Rxns_ids[i]
                    kinetics = model.getRateLaw(i)
                    rct_num = model.getNumReactants(i)
                    prd_num = model.getNumProducts(i)

                    for j in range(rct_num):
                        rct_id = model.getReactant(temp_id, j)
                        for k in range(numNodes):
                            if allNodes[k].id == rct_id:
                                src.append(allNodes[k].index)

                    for j in range(prd_num):
                        prd_id = model.getProduct(temp_id, j)
                        for k in range(numNodes):
                            if allNodes[k].id == prd_id:
                                dst.append(allNodes[k].index)

                    api.add_reaction(net_index,
                                     id=temp_id,
                                     reactants=src,
                                     products=dst,
                                     rate_law=kinetics,
                                     fill_color=api.Color(
                                         reaction_line_color[0],
                                         reaction_line_color[1],
                                         reaction_line_color[2]),
                                     line_thickness=reaction_line_width)
Esempio n. 9
0
 def test_update_basic(self):
     api.add_node(self.neti, id="Eric")
     api.update_node(self.neti, 0, 'James')
     nodes = api.get_nodes(self.neti)
     self.assertEqual(len(nodes), 1)
     self.assertEqual(nodes[0].id, 'James')
Esempio n. 10
0
    def Show(self, evt):
        """
        Handler for the "Export" button.
        Get the network on canvas and change it to an SBML string.
        """

        isReversible = True
        netIn = 0
        numNodes = api.node_count(netIn)
        numReactions = api.reaction_count(netIn)

        if numNodes == 0 or numReactions == 0:
            wx.MessageBox(
                "Please import a network with at least one reaction on canvas",
                "Message", wx.OK | wx.ICON_INFORMATION)
        else:
            allNodes = api.get_nodes(netIn)
            allReactions = api.get_reactions(netIn)
            allcompartments = api.get_compartments(netIn)
            numCompartments = len(allcompartments)
            #######################################

            # Creates an SBMLNamespaces object with the given SBML level, version
            # package name, package version.
            #
            # (NOTE) By default, the name of package (i.e. "layout") will be used
            # if the argument for the prefix is missing or empty. Thus the argument
            # for the prefix can be added as follows:
            #
            #    SBMLNamespaces sbmlns(3,1,"layout",1,"LAYOUT")
            #
            sbmlns = SBMLNamespaces(3, 1, "layout", 1)
            # create the document
            document = SBMLDocument(sbmlns)
            # set the "required" attribute of layout package  to "true"
            document.setPkgRequired("layout", False)

            # create the Model
            model = document.createModel()
            model.setId("Model_layout")
            document.setModel(model)

            # create the Compartment and species

            comp_id_list = []
            for i in range(numCompartments):
                comp_id_list.append(allcompartments[i].id)

            if numCompartments != 0:
                if "_compartment_default_" not in comp_id_list:
                    compartment = model.createCompartment()
                    comp_id = "_compartment_default_"
                    compartment.setId(comp_id)
                    compartment.setConstant(True)

                for i in range(numCompartments):
                    compartment = model.createCompartment()
                    comp_id = allcompartments[i].id
                    compartment.setId(comp_id)
                    compartment.setConstant(True)
                for i in range(numNodes):
                    original_index = allNodes[i].original_index
                    if original_index == -1:
                        spec_id = allNodes[i].id
                        species = model.createSpecies()
                        species.setId(spec_id)
                        comp_idx = allNodes[i].comp_idx
                        if comp_idx != -1:
                            comp_id = allcompartments[comp_idx].id
                            species.setCompartment(comp_id)
                        else:
                            species.setCompartment("_compartment_default_")
                        species.setInitialConcentration(1.0)
                        species.setHasOnlySubstanceUnits(False)
                        species.setBoundaryCondition(False)
                        species.setConstant(False)
                        if allNodes[i].floating_node == False:
                            species.setBoundaryCondition(True)
                            species.setConstant(True)
            else:  #set default compartment
                compartment = model.createCompartment()
                comp_id = "_compartment_default_"
                compartment.setId(comp_id)
                compartment.setConstant(True)
                for i in range(numNodes):
                    original_index = allNodes[i].original_index
                    if original_index == -1:
                        spec_id = allNodes[i].id
                        species = model.createSpecies()
                        species.setId(spec_id)
                        species.setCompartment(comp_id)
                        species.setInitialConcentration(1.0)
                        species.setHasOnlySubstanceUnits(False)
                        species.setBoundaryCondition(False)
                        species.setConstant(False)
                        if allNodes[i].floating_node == False:
                            species.setBoundaryCondition(True)
                            species.setConstant(True)
            # create reactions:
            for i in range(numReactions):
                reaction_id = allReactions[i].id
                rct = []  # id list of the rcts
                prd = []
                rct_num = len(allReactions[i].sources)
                prd_num = len(allReactions[i].targets)
                for j in range(rct_num):
                    rct.append(
                        get_node_by_index(netIn,
                                          allReactions[i].sources[j]).id)
                for j in range(prd_num):
                    prd.append(
                        get_node_by_index(netIn,
                                          allReactions[i].targets[j]).id)

                kinetic_law = ''
                parameter_list = []
                kinetic_law = kinetic_law + 'E' + str(i) + '*(k' + str(i)
                parameter_list.append('E' + str(i))
                parameter_list.append('k' + str(i))
                for j in range(rct_num):
                    kinetic_law = kinetic_law + '*' + rct[j]

                reaction = model.createReaction()
                reaction.setId(allReactions[i].id)
                reaction.setReversible(False)
                reaction.setFast(False)
                if isReversible:
                    reaction.setReversible(True)
                    kinetic_law = kinetic_law + ' - k' + str(i) + 'r'
                    parameter_list.append('k' + str(i) + 'r')
                    for j in range(prd_num):
                        kinetic_law = kinetic_law + '*' + prd[j]
                kinetic_law = kinetic_law + ')'
                for j in range(len(parameter_list)):
                    parameters = model.createParameter()
                    parameters.setId(parameter_list[j])
                    parameters.setValue(0.1)
                    parameters.setConstant(True)
                kinetics = reaction.createKineticLaw()
                kinetics.setFormula(kinetic_law)

                for j in range(rct_num):
                    reference = reaction.createReactant()
                    reference.setSpecies(rct[j])
                    ref_id = "SpecRef_" + reaction_id + "_rct" + str(j)
                    reference.setId(ref_id)
                    reference.setStoichiometry(1.)
                    reference.setConstant(False)

                for j in range(prd_num):
                    reference = reaction.createProduct()
                    reference.setSpecies(prd[j])
                    ref_id = "SpecRef_" + reaction_id + "_prd" + str(j)
                    reference.setId(ref_id)
                    reference.setStoichiometry(1.)
                    reference.setConstant(False)

            # create the Layout

            #
            # set the LayoutPkgNamespaces for Level 3 Version1 Layout Version 1
            #
            layoutns = LayoutPkgNamespaces(3, 1, 1)

            renderns = RenderPkgNamespaces(3, 1, 1)

            #
            # Get a LayoutModelPlugin object plugged in the model object.
            #
            # The type of the returned value of SBase::getPlugin() function is SBasePlugin, and
            # thus the value needs to be casted for the corresponding derived class.
            #

            mplugin = model.getPlugin("layout")

            # rPlugin = model.getPlugin("render")
            # if rPlugin is None:
            #   print("there is no render outside layout.")

            # lolPlugin = mplugin.getListOfLayouts().getPlugin("render")
            # if lolPlugin is None:
            #   print("there is no render info inside layout.")

            if mplugin is None:
                # print(
                #     "[Fatal Error] Layout Extension Level " + layoutns.getLevel() + " Version " + layoutns.getVersion() + " package version " + layoutns.getPackageVersion() + " is not registered.")
                # sys.exit(1)
                wx.MessageBox("There is no layout information.", "Message",
                              wx.OK | wx.ICON_INFORMATION)

            #
            # Creates a Layout object via LayoutModelPlugin object.
            #
            layout = mplugin.createLayout()
            layout.setId("Layout_1")
            layout.setDimensions(Dimensions(layoutns, 800.0, 800.0))
            # random network (40+800x, 40+800y)

            #create the CompartmentGlyph and SpeciesGlyphs
            if numCompartments != 0:
                # if "_compartment_default_" not in comp_id_list:
                #     comp_id= "_compartment_default_"
                #     compartmentGlyph = layout.createCompartmentGlyph()
                #     compG_id = "CompG_" + comp_id
                #     compartmentGlyph.setId(compG_id)
                #     compartmentGlyph.setCompartmentId(comp_id)
                #     bb_id  = "bb_" + comp_id
                #     pos_x  = 10
                #     pos_y  = 10
                #     width  = 3900
                #     height = 2400
                #     compartmentGlyph.setBoundingBox(BoundingBox(layoutns, bb_id, pos_x, pos_y, width, height))

                for i in range(numCompartments):
                    comp_id = allcompartments[i].id
                    if comp_id != "_compartment_default_":
                        compartmentGlyph = layout.createCompartmentGlyph()
                        compG_id = "CompG_" + comp_id
                        compartmentGlyph.setId(compG_id)
                        compartmentGlyph.setCompartmentId(comp_id)
                        bb_id = "bb_" + comp_id
                        pos_x = allcompartments[i].position.x
                        pos_y = allcompartments[i].position.y
                        width = allcompartments[i].size.x
                        height = allcompartments[i].size.y
                        compartmentGlyph.setBoundingBox(
                            BoundingBox(layoutns, bb_id, pos_x, pos_y, width,
                                        height))
                for i in range(numNodes):
                    spec_id = allNodes[i].id
                    spec_index = allNodes[i].index
                    spec_shapeIdx = allNodes[i].shape_index
                    speciesGlyph = layout.createSpeciesGlyph()
                    specG_id = "SpecG_" + spec_id + '_idx_' + str(spec_index)
                    speciesGlyph.setId(specG_id)
                    speciesGlyph.setSpeciesId(spec_id)
                    bb_id = "bb_" + spec_id + '_idx_' + str(spec_index)
                    pos_x = allNodes[i].position.x
                    pos_y = allNodes[i].position.y
                    width = allNodes[i].size.x
                    height = allNodes[i].size.y
                    speciesGlyph.setBoundingBox(
                        BoundingBox(layoutns, bb_id, pos_x, pos_y, width,
                                    height))

                    textGlyph = layout.createTextGlyph()
                    textG_id = "TextG_" + spec_id + '_idx_' + str(spec_index)
                    textGlyph.setId(textG_id)
                    bb_id = "bb_spec_text_" + spec_id + '_idx_' + str(
                        spec_index)
                    if spec_shapeIdx == 6:  #rough by eyes
                        pos_x_text = pos_x + 50
                        pos_y_text = pos_y + 30
                    else:
                        pos_x_text = pos_x
                        pos_y_text = pos_y
                    textGlyph.setBoundingBox(
                        BoundingBox(layoutns, bb_id, pos_x_text, pos_y_text,
                                    width, height))
                    textGlyph.setOriginOfTextId(specG_id)
                    textGlyph.setGraphicalObjectId(specG_id)
            else:  #there is no compartment
                comp_id = "_compartment_default_"
                compartmentGlyph = layout.createCompartmentGlyph()
                compG_id = "CompG_" + comp_id
                compartmentGlyph.setId(compG_id)
                compartmentGlyph.setCompartmentId(comp_id)
                bb_id = "bb_" + comp_id
                pos_x = 10
                pos_y = 10
                width = 3900
                height = 2400
                compartmentGlyph.setBoundingBox(
                    BoundingBox(layoutns, bb_id, pos_x, pos_y, width, height))

                for i in range(numNodes):
                    spec_id = allNodes[i].id
                    spec_index = allNodes[i].index
                    spec_shapeIdx = allNodes[i].shape_index
                    speciesGlyph = layout.createSpeciesGlyph()
                    specG_id = "SpecG_" + spec_id + '_idx_' + str(spec_index)
                    speciesGlyph.setId(specG_id)
                    speciesGlyph.setSpeciesId(spec_id)
                    bb_id = "bb_" + spec_id + '_idx_' + str(spec_index)
                    pos_x = allNodes[i].position.x
                    pos_y = allNodes[i].position.y
                    width = allNodes[i].size.x
                    height = allNodes[i].size.y
                    speciesGlyph.setBoundingBox(
                        BoundingBox(layoutns, bb_id, pos_x, pos_y, width,
                                    height))

                    textGlyph = layout.createTextGlyph()
                    textG_id = "TextG_" + spec_id + '_idx_' + str(spec_index)
                    textGlyph.setId(textG_id)
                    if spec_shapeIdx == 6:  #rough by eyes
                        pos_x_text = pos_x + 50
                        pos_y_text = pos_y + 30
                    else:
                        pos_x_text = pos_x
                        pos_y_text = pos_y
                    bb_id = "bb_spec_text_" + spec_id + '_idx_' + str(
                        spec_index)
                    textGlyph.setBoundingBox(
                        BoundingBox(layoutns, bb_id, pos_x_text, pos_y_text,
                                    width, height))
                    textGlyph.setOriginOfTextId(specG_id)
                    textGlyph.setGraphicalObjectId(specG_id)

            # create the ReactionGlyphs and SpeciesReferenceGlyphs
            for i in range(numReactions):
                reaction_id = allReactions[i].id
                reactionGlyph = layout.createReactionGlyph()
                reactionG_id = "RectionG_" + reaction_id
                reactionGlyph.setId(reactionG_id)
                reactionGlyph.setReactionId(reaction_id)

                reactionCurve = reactionGlyph.getCurve()
                ls = reactionCurve.createLineSegment()
                centroid = api.compute_centroid(0, allReactions[i].sources,
                                                allReactions[i].targets)
                ls.setStart(Point(layoutns, centroid.x, centroid.y))
                ls.setEnd(Point(layoutns, centroid.x, centroid.y))

                rct = []  # id list of the rcts
                prd = []
                rct_index = []
                prd_index = []
                rct_num = len(allReactions[i].sources)
                prd_num = len(allReactions[i].targets)

                for j in range(rct_num):
                    rct.append(
                        get_node_by_index(netIn,
                                          allReactions[i].sources[j]).id)
                    rct_index.append(
                        get_node_by_index(netIn,
                                          allReactions[i].sources[j]).index)
                for j in range(prd_num):
                    prd.append(
                        get_node_by_index(netIn,
                                          allReactions[i].targets[j]).id)
                    prd_index.append(
                        get_node_by_index(netIn,
                                          allReactions[i].targets[j]).index)
                for j in range(rct_num):
                    ref_id = "SpecRef_" + reaction_id + "_rct" + str(j)

                    speciesReferenceGlyph = reactionGlyph.createSpeciesReferenceGlyph(
                    )
                    specsRefG_id = "SpecRefG_" + reaction_id + "_rct" + str(j)
                    specG_id = "SpecG_" + rct[j] + '_idx_' + str(rct_index[j])
                    speciesReferenceGlyph.setId(specsRefG_id)
                    speciesReferenceGlyph.setSpeciesGlyphId(specG_id)
                    speciesReferenceGlyph.setSpeciesReferenceId(ref_id)
                    speciesReferenceGlyph.setRole(SPECIES_ROLE_SUBSTRATE)

                    speciesReferenceCurve = speciesReferenceGlyph.getCurve()
                    cb = speciesReferenceCurve.createCubicBezier()
                    #cb = speciesReferenceCurve.createLineSegment()

                    cb.setStart(Point(layoutns, centroid.x, centroid.y))

                    handles = api.default_handle_positions(
                        netIn, allReactions[i].index)
                    pos_x = handles[1 + j].x
                    pos_y = handles[1 + j].y
                    cb.setBasePoint1(Point(layoutns, pos_x, pos_y))
                    cb.setBasePoint2(Point(layoutns, pos_x, pos_y))

                    pos_x = get_node_by_index(
                        netIn, allReactions[i].sources[j]).position.x
                    pos_y = get_node_by_index(
                        netIn, allReactions[i].sources[j]).position.y
                    width = get_node_by_index(
                        netIn, allReactions[i].sources[j]).size.x
                    height = get_node_by_index(
                        netIn, allReactions[i].sources[j]).size.y
                    cb.setEnd(
                        Point(layoutns, pos_x + 0.5 * width,
                              pos_y - 0.5 * height))

                for j in range(prd_num):
                    ref_id = "SpecRef_" + reaction_id + "_prd" + str(j)
                    speciesReferenceGlyph = reactionGlyph.createSpeciesReferenceGlyph(
                    )
                    specsRefG_id = "SpecRefG_" + reaction_id + "_prd" + str(j)
                    specG_id = "SpecG_" + prd[j] + '_idx_' + str(prd_index[j])
                    speciesReferenceGlyph.setId(specsRefG_id)
                    speciesReferenceGlyph.setSpeciesGlyphId(specG_id)
                    speciesReferenceGlyph.setSpeciesReferenceId(ref_id)
                    speciesReferenceGlyph.setRole(SPECIES_ROLE_PRODUCT)

                    speciesReferenceCurve = speciesReferenceGlyph.getCurve()
                    cb = speciesReferenceCurve.createCubicBezier()
                    #cb = speciesReferenceCurve.createLineSegment()
                    cb.setStart(Point(layoutns, centroid.x, centroid.y))

                    handles = api.default_handle_positions(
                        netIn, allReactions[i].index)
                    pos_x = handles[1 + j].x
                    pos_y = handles[1 + j].y
                    cb.setBasePoint1(Point(layoutns, pos_x, pos_y))
                    cb.setBasePoint2(Point(layoutns, pos_x, pos_y))

                    pos_x = get_node_by_index(
                        netIn, allReactions[i].targets[j]).position.x
                    pos_y = get_node_by_index(
                        netIn, allReactions[i].targets[j]).position.y
                    width = get_node_by_index(
                        netIn, allReactions[i].targets[j]).size.x
                    height = get_node_by_index(
                        netIn, allReactions[i].targets[j]).size.y
                    cb.setEnd(
                        Point(layoutns, pos_x + 0.5 * width,
                              pos_y - 0.5 * height))

            sbmlStr_layout = writeSBMLToString(
                document)  #sbmlStr is w/o layout info
            #self.SBMLText.SetValue(sbmlStr_layout)

            doc = readSBMLFromString(sbmlStr_layout)
            model_layout = doc.getModel()
            mplugin = model_layout.getPlugin("layout")

            # add render information to the first layout
            layout = mplugin.getLayout(0)

            rPlugin = layout.getPlugin("render")

            uri = RenderExtension.getXmlnsL2() if doc.getLevel(
            ) == 2 else RenderExtension.getXmlnsL3V1V1()

            # enable render package
            doc.enablePackage(uri, "render", True)
            doc.setPackageRequired("render", False)

            rPlugin = layout.getPlugin("render")

            rInfo = rPlugin.createLocalRenderInformation()
            rInfo.setId("info")
            rInfo.setName("Render Information")
            rInfo.setProgramName("RenderInformation")
            rInfo.setProgramVersion("1.0")

            # add some colors
            color = rInfo.createColorDefinition()
            color.setId("black")
            color.setColorValue("#000000")

            if numCompartments != 0:
                for i in range(len(allcompartments)):
                    temp_id = allcompartments[i].id
                    if temp_id != '_compartment_default':
                        fill_color = allcompartments[i].fill_color
                        border_color = allcompartments[i].border_color
                        comp_border_width = allcompartments[i].border_width
                        fill_color_str = '#%02x%02x%02x' % (
                            fill_color.r, fill_color.g, fill_color.b)
                        border_color_str = '#%02x%02x%02x' % (
                            border_color.r, border_color.g, border_color.b)

                        # color = rInfo.createColorDefinition()
                        # color.setId("comp_fill_color" + str(i))
                        # color.setColorValue(fill_color_str)

                        # color = rInfo.createColorDefinition()
                        # color.setId("comp_border_color" + str(i))
                        # color.setColorValue(border_color_str)

                        # # add a list of styles
                        # style = rInfo.createStyle("compStyle" + str(i))
                        # style.getGroup().setFillColor("comp_fill_color" + str(i))
                        # style.getGroup().setStroke("comp_border_color" + str (i))
                        # style.getGroup().setStrokeWidth(comp_border_width)
                        # style.addType("COMPARTMENTGLYPH")
                        # rectangle = style.getGroup().createRectangle()
                        # rectangle.setCoordinatesAndSize(RelAbsVector(0,0),RelAbsVector(0,0),RelAbsVector(0,0),RelAbsVector(0,100),RelAbsVector(0,100))

                color = rInfo.createColorDefinition()
                color.setId("comp_fill_color")
                color.setColorValue(fill_color_str)

                color = rInfo.createColorDefinition()
                color.setId("comp_border_color")
                color.setColorValue(border_color_str)

                # add a list of styles
                style = rInfo.createStyle("compStyle")
                style.getGroup().setFillColor("comp_fill_color")
                style.getGroup().setStroke("comp_border_color")
                style.getGroup().setStrokeWidth(comp_border_width)
                style.addType("COMPARTMENTGLYPH")
                rectangle = style.getGroup().createRectangle()
                rectangle.setCoordinatesAndSize(RelAbsVector(0, 0),
                                                RelAbsVector(0, 0),
                                                RelAbsVector(0, 0),
                                                RelAbsVector(0, 100),
                                                RelAbsVector(0, 100))

            else:
                comp_border_width = 2.
                #fill_color_str    = '#9ea9ff'
                #border_color_str  = '#001dff'
                #set default compartment with white color
                fill_color_str = '#ffffff'
                border_color_str = '#ffffff'

                color = rInfo.createColorDefinition()
                color.setId("comp_fill_color")
                color.setColorValue(fill_color_str)

                color = rInfo.createColorDefinition()
                color.setId("comp_border_color")
                color.setColorValue(border_color_str)

                # add a list of styles
                style = rInfo.createStyle("compStyle")
                style.getGroup().setFillColor("comp_fill_color")
                style.getGroup().setStroke("comp_border_color")
                style.getGroup().setStrokeWidth(comp_border_width)
                style.addType("COMPARTMENTGLYPH")
                rectangle = style.getGroup().createRectangle()
                rectangle.setCoordinatesAndSize(RelAbsVector(0, 0),
                                                RelAbsVector(0, 0),
                                                RelAbsVector(0, 0),
                                                RelAbsVector(0, 100),
                                                RelAbsVector(0, 100))

            for i in range(len(allNodes)):
                node = allNodes[i]
                #print(node.shape)
                try:
                    primitive, transform = node.shape.items[0]
                    spec_fill_color = primitive.fill_color
                    spec_border_color = primitive.border_color
                    spec_fill_color_str = '#%02x%02x%02x' % (spec_fill_color.r,
                                                             spec_fill_color.g,
                                                             spec_fill_color.b)
                    spec_border_color_str = '#%02x%02x%02x' % (
                        spec_border_color.r, spec_border_color.g,
                        spec_border_color.b)
                    spec_border_width = primitive.border_width
                except:  #text-only
                    #spec_fill_color_str = '#ffcc99'
                    #spec_border_color_str = '#ff6c09'
                    #set default species/node with white color
                    spec_fill_color_str = '#ffffff'
                    spec_border_color_str = '#ffffff'
                    #transparent color does not work
                    #spec_fill_color_str = '#000000'
                    #spec_border_color_str = '#000000'
                    spec_border_width = 2.

                color = rInfo.createColorDefinition()
                color.setId("spec_fill_color" + str(i))
                color.setColorValue(spec_fill_color_str)

                color = rInfo.createColorDefinition()
                color.setId("spec_border_color" + str(i))
                color.setColorValue(spec_border_color_str)

                style = rInfo.createStyle("specStyle" + str(i))
                style.getGroup().setFillColor("spec_fill_color" + str(i))
                style.getGroup().setStroke("spec_border_color" + str(i))
                style.getGroup().setStrokeWidth(spec_border_width)
                style.addType("SPECIESGLYPH")
                if node.shape_index == 1 or node.shape_index == 6:  #ellipse/text-outside
                    ellipse = style.getGroup().createEllipse()
                    ellipse.setCenter2D(RelAbsVector(0, 50),
                                        RelAbsVector(0, 50))
                    ellipse.setRadii(RelAbsVector(0, 50), RelAbsVector(0, 50))

                elif node.shape_index == 2:  #hexagon(6)
                    polygon = style.getGroup().createPolygon()
                    renderPoint1 = polygon.createPoint()
                    renderPoint1.setCoordinates(RelAbsVector(0, 100),
                                                RelAbsVector(0, 50))
                    renderPoint2 = polygon.createPoint()
                    renderPoint2.setCoordinates(RelAbsVector(0, 75),
                                                RelAbsVector(0, 7))
                    renderPoint3 = polygon.createPoint()
                    renderPoint3.setCoordinates(RelAbsVector(0, 25),
                                                RelAbsVector(0, 7))
                    renderPoint4 = polygon.createPoint()
                    renderPoint4.setCoordinates(RelAbsVector(0, 0),
                                                RelAbsVector(0, 50))
                    renderPoint5 = polygon.createPoint()
                    renderPoint5.setCoordinates(RelAbsVector(0, 25),
                                                RelAbsVector(0, 86))
                    renderPoint6 = polygon.createPoint()
                    renderPoint6.setCoordinates(RelAbsVector(0, 75),
                                                RelAbsVector(0, 86))
                elif node.shape_index == 3:  #line(2)
                    polygon = style.getGroup().createPolygon()
                    renderPoint1 = polygon.createPoint()
                    renderPoint1.setCoordinates(RelAbsVector(0, 0),
                                                RelAbsVector(0, 50))
                    renderPoint2 = polygon.createPoint()
                    renderPoint2.setCoordinates(RelAbsVector(0, 100),
                                                RelAbsVector(0, 50))
                elif node.shape_index == 4:  #triangle(3)
                    polygon = style.getGroup().createPolygon()
                    renderPoint1 = polygon.createPoint()
                    renderPoint1.setCoordinates(RelAbsVector(0, 100),
                                                RelAbsVector(0, 50))
                    renderPoint2 = polygon.createPoint()
                    renderPoint2.setCoordinates(RelAbsVector(0, 25),
                                                RelAbsVector(0, 7))
                    renderPoint3 = polygon.createPoint()
                    renderPoint3.setCoordinates(RelAbsVector(0, 25),
                                                RelAbsVector(0, 86))
                else:  #rectangle shape_index = 0/text-only 5/demo-combo 7/others as default (rectangle)
                    rectangle = style.getGroup().createRectangle()
                    rectangle.setCoordinatesAndSize(RelAbsVector(0, 0),
                                                    RelAbsVector(0, 0),
                                                    RelAbsVector(0, 0),
                                                    RelAbsVector(0, 100),
                                                    RelAbsVector(0, 100))

                style = rInfo.createStyle("textStyle")
                style.getGroup().setStroke("black")
                style.getGroup().setStrokeWidth(1.)
                style.addType("TEXTGLYPH")

            if numReactions != 0:
                for i in range(len(allReactions)):
                    reaction_fill_color = allReactions[i].fill_color
                    reaction_fill_color_str = '#%02x%02x%02x' % (
                        reaction_fill_color.r, reaction_fill_color.g,
                        reaction_fill_color.b)
                    reaction_line_thickness = allReactions[i].line_thickness

                    color = rInfo.createColorDefinition()
                    color.setId("reaction_fill_color" + str(i))
                    color.setColorValue(reaction_fill_color_str)

                    style = rInfo.createStyle("reactionStyle" + str(i))
                    style.getGroup().setStroke("reaction_fill_color" + str(i))
                    style.getGroup().setStrokeWidth(reaction_line_thickness)
                    style.addType("REACTIONGLYPH SPECIESREFERENCEGLYPH")

            sbmlStr_layout_render = writeSBMLToString(doc)
            self.SBMLText.SetValue(sbmlStr_layout_render)