Esempio n. 1
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. 2
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. 3
0
    def Export(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)
            id = allNodes[0].id[0:-2]
            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 + id + '_' + str(
                        allReactions[i].sources[j])
                    antStr = antStr + ' + '
                antStr = antStr + id + '_' + str(
                    allReactions[i].sources[rct_num - 1])
                antStr = antStr + ' -> '
                for j in range(prd_num - 1):
                    antStr = antStr + id + '_' + str(
                        allReactions[i].targets[j])
                    antStr = antStr + ' + '
                antStr = antStr + id + '_' + str(
                    allReactions[i].targets[prd_num - 1])
                antStr = antStr + '; E' + str(i) + '*(k' + str(i)
                for j in range(rct_num):
                    antStr = antStr + '*' + id + '_' + str(
                        allReactions[i].sources[j])
                if isReversible:
                    antStr = antStr + ' - k' + str(i) + 'r'
                    for j in range(prd_num):
                        antStr = antStr + '*' + id + '_' + str(
                            allReactions[i].targets[j])
                antStr = antStr + ')'
                antStr = antStr + ';\n'
            self.antimonyText.SetValue(antStr)
Esempio n. 4
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. 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(expected, nodes[0])
Esempio n. 6
0
    def Visualize(self, evt):
        """
        Handler for the "Visualize" button.
        Visualize the SBML string to a network shown on the canvas.
        """

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

        if len(self.sbmlStr) == 0:
            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 =[]
            spec_dimension_list =[]
            spec_position_list = []


            #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(self.sbmlStr)
            model_layout = document.getModel()
            mplugin = (model_layout.getPlugin("layout"))

            if mplugin is None:
                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:
                    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()

                    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])

                    rPlugin = layout.getPlugin("render")
                    if (rPlugin != None and rPlugin.getNumLocalRenderInformationObjects() > 0):
                        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()
                            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(self.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 len(comp_id_list) != 0:
                #if mplugin is not None:
                    for j in range(numComps):
                        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
                    dimension = [4000,2500]
                    position = [0,0] 

                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

            for i in range(numComps):
                comp_node_list[i] = []

            if len(comp_id_list) != 0:
            #if mplugin is not None:
                for i in range (numFloatingNodes):
                    temp_id = FloatingNodes_ids[i]
                    comp_id = model.getCompartmentIdSpeciesIsIn(temp_id)
                    for j in range(numNodes):
                        if temp_id == spec_id_list[j]:
                            dimension = spec_dimension_list[j]
                            position = spec_position_list[j] 
                    nodeIdx_temp = api.add_node(net_index, id=temp_id, floatingNode = 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)
                    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)
                    for j in range(numNodes):
                        if temp_id == spec_id_list[j]:
                            dimension = spec_dimension_list[j]
                            position = spec_position_list[j] 
                    nodeIdx_temp = api.add_node(net_index, id=temp_id, floatingNode = 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)
                    for j in range(numComps):
                        if comp_id == comp_id_list[j]:
                            comp_node_list[j].append(nodeIdx_temp)

            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), floatingNode = 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)
                    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), floatingNode = 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)
                    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 j in range(len(node_list_temp)):
                    api.set_compartment_of_node(net_index=net_index, node_index=node_list_temp[j], 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. 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.
        """

        #self.index_list=[]

        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

        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]
            self.default_color = allNodes[0].fill_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))

            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))

            CSUM_id = 0
            for i in range(moi_mat.shape[0]):
                a = moi_mat[i, :]
                a = [0 if 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"))  #

                    CSUM_id += 1
Esempio n. 8
0
    def Export(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 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
            if numCompartments != 0:
                for i in range(numCompartments):
                    compartment = model.createCompartment()
                    comp_id = allcompartments[i].id
                    compartment.setId(comp_id)
                    compartment.setConstant(True)
                    for j in range(len(allcompartments[i].nodes)):
                        spec_id = allNodes[allcompartments[i].nodes[j]].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[allcompartments[i].
                                    nodes[j]].floatingNode == False:
                            species.setBoundaryCondition(True)
            else:  #set default compartment
                compartment = model.createCompartment()
                comp_id = "c_0"
                compartment.setId(comp_id)
                compartment.setConstant(True)
                for i in range(numNodes):
                    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].floatingNode == 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(allNodes[allReactions[i].sources[j]].id)
                for j in range(prd_num):
                    prd.append(allNodes[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:
                for i in range(numCompartments):
                    comp_id = allcompartments[i].id

                    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 j in range(len(allcompartments[i].nodes)):
                        spec_id = allNodes[allcompartments[i].nodes[j]].id
                        speciesGlyph = layout.createSpeciesGlyph()
                        specG_id = "SpecG_" + spec_id
                        speciesGlyph.setId(specG_id)
                        speciesGlyph.setSpeciesId(spec_id)
                        bb_id = "bb_" + spec_id
                        pos_x = allNodes[
                            allcompartments[i].nodes[j]].position.x
                        pos_y = allNodes[
                            allcompartments[i].nodes[j]].position.y
                        width = allNodes[allcompartments[i].nodes[j]].size.x
                        height = allNodes[allcompartments[i].nodes[j]].size.y
                        speciesGlyph.setBoundingBox(
                            BoundingBox(layoutns, bb_id, pos_x, pos_y, width,
                                        height))

                        textGlyph = layout.createTextGlyph()
                        textG_id = "TextG_" + spec_id
                        textGlyph.setId(textG_id)
                        bb_id = "bb_spec_text_" + spec_id
                        textGlyph.setBoundingBox(
                            BoundingBox(layoutns, bb_id, pos_x, pos_y, width,
                                        height))
                        textGlyph.setOriginOfTextId(specG_id)
                        textGlyph.setGraphicalObjectId(specG_id)
            else:  #there is no compartment
                for i in range(numNodes):
                    spec_id = allNodes[i].id
                    speciesGlyph = layout.createSpeciesGlyph()
                    specG_id = "SpecG_" + spec_id
                    speciesGlyph.setId(specG_id)
                    speciesGlyph.setSpeciesId(spec_id)
                    bb_id = "bb_" + spec_id
                    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
                    textGlyph.setId(textG_id)
                    bb_id = "bb_spec_text_" + spec_id
                    textGlyph.setBoundingBox(
                        BoundingBox(layoutns, bb_id, pos_x, pos_y, 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_num = len(allReactions[i].sources)
                prd_num = len(allReactions[i].targets)
                for j in range(rct_num):
                    rct.append(allNodes[allReactions[i].sources[j]].id)
                for j in range(prd_num):
                    prd.append(allNodes[allReactions[i].targets[j]].id)

                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]
                    speciesReferenceGlyph.setId(specsRefG_id)
                    speciesReferenceGlyph.setSpeciesGlyphId(specG_id)
                    speciesReferenceGlyph.setSpeciesReferenceId(ref_id)
                    speciesReferenceGlyph.setRole(SPECIES_ROLE_UNDEFINED)

                    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 = allNodes[allReactions[i].sources[j]].position.x
                    pos_y = allNodes[allReactions[i].sources[j]].position.y
                    width = allNodes[allReactions[i].sources[j]].size.x
                    height = allNodes[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]
                    speciesReferenceGlyph.setId(specsRefG_id)
                    speciesReferenceGlyph.setSpeciesGlyphId(specG_id)
                    speciesReferenceGlyph.setSpeciesReferenceId(ref_id)
                    speciesReferenceGlyph.setRole(SPECIES_ROLE_UNDEFINED)

                    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 = allNodes[allReactions[i].targets[j]].position.x
                    pos_y = allNodes[allReactions[i].targets[j]].position.y
                    width = allNodes[allReactions[i].targets[j]].size.x
                    height = allNodes[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
            if numCompartments != 0:
                fill_color = allcompartments[0].fill_color
                border_color = allcompartments[0].border_color
                comp_border_width = allcompartments[0].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)

            else:
                comp_border_width = 2.
                fill_color_str = '#9ea9ff'
                border_color_str = '#001dff'

            #nodeData does not have fill_color,border_color,border_width
            node = allNodes[0]
            # spec_fill_color   = node.fill_color
            # spec_border_color = node.border_color
            # spec_border_width = node.border_width
            # 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_fill_color_str = '#ffcc99'
            spec_border_color_str = '#ff6c09'
            spec_border_width = 2.

            if numReactions != 0:
                reaction_fill_color = allReactions[0].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

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

            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)

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

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

            if numReactions != 0:
                color = rInfo.createColorDefinition()
                color.setId("reaction_fill_color")
                color.setColorValue(reaction_fill_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))

            style = rInfo.createStyle("specStyle")
            style.getGroup().setFillColor("spec_fill_color")
            style.getGroup().setStroke("spec_border_color")
            style.getGroup().setStrokeWidth(spec_border_width)
            style.addType("SPECIESGLYPH")
            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:
                style = rInfo.createStyle("reactionStyle")
                style.getGroup().setStroke("reaction_fill_color")
                style.getGroup().setStrokeWidth(reaction_line_thickness)
                style.addType("REACTIONGLYPH SPECIESREFERENCEGLYPH")

            sbmlStr_layout_render = writeSBMLToString(doc)
            self.SBMLText.SetValue(sbmlStr_layout_render)
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')