示例#1
0
def generateNetworkWithSteadyState(num_node, num_bound, num_input, knownr=1):
    """
    Generate network topology that has steady state solution
    
    :param num_node: total number of species
    :param num_bound: total number of boundary species
    :param num_input: number of input boundary species
    :rtype: array
    """
    import antimony
    import tellurium as te

    i = 0
    while i < 2:
        try:
            test_net = generateRandomNetwork(num_node, num_bound, num_input)
            k_count = np.count_nonzero(test_net)
            s_init = generateInitialSpecies(num_node, 5)
            k_init = generateInitialRateConstants(k_count, 1)
            ant_str = generateAntimony(test_net, s_init, k_init, num_node,
                                       num_bound)

            antimony.clearPreviousLoads()
            rr = te.loada(ant_str)
            rr.resetToOrigin()  # ALWAYS RESET
            rr.steadyStateNamedArray()  # Test steady state
            i += 1
        except ValueError:
            pass
        except RuntimeError:
            pass

    antimony.clearPreviousLoads()

    return test_net, s_init, k_init
示例#2
0
文件: core.py 项目: kirichoi/NSSR
def simulationSandbox(setup, ant_str, r_comb):
    '''
    Function to parallelize simulations due to memory leak issue.
    Sandbox anything that has to do with antimony and kill it off after an
    iteration
    '''
    antimony.clearPreviousLoads()

    rr = te.loada(ant_str)
    rr.resetAll()  # ALWAYS RESET
    rr.conservedMoietyAnalysis = True
    pert_i = rr.steadyStateNamedArray()  # Initial steady state

    # Put initial steady state and species ids
    #pert_init.append(pert_i[0])

    # Pertubation for rate constants
    k_pert_output_i = np.empty([len(r_comb), setup.num_float])

    for i in range(len(r_comb)):
        k_pert_output_i[i] = util.perturbRate(rr, r_comb[i], setup.k_pert)

    antimony.clearPreviousLoads()

    return pert_i.tolist(), k_pert_output_i.tolist()
示例#3
0
def flattenMotif(combined):
    #flatten the combined model by converting it to sbml and then converting back to Antimony
    antimony.clearPreviousLoads()
    code = antimony.loadAntimonyString(combined)
    if code <= 0:
        textfile = open('combined.txt', 'w')
        textfile.write(combined)
        textfile.close()
        raise AssertionError(
            'combined model is not flattenable. Are you using the right species names? '
            + 'Combined model saved as: ' + str(os.getcwd()) +
            '\\combined.txt')
    sbmlStr = antimony.getSBMLString('combined')
    antimony.loadSBMLString(sbmlStr)
    flatComb = antimony.getAntimonyString('combined')

    ####TODO
    #Delete extraneous mRNA -> Protein reactions at P_c connections
    #look for p_c#, regex
    #delete second equation with occurance of p_c#curr, regex

    #todo: remove extraneous species + parameters in the removed equation

    ####TODO
    return (flatComb)
    def translate_to_sbml_string(self, model_file: str = '', model_string: str = ''):
        """
        Returns string of SBML model specification translated from Antimony or CellML model specification file or string
        :param model_file: relative path to model specification file
        :param model_string: model specification string
        :return {str,str}: string of SBML model specification, string of main module name
        """

        # Just to be sure, call clear previous loads
        antimony.clearPreviousLoads()

        # Loading from model string or file?
        if model_file == '':
            res_load = antimony.loadString(model_string)
        else:
            model_path_normalized = self.normalize_path(model_file)
            res_load = antimony.loadFile(model_path_normalized)

        if res_load == -1:
            AntimonyTranslatorError(self, getAntimonyMessage=True)

        # Get main loaded module
        main_module_name = antimony.getMainModuleName()
        if not main_module_name:
            AntimonyTranslatorError(self, getAntimonyMessage=True)

        # Return string of SBML model specification
        translated_model_string = antimony.getSBMLString(main_module_name)
        if not translated_model_string:
            AntimonyTranslatorError(self, getAntimonyMessage=True)
        else:
            return translated_model_string, main_module_name
示例#5
0
def classify(setup, s_arr, c_arr):
    """
    Ground truth classification. Returns initial perturbation response, 
    perturbation response, classification, and reaction index
    
    :param g_truth: ground truth network matrix
    :param s_truth: ground truth species concentrations
    :param k_truth: ground truth rate constants
    :param num_node: ground truth numbder of nodes
    :param num_bound: ground truth numbder of boundary species
    :param k_pert: perturbation amount
    :param Thres: classification threshold
    :rtype: list
    """
    antimony.clearPreviousLoads()

    # Strip and translate to string
    t_s = setup.t_s.astype('str')
    t_k = setup.t_k[setup.t_k != np.array(0)].astype('str')

    #t_k_count = np.count_nonzero(setup.t_net)
    t_ant = generate.generateAntimonyNew(setup.t_net, t_s, t_k, s_arr, c_arr)

    #r_ind = np.array(np.where(setup.t_net != np.array(0))).T
    r_ind = util.getPersistantOrder(setup.t_net, setup.p_net)
    rr = te.loada(t_ant)
    rr.reset()  # ALWAYS RESET
    rr.conservedMoietyAnalysis = True
    pert_i = rr.steadyStateNamedArray()  # Initial steady state

    r_comb = clustering.getListOfCombinations(r_ind)

    # Pertubation for rate constants
    k_pert_output_i = np.empty([len(r_comb), setup.num_float])

    for i in range(len(r_comb)):
        k_pert_output_i[i] = util.perturbRate(rr, r_comb[i], setup.k_pert)

    # Classification for rate constants
    k_class_i = np.empty([len(r_comb), setup.num_float], dtype=int)

    for i in range(len(r_comb)):
        for j in range(setup.num_float):
            k_diff = (k_pert_output_i[i][j] - pert_i[0][j])
            if (np.abs(k_diff) > setup.Thres):
                if k_diff < 0.:
                    k_class_i[i][j] = 1
                else:
                    k_class_i[i][j] = 2
            else:
                k_class_i[i][j] = 0

    antimony.clearPreviousLoads()

    return pert_i[0], k_pert_output_i, k_class_i
示例#6
0
def loadAntimonyModel(antStr):
    """Load an Antimony string:
    
    r = loadAntModel (antimonyStr)
    """
    err = antimony.loadAntimonyString(antStr)

    if err < 0:
        raise Exception("Antimony: " + antimony.getLastError())

    Id = antimony.getMainModuleName()
    sbmlStr = antimony.getSBMLString(Id)
    rr = roadrunner.RoadRunner(sbmlStr)

    antimony.clearPreviousLoads()

    return rr
示例#7
0
def generateNetworkFromAntimony(ant_str):
    """
    Generate network matrix from Antimony string
    
    :param ant_str: Antimony string
    :rtype: array
    """

    import antimony
    import tellurium as te

    antimony.clearPreviousLoads()

    antimony.loadAntimonyString(ant_str)

    module = antimony.getModuleNames()[-1]

    num_rxn = int(antimony.getNumReactions(module))

    rct = antimony.getReactantNames(module)
    rct = [list(i) for i in rct]
    rct_flat = [item for sublist in rct for item in sublist]

    prd = antimony.getProductNames(module)
    prd = [list(i) for i in prd]
    prd_flat = [item for sublist in prd for item in sublist]

    ratelaw = antimony.getReactionRates(module)

    r = te.loada(ant_str)
    bnd = r.getBoundarySpeciesIds()
    flt = r.getFloatingSpeciesIds()
    s_arr = np.array(sorted(bnd + flt))

    ref_list = generateCombinationOfSpecies(s_arr)

    net_mat = np.zeros([len(ref_list), len(ref_list)])

    for i in range(num_rxn):
        if len(rct[i]) == 1 and len(prd[i]) == 1:
            r_s = rct[i][0]
            p_s = prd[i][0]
            r_s_i = ref_list.index(r_s)
            p_s_i = ref_list.index(p_s)
            net_mat[r_s_i][p_s_i] = 1
        elif len(rct[i]) == 2 and len(prd[i]) == 1:
            r_s1 = rct[i][0]
            r_s2 = rct[i][1]
            p_s = prd[i][0]
            r_s_i = ref_list.index(tuple(sorted((r_s1, r_s2))))
            p_s_i = ref_list.index(p_s)
            net_mat[r_s_i][p_s_i] = 1
        elif len(rct[i]) == 1 and len(prd[i]) == 2:
            r_s = rct[i][0]
            p_s1 = prd[i][0]
            p_s2 = prd[i][1]
            r_s_i = ref_list.index(r_s)
            p_s_i = ref_list.index(tuple(sorted((p_s1, p_s2))))
            net_mat[r_s_i][p_s_i] = 1
        elif len(rct[i]) == 2 and len(prd[i]) == 2:
            r_s1 = rct[i][0]
            r_s2 = rct[i][1]
            p_s1 = prd[i][0]
            p_s2 = prd[i][1]
            r_s_i = ref_list.index(tuple(sorted((r_s1, r_s2))))
            p_s_i = ref_list.index(tuple(sorted((p_s1, p_s2))))
            if '/' in ratelaw[i]:  # Inhibition
                net_mat[r_s_i][p_s_i] = 2
            else:
                net_mat[r_s_i][p_s_i] = 1

    antimony.clearPreviousLoads()

    return net_mat, ref_list
示例#8
0
文件: main.py 项目: kirichoi/CCR
def mutate_and_evaluate(listantStr, listdist, listrl):
    global countf
    global counts
    
    eval_dist = np.empty(mut_size)
    eval_model = np.empty(mut_size, dtype='object')
    eval_rl = np.empty(mut_size, dtype='object')
    
    for m in mut_range:
        r = te.loada(listantStr[m])
        
        r.steadyStateApproximate()
        
        concCC = r.getScaledConcentrationControlCoefficientMatrix()
        
        cFalse = (1 + np.sum(np.not_equal(np.sign(np.array(realConcCC)), 
                                          np.sign(np.array(concCC))), axis=0))

        tempdiff = cFalse*np.linalg.norm(realConcCC - concCC, axis=0)
        
        stt = [[],[],[]]
        reactionList = rl_track[0]
        
        o = 0
        
        while ((stt[1] != realFloatingIdsInd or stt[2] != realBoundaryIdsInd or
                reactionList in rl_track) and (o < maxIter_mut)):
            r_idx = np.random.choice(np.arange(nr), 
                                     p=np.divide(tempdiff,np.sum(tempdiff)))
            posRctInd = np.append(np.array(realFloatingIdsInd)[np.where(
                        np.abs(realConcCC[:,r_idx]) > 1e-12)[0]], np.array(realBoundaryIdsInd)).astype(int)
            
            reactionList = copy.deepcopy(listrl[m])
            
            rct = [col[3] for col in reactionList]
            prd = [col[4] for col in reactionList]
            
            rType, regType, revType = ng.pickReactionType()
            
            # TODO: pick reactants and products based on control coefficients
            if rType == ng.ReactionType.UNIUNI:
                # UniUni
                rct_id = np.random.choice(posRctInd, size=1).tolist()
                prd_id = np.random.choice(np.delete(nsList, rct_id), size=1).tolist()
                all_rct = [i for i,x in enumerate(rct) if x==rct_id]
                all_prd = [i for i,x in enumerate(prd) if x==prd_id]
                
                while (((np.any(np.isin(rct_id, realBoundaryIdsInd))) and 
                       (np.any(np.isin(prd_id, realBoundaryIdsInd)))) or 
                       (len(set(all_rct) & set(all_prd)) > 0)):
                    rct_id = np.random.choice(posRctInd, size=1).tolist()
                    prd_id = np.random.choice(np.delete(nsList, rct_id), size=1).tolist()
                    # Search for potentially identical reactions
                    all_rct = [i for i,x in enumerate(rct) if x==rct_id]
                    all_prd = [i for i,x in enumerate(prd) if x==prd_id]
            elif rType == ng.ReactionType.BIUNI:
                # BiUni
                rct_id = np.random.choice(posRctInd, size=2, replace=True).tolist()
                prd_id = np.random.choice(np.delete(nsList, rct_id), size=1).tolist()
                all_rct = [i for i,x in enumerate(rct) if set(x)==set(rct_id)]
                all_prd = [i for i,x in enumerate(prd) if x==prd_id]
                
                while (((np.any(np.isin(rct_id, realBoundaryIdsInd))) and 
                       (np.any(np.isin(prd_id, realBoundaryIdsInd)))) or 
                       (len(set(all_rct) & set(all_prd)) > 0)):
                    rct_id = np.random.choice(posRctInd, size=2, replace=True).tolist()
                    prd_id = np.random.choice(np.delete(nsList, rct_id), size=1).tolist()
                    # Search for potentially identical reactions
                    all_rct = [i for i,x in enumerate(rct) if set(x)==set(rct_id)]
                    all_prd = [i for i,x in enumerate(prd) if x==prd_id]
            elif rType == ng.ReactionType.UNIBI:
                # UniBi
                rct_id = np.random.choice(posRctInd, size=1).tolist()
                prd_id = np.random.choice(np.delete(nsList, rct_id), size=2, replace=True).tolist()
                all_rct = [i for i,x in enumerate(rct) if x==rct_id]
                all_prd = [i for i,x in enumerate(prd) if set(x)==set(prd_id)]
                
                while (((np.any(np.isin(rct_id, realBoundaryIdsInd))) and 
                       (np.any(np.isin(prd_id, realBoundaryIdsInd)))) or 
                       (len(set(all_rct) & set(all_prd)) > 0)):
                    rct_id = np.random.choice(posRctInd, size=1).tolist()
                    prd_id = np.random.choice(np.delete(nsList, rct_id), size=2, replace=True).tolist()
                    # Search for potentially identical reactions
                    all_rct = [i for i,x in enumerate(rct) if x==rct_id]
                    all_prd = [i for i,x in enumerate(prd) if set(x)==set(prd_id)]
            else:
                # BiBi
                rct_id = np.random.choice(posRctInd, size=2, replace=True).tolist()
                prd_id = np.random.choice(np.delete(nsList, rct_id), size=2, replace=True).tolist()
                all_rct = [i for i,x in enumerate(rct) if set(x)==set(rct_id)]
                all_prd = [i for i,x in enumerate(prd) if set(x)==set(prd_id)]
                
                while (((np.any(np.isin(rct_id, realBoundaryIdsInd))) and 
                       (np.any(np.isin(prd_id, realBoundaryIdsInd)))) or
                       (len(set(all_rct) & set(all_prd)) > 0)):
                    rct_id = np.random.choice(posRctInd, size=2, replace=True).tolist()
                    prd_id = np.random.choice(np.delete(nsList, rct_id), size=2, replace=True).tolist()
                    # Search for potentially identical reactions
                    all_rct = [i for i,x in enumerate(rct) if set(x)==set(rct_id)]
                    all_prd = [i for i,x in enumerate(prd) if set(x)==set(prd_id)]
                    
            if regType == ng.RegulationType.DEFAULT:
                act_id = []
                inhib_id = []
            elif regType == ng.RegulationType.INHIBITION:
                act_id = []
                delList = np.concatenate([rct_id, prd_id])
                if len(realBoundaryIdsInd) > 0:
                    delList = np.unique(np.append(delList, realBoundaryIdsInd))
                cList = np.delete(nsList, delList)
                if len(cList) == 0:
                    inhib_id = []
                    regType = ng.RegulationType.DEFAULT
                else:
                    inhib_id = np.random.choice(cList, size=1).tolist()
            elif regType == ng.RegulationType.ACTIVATION:
                inhib_id = []
                delList = np.concatenate([rct_id, prd_id])
                if len(realBoundaryIdsInd) > 0:
                    delList = np.unique(np.append(delList, realBoundaryIdsInd))
                cList = np.delete(nsList, delList)
                if len(cList) == 0:
                    act_id = []
                    regType = ng.RegulationType.DEFAULT
                else:
                    act_id = np.random.choice(cList, size=1).tolist()
            else:
                delList = np.concatenate([rct_id, prd_id])
                if len(realBoundaryIdsInd) > 0:
                    delList = np.unique(np.append(delList, realBoundaryIdsInd))
                cList = np.delete(nsList, delList)
                if len(cList) < 2:
                    act_id = []
                    inhib_id = []
                    regType = ng.RegulationType.DEFAULT
                else:
                    reg_id = np.random.choice(cList, size=2, replace=False)
                    act_id = [reg_id[0]]
                    inhib_id = [reg_id[1]]
                
            reactionList[r_idx] = [rType, 
                                   regType, 
                                   revType, 
                                   rct_id, 
                                   prd_id, 
                                   act_id, 
                                   inhib_id]
            
            st = ng.getFullStoichiometryMatrix(reactionList, ns).tolist()
            stt = ng.removeBoundaryNodes(np.array(st))
            o += 1
        
        if o >= maxIter_mut:
            eval_dist[m] = listdist[m]
            eval_model[m] = listantStr[m]
            eval_rl[m] = listrl[m]
        else:
            antStr = ng.generateAntimony(realFloatingIds, realBoundaryIds, 
                                          stt[1], stt[2], reactionList, 
                                          boundary_init=realBoundaryVal)
            try:
                r = te.loada(antStr)
                
                counts = 0
                countf = 0
                
                r.steadyStateApproximate()

                p_bound = ng.generateParameterBoundary(r.getGlobalParameterIds())
                res = scipy.optimize.differential_evolution(f1, args=(r,), 
                            bounds=p_bound, maxiter=optiMaxIter, tol=optiTol,
                            polish=optiPolish, seed=r_seed)
                
                if not res.success:
                    eval_dist[m] = listdist[m]
                    eval_model[m] = listantStr[m]
                    eval_rl[m] = listrl[m]
                else:
                    r = te.loada(antStr)
                    r.setValues(r.getGlobalParameterIds(), res.x)
                    
                    r.steadyStateApproximate()
                    SS_i = r.getFloatingSpeciesConcentrations()
                    
                    r.steadyStateApproximate()
                    
                    if np.any(SS_i < 1e-5) or np.any(SS_i > 1e5):
                        eval_dist[m] = listdist[m]
                        eval_model[m] = listantStr[m]
                        eval_rl[m] = listrl[m]
                    else:
                        concCC_i = r.getScaledConcentrationControlCoefficientMatrix()
                        
                        if np.isnan(concCC_i).any():
                            eval_dist[m] = listdist[m]
                            eval_model[m] = listantStr[m]
                            eval_rl[m] = listrl[m]
                        else:
                            concCC_i[np.abs(concCC_i) < 1e-12] = 0 # Set small values to zero
                            
                            concCC_i_row = concCC_i.rownames
                            concCC_i_col = concCC_i.colnames
                            concCC_i = concCC_i[np.argsort(concCC_i_row)]
                            concCC_i = concCC_i[:,np.argsort(concCC_i_col)]
                            
                            dist_i = ((np.linalg.norm(realConcCC - concCC_i))*(1 + 
                                        np.sum(np.not_equal(np.sign(np.array(realConcCC)), 
                                                            np.sign(np.array(concCC_i))))))
                            
                            if dist_i < listdist[m]:
                                eval_dist[m] = dist_i
                                r.reset()
                                eval_model[m] = r.getAntimony(current=True)
                                eval_rl[m] = reactionList
                                rl_track.append(reactionList)
                            else:
                                eval_dist[m] = listdist[m]
                                eval_model[m] = listantStr[m]
                                eval_rl[m] = listrl[m]
            except:
                eval_dist[m] = listdist[m]
                eval_model[m] = listantStr[m]
                eval_rl[m] = listrl[m]
        antimony.clearPreviousLoads()

    return eval_dist, eval_model, eval_rl
示例#9
0
文件: main.py 项目: kirichoi/CCR
def random_gen(listAntStr, listDist, listrl):
    global countf
    global counts
    
    rndSize = len(listDist)
    
    rnd_dist = np.empty(rndSize)
    rnd_model = np.empty(rndSize, dtype='object')
    rnd_rl = np.empty(rndSize, dtype='object')
    
    for l in range(rndSize):
        d = 0
        rl = ng.generateReactionList(ns, nr, realBoundaryIdsInd)
        st = ng.getFullStoichiometryMatrix(rl, ns).tolist()
        stt = ng.removeBoundaryNodes(np.array(st))
        # Ensure no redundant models
        while ((stt[1] != realFloatingIdsInd or stt[2] != realBoundaryIdsInd or
                rl in rl_track) and (d < maxIter_gen)):
            rl = ng.generateReactionList(ns, nr, realBoundaryIdsInd)
            st = ng.getFullStoichiometryMatrix(rl, ns).tolist()
            stt = ng.removeBoundaryNodes(np.array(st))
            d += 1
            
        if d >= maxIter_gen:
            rnd_dist[l] = listDist[l]
            rnd_model[l] = listAntStr[l]
            rnd_rl[l] = listrl[l]
        else:
            antStr = ng.generateAntimony(realFloatingIds, realBoundaryIds, 
                            stt[1], stt[2], rl, boundary_init=realBoundaryVal)
            try:
                r = te.loada(antStr)
                
                counts = 0
                countf = 0
                
                r.steadyStateApproximate()
                
                p_bound = ng.generateParameterBoundary(r.getGlobalParameterIds())
                res = scipy.optimize.differential_evolution(f1, args=(r,), 
                            bounds=p_bound, maxiter=optiMaxIter, tol=optiTol,
                            polish=optiPolish, seed=r_seed)
                
                # Failed to find solution
                if not res.success:
                    rnd_dist[l] = listDist[l]
                    rnd_model[l] = listAntStr[l]
                    rnd_rl[l] = listrl[l]
                else:
                    r = te.loada(antStr)
                    r.setValues(r.getGlobalParameterIds(), res.x)

                    r.steadyStateApproximate()
                    SS_i = r.getFloatingSpeciesConcentrations()
                    
                    r.steadyStateApproximate()
                    
                    if np.any(SS_i < 1e-5) or np.any(SS_i > 1e5):
                        rnd_dist[l] = listDist[l]
                        rnd_model[l] = listAntStr[l]
                        rnd_rl[l] = listrl[l]
                    else:
                        concCC_i = r.getScaledConcentrationControlCoefficientMatrix()
                        
                        if np.isnan(concCC_i).any():
                            rnd_dist[l] = listDist[l]
                            rnd_model[l] = listAntStr[l]
                            rnd_rl[l] = listrl[l]
                        else:
                            concCC_i[np.abs(concCC_i) < 1e-12] = 0 # Set small values to zero
                            
                            concCC_i_row = concCC_i.rownames
                            concCC_i_col = concCC_i.colnames
                            concCC_i = concCC_i[np.argsort(concCC_i_row)]
                            concCC_i = concCC_i[:,np.argsort(concCC_i_col)]
                            
                            dist_i = ((np.linalg.norm(realConcCC - concCC_i))*(1 + 
                                        np.sum(np.not_equal(np.sign(np.array(realConcCC)), 
                                                            np.sign(np.array(concCC_i))))))
                            
                            if dist_i < listDist[l]:
                                rnd_dist[l] = dist_i
                                r.reset()
                                rnd_model[l] = r.getAntimony(current=True)
                                rnd_rl[l] = rl
                                rl_track.append(rl)
                            else:
                                rnd_dist[l] = listDist[l]
                                rnd_model[l] = listAntStr[l]
                                rnd_rl[l] = listrl[l]
            except:
                rnd_dist[l] = listDist[l]
                rnd_model[l] = listAntStr[l]
                rnd_rl[l] = listrl[l]
        antimony.clearPreviousLoads()
        
    return rnd_dist, rnd_model, rnd_rl
示例#10
0
文件: main.py 项目: kirichoi/CCR
def initialize():
    global countf
    global counts
    
    numBadModels = 0
    numGoodModels = 0
    numIter = 0
    
    ens_dist = np.empty(ens_size)
    ens_model = np.empty(ens_size, dtype='object')
    ens_rl = np.empty(ens_size, dtype='object')
    rl_track = []
    
    # Initial Random generation
    while (numGoodModels < ens_size):
        rl = ng.generateReactionList(ns, nr, realBoundaryIdsInd)
        st = ng.getFullStoichiometryMatrix(rl, ns).tolist()
        stt = ng.removeBoundaryNodes(np.array(st))
        # Ensure no redundant model
        while (stt[1] != realFloatingIdsInd or stt[2] != realBoundaryIdsInd 
               or rl in rl_track):
            rl = ng.generateReactionList(ns, nr, realBoundaryIdsInd)
            st = ng.getFullStoichiometryMatrix(rl, ns).tolist()
            stt = ng.removeBoundaryNodes(np.array(st))
        antStr = ng.generateAntimony(realFloatingIds, realBoundaryIds, stt[1],
                                      stt[2], rl, boundary_init=realBoundaryVal)
        try:
            r = te.loada(antStr)

            counts = 0
            countf = 0
            
            r.steadyStateApproximate()
            
            p_bound = ng.generateParameterBoundary(r.getGlobalParameterIds())
            res = scipy.optimize.differential_evolution(f1, args=(r,), 
                               bounds=p_bound, maxiter=optiMaxIter, tol=optiTol,
                               polish=optiPolish, seed=r_seed)
            
            if not res.success:
                numBadModels += 1
            else:
                # TODO: Might be able to cut the bottom part by simply using 
                # the obj func value from optimizer
                r = te.loada(antStr)
                r.setValues(r.getGlobalParameterIds(), res.x)
                    
                r.steadyStateApproximate()
                SS_i = r.getFloatingSpeciesConcentrations()
                
                r.steadyStateApproximate()
                
                if np.any(SS_i < 1e-5) or np.any(SS_i > 1e5):
                    numBadModels += 1
                else:
                    concCC_i = r.getScaledConcentrationControlCoefficientMatrix()
                    
                    if np.isnan(concCC_i).any():
                        numBadModels += 1
                    else:
                        concCC_i[np.abs(concCC_i) < 1e-12] = 0 # Set small values to zero
                        
                        concCC_i_row = concCC_i.rownames
                        concCC_i_col = concCC_i.colnames
                        concCC_i = concCC_i[np.argsort(concCC_i_row)]
                        concCC_i = concCC_i[:,np.argsort(concCC_i_col)]
                        
                        dist_i = ((np.linalg.norm(realConcCC - concCC_i))*(1 + 
                                        np.sum(np.not_equal(np.sign(np.array(realConcCC)), 
                                                            np.sign(np.array(concCC_i))))))
                        
                        ens_dist[numGoodModels] = dist_i
                        r.reset()
                        ens_model[numGoodModels] = r.getAntimony(current=True)
                        ens_rl[numGoodModels] = rl
                        rl_track.append(rl)
                        
                        numGoodModels = numGoodModels + 1
        except:
            numBadModels = numBadModels + 1
        antimony.clearPreviousLoads()
        numIter = numIter + 1
        if int(numIter/1000) == (numIter/1000):
            print("Number of iterations = " + str(numIter))
        if int(numIter/10000) == (numIter/10000):
            print("Number of good models = " + str(numGoodModels))
    
    print("In generation: 1")
    print("Number of total iterations = " + str(numIter))
    print("Number of bad models = " + str(numBadModels))
    
    return ens_dist, ens_model, ens_rl, rl_track
示例#11
0
 def getSBMLStr(self):
     antimony.clearPreviousLoads()
     antimony.loadString(self.getRawStr())
     return antimony.getSBMLString(antimony.getModuleNames()[-1])
示例#12
0
文件: core.py 项目: kirichoi/metaMEG
def mutate_and_evaluate(Parameters, listantStr, listdist, listrl, rl_track):
    global countf
    global counts

    eval_dist = np.empty(Parameters.mut_size)
    eval_model = np.empty(Parameters.mut_size, dtype='object')
    eval_rl = np.empty(Parameters.mut_size, dtype='object')

    for m in Parameters.mut_range:
        o = 0

        rl = ng.generateMutation(Parameters, listrl[m], listantStr[m])
        st = ng.getFullStoichiometryMatrix(rl, Parameters.ns).tolist()
        stt = ng.removeBoundaryNodes(np.array(st))

        while ((rl in rl_track) and (o < Parameters.maxIter_mut)):
            rl = ng.generateMutation(Parameters, listrl[m], listantStr[m])
            st = ng.getFullStoichiometryMatrix(rl, Parameters.ns).tolist()
            stt = ng.removeBoundaryNodes(np.array(st))
            o += 1

        if o >= Parameters.maxIter_mut:
            eval_dist[m] = listdist[m]
            eval_model[m] = listantStr[m]
            eval_rl[m] = listrl[m]
        else:
            antStr = ng.generateAntimony(
                Parameters.realFloatingIds,
                Parameters.realBoundaryIds,
                stt[1],
                stt[2],
                rl,
                boundary_init=Parameters.realBoundaryVal)
            try:
                r = te.loada(antStr)

                r.steadyStateApproximate()

                p_bound = ng.generateParameterBoundary(
                    r.getGlobalParameterIds())
                res = scipy.optimize.differential_evolution(
                    f1,
                    args=(r, Parameters.realConcCC, Parameters.realFlux,
                          Parameters.FLUX),
                    bounds=p_bound,
                    maxiter=Parameters.optiMaxIter,
                    tol=Parameters.optiTol,
                    polish=Parameters.optiPolish,
                    seed=Parameters.r_seed)
                if not res.success:
                    eval_dist[m] = listdist[m]
                    eval_model[m] = listantStr[m]
                    eval_rl[m] = listrl[m]
                else:
                    r = te.loada(antStr)
                    r.setValues(r.getGlobalParameterIds(), res.x)

                    r.steadyStateApproximate()
                    SS_i = r.getFloatingSpeciesConcentrations()

                    r.steadyStateApproximate()

                    if np.any(SS_i < 1e-5) or np.any(SS_i > 1e5):
                        eval_dist[m] = listdist[m]
                        eval_model[m] = listantStr[m]
                        eval_rl[m] = listrl[m]
                    else:
                        concCC_i = r.getScaledConcentrationControlCoefficientMatrix(
                        )
                        if Parameters.FLUX:
                            flux_i = r.getReactionRates()

                        if np.isnan(concCC_i).any():
                            eval_dist[m] = listdist[m]
                            eval_model[m] = listantStr[m]
                            eval_rl[m] = listrl[m]
                        else:
                            concCC_i[np.abs(concCC_i) <
                                     1e-12] = 0  # Set small values to zero
                            if Parameters.FLUX:
                                flux_i[np.abs(flux_i) <
                                       1e-12] = 0  # Set small values to zero

                            concCC_i_row = concCC_i.rownames
                            concCC_i_col = concCC_i.colnames
                            concCC_i = concCC_i[np.argsort(concCC_i_row)]
                            concCC_i = concCC_i[:, np.argsort(concCC_i_col)]

                            if Parameters.FLUX:
                                flux_i = flux_i[np.argsort(concCC_i_col)]

                                dist_i = (
                                    ((np.linalg.norm(Parameters.realConcCC -
                                                     concCC_i)) +
                                     (np.linalg.norm(Parameters.realFlux -
                                                     flux_i))) *
                                    ((1 + np.sum(
                                        np.not_equal(
                                            np.sign(
                                                np.array(Parameters.realConcCC)
                                            ), np.sign(np.array(concCC_i))))) +
                                     (1 + np.sum(
                                         np.not_equal(
                                             np.sign(
                                                 np.array(Parameters.realFlux)
                                             ), np.sign(np.array(flux_i)))))))
                            else:
                                dist_i = (
                                    (np.linalg.norm(Parameters.realConcCC -
                                                    concCC_i)) *
                                    (1 + np.sum(
                                        np.not_equal(
                                            np.sign(
                                                np.array(Parameters.realConcCC)
                                            ), np.sign(np.array(concCC_i))))))

                            if dist_i < listdist[m]:
                                eval_dist[m] = dist_i
                                r.reset()
                                eval_model[m] = r.getAntimony(current=True)
                                eval_rl[m] = rl
                                rl_track.append(rl)
                            else:
                                eval_dist[m] = listdist[m]
                                eval_model[m] = listantStr[m]
                                eval_rl[m] = listrl[m]
            except:
                eval_dist[m] = listdist[m]
                eval_model[m] = listantStr[m]
                eval_rl[m] = listrl[m]
        antimony.clearPreviousLoads()

    return eval_dist, eval_model, eval_rl, rl_track