def Output(exportData,model,seed,selections,result,noiseLevel,resultNoisy,folderPath, fileName, antStr,bioTap):
#    export csv of results
    data = {next_name:result[:,i] for i, next_name in enumerate(selections)}
    df = pd.DataFrame.from_dict(data)
    df.set_index('time', inplace=True)

    df.to_csv(folderPath / (fileName + "Result_Clean.csv"))
    if noiseLevel != 0:
        data = {next_name:resultNoisy[:,i] for i, next_name in enumerate(selections)}
        df = pd.DataFrame.from_dict(data)
        df.set_index('time', inplace=True)
        df.to_csv(folderPath / (fileName + ".csv"))
#     export csv file for importing into Biotapestry
    if bioTap != '':
        f2 = open(folderPath / ("biotapestry.csv"), 'w')
        f2.write(bioTap)
        f2.close()
    # export Antimony model text
    if exportData[0]:
        if os.path.exists(folderPath / ("antimony.txt")):
            print('\nWarning: antimony.txt already exists! Preventing overwrite.' )
            exportData[1] == False
        else:
            fh = open(folderPath / ("antimony.txt"), 'w')
            fh.write(str(antStr))
            fh.close()
    # export SBML model text
    if exportData[1]:
        sbmlStr = model.getSBML()
        te.saveToFile (folderPath / ("SBML.xml"), sbmlStr)
    print('\nExport Data Saved!\n')
Esempio n. 2
0
def Output(modelName, folderPath, rSeed, r, antStr, Regulations):
    if rSeed != 0:
        fh = open(folderPath + modelName + ' Seed.txt', 'wb')
        fh.write('Random Seed = ' + str(rSeed))
    sbmlStr = r.getSBML()
    te.saveToFile(folderPath + modelName + ' Model.xml', sbmlStr)
    fh = open(folderPath + modelName + ' Antimony.txt', 'wb')
    fh.write(str(antStr))

    fh = open(folderPath + modelName + ' Network Regulations.txt', 'wb')
    fh.write(Regulations)
    plt.close('all')
Esempio n. 3
0
def Output(data, Name,r,rSeed,result,NoisyResult):
    
    
    for i in range(len(data)):
        if i == 1 and data[i] == 'y':
            writecsvFile(fileName + Name + '_Results.csv',r,result)
        elif data[i] == 'y':
            writecsvFile(fileName + Name + '_Noisy_result.csv',r,NoisyResult)
    if rSeed != 0:
        fh = open(fileName + Name + '_Seed.txt', 'wb')
        fh.write('Random Seed = ' + str(rSeed))
    sbmlStr = r.getSBML()
    te.saveToFile (fileName + Name + '_Model.xml', sbmlStr)
Esempio n. 4
0
def Output(data, Name,model,seed,result,NoisyResult, fileName, antStr):
    for i in range(len(data)):
        if i == 0 and data[i] == 'y':
            writecsvFile(fileName + Name + '_Results.csv',model,result)
        elif data[i] == 'y':
            writecsvFile(fileName + Name + '_Noisy_Result.csv',model,NoisyResult)
    if seed != 0:
        fh = open(fileName + Name + '_Seed.txt', 'wb')
        fh.write('Random Seed = ' + str(seed))
    if seed == 0:
        fh = open(fileName + Name + '_Seed.txt', 'wb')
        fh.write('Random Seed not chosen.')
    sbmlStr = model.getSBML()
    te.saveToFile (fileName + Name + '_Model.xml', sbmlStr)
    fh = open(fileName + Name + '_Antimony.txt', 'wb')
    fh.write(str(antStr))
#    plt.close('all')
    print('\nData Saved!\n')
Esempio n. 5
0
def Output(exportData, model, seed, result, noiseLevel, resultNoisy, filesPath,
           antStr, bioTap, selections, filename):
    # export csv of results

    # do not want to give students the clean data
    #data = {next_name:result[:,i] for i,next_name in enumerate(selections)}
    #df = pd.DataFrame.from_dict(data)
    #df.set_index('time', inplace=True)
    #df.to_csv(filesPath + "Results_Clean2.csv")

    data = {
        next_name: resultNoisy[:, i]
        for i, next_name in enumerate(selections)
    }
    df = pd.DataFrame.from_dict(data)
    df.set_index('time', inplace=True)
    df.to_csv(filesPath + filename + ".csv")

    # export csv file for importing into Biotapestry
    if bioTap != '':
        f2 = open(filesPath + "biotapestry.csv", 'w')
        f2.write(bioTap)
        f2.close()
    #  export SBML model text
    if exportData == True:
        sbmlStr = model.getSBML()
        te.saveToFile(filesPath + 'OrigModel.xml', sbmlStr)
    # export Antimony model text
    if exportData == True:
        if np.DataSource().exists(filesPath + 'OrigAntimony.txt'):
            print('Warning: ' + filesPath +
                  'OrigAntimony.txt already exists! Preventing overwrite.')
        else:
            fh = open(filesPath + 'OrigAntimony.txt', 'w')
            fh.write(str(antStr))

    print('\nData Saved!\n')
r = te.loada ('''
MJ00: MH -> MS; MH*0.2
MJ02: MH -> MD; MH*0.01
MJ10: MS -> MH; MS*0.1
MJ12: MS -> MD; MS*0.3

FJ00: FH -> FS; FH*0.1
FJ02: FH -> FD; FH*0.01
FJ10: FS -> FH; FS*0.1
FJ12: FS -> FD; FS*0.3

MH = 50
MS = 0
MD = 0

FH = 50
FS = 0
FD = 0

''')

# This will create the SBML XML file
te.saveToFile ('Example3.xml', r.getSBML())

r.setIntegrator('gillespie')
r.integrator.variable_step_size = True
r.getIntegrator().setValue('seed', 0)
result = r.simulate(0,10)
r.plot (result)
        sp3 = "S" + str(i[2])
        sp4 = "S" + str(i[3])
        if i[1] == 0 and i[3] == 0:
            m.addReaction([sp1], [sp2], "k" + str(count) + "*" + sp1)
        elif i[3] == 0:
            m.addReaction([sp1, sp2], [sp3], "k" + str(count) + "*" + sp1 
                            + "*" + sp2)
        elif i[1] == 0:
            m.addReaction([sp1], [sp2, sp3], "k" + str(count) + "*" + sp1)
                          
        else:
            m.addReaction([sp1, sp2], [sp3, sp4], "k" + str(count) + "*" + sp1 
                            + "*" + sp2)
                          
                
    te.saveToFile('Model.xml', str(m))

    r = te.loadSBMLModel('Model.xml')
    try:
        if forbidZeros:
            r.simulate()
            for i in r.getSteadyStateValues():
                if i < 1e-5:
                    raise ValueError
        if limitBoundarySpecies:
            if speciesType.count(1) > maxBoundarySpecies:
                raise ValueError
        steady = r.steadyState() #Determine if concentrations converge
        if steady < 10e-6: # If they do, it's a successful model
            print "Success!"
            print ("Number of tries = " + str(zcount))
Esempio n. 8
0
def getElementaryModesDouble(self):
    def isAllPositive(v):
        AllPositive = True
    
        for i in v:
            if i < 0:
                AllPositive = False
                break
        return AllPositive

    def isAllNegative(v):
        AllNegative = True
        for i in v:
            if i > 0:
                AllNegative = False
                break
        return AllNegative

    mStr = ''
    
    rxn_ids = self.getReactionIds()
    flt_ids = self.getFloatingSpeciesIds()
    bnd_ids = self.getBoundarySpeciesIds()
    if bnd_ids == ():
        return None
    matx = self.getStoichiometryMatrix()
          
    mStr += "-ENZREV" + "\n"

    for i in range(len(rxn_ids)):
        if self.isReactionReversible(i):
            mStr += rxn_ids[i] + " "
        
    mStr += "\n\n"+"-ENZIRREV" + "\n"
    
    for i in range(len(rxn_ids)):
        if not self.isReactionReversible(i):
            mStr += rxn_ids[i] + " "
    
    mStr += "\n\n"+"-METINT"+"\n"
    
    for  i in flt_ids:
        mStr += str (i) + " "
    
    mStr += "\n\n"+"-METEXT"+"\n"
    
    mStr += bnd_ids[0] + " "
        
    mStr += "\n\n"+"-CAT"+"\n"  
    
    for i in range(len(rxn_ids)):
        react_list = []
        col = matx[:,i]
        mStr += rxn_ids[i] + " : "
        if isAllPositive(col):
            mStr += bnd_ids[0]
        else:
            for j in range(len(flt_ids)):
                if matx[j,i] < 0:
                    stStr = ''
                    if abs(matx[j,i]) > 1:
                        stStr = str(abs(matx[j,i])) + ' ' 
                    react_list.append(stStr + flt_ids[j])
            mStr += react_list[0]
            for k in range(1,len(react_list)):
                mStr += " + " + react_list[k]
        mStr += " = "
        
        react_list = []
        if isAllNegative(col):
            mStr += bnd_ids[0]
        else:
            for j in range(len(flt_ids)):
                if matx[j,i] > 0:
                    react_list.append(flt_ids[j])
            mStr += react_list[0]
            for k in range(1,len(react_list)):
                mStr += " + " + react_list[k]
        mStr += " .\n"


    f = tempfile.TemporaryFile (delete=False)
    d = tempfile.gettempdir()
    
    resultFile = d+"\\MetaToolResult.txt"
    metatoolFile = f.name
    f.write (mStr)
    f.close()
    te.saveToFile ('c:\\tmp\\m.txt', mStr)
    
    pathToMetatool = site.getsitepackages()[1] + '\\structural\\' + 'metaToolDouble.exe'
    
    exit_code = subprocess.call ([pathToMetatool, metatoolFile, resultFile])
    
    if exit_code == 0:
        line_array = []
        with open(resultFile) as f:
            for lines in f:
                line_array.append(lines)
                
        start_pt = line_array.index("ELEMENTARY MODES\n")
        
        if line_array[start_pt+1] == ' \n':
            row_num = int(list(line_array[start_pt+2].split()[2])[1])
    #        col_num = int(list(line_array[start_pt+2].split()[4])[1])
            
            elementaryModeMatrix = []
            for i in range(row_num):
                elementaryModeMatrix.append(line_array[start_pt+3+i].split())
            elementaryModeMatrix = np.array(elementaryModeMatrix, dtype=float)
        f.close()
        return elementaryModeMatrix
    else:
        return exit_code
Esempio n. 9
0
                mStr += " + " + react_list[k]
        mStr += " .\n"
    
    return mStr


mStr = converSBMLtoMetaToolString(r.getSBML())

f = tempfile.TemporaryFile (delete=False)
d = tempfile.gettempdir()

resultFile = d+"\\MetaToolResult.txt"
metatoolFile = f.name
f.write (mStr)
f.close()
te.saveToFile ('c:\\tmp\\m.txt', mStr)

pathToMetatool = site.getsitepackages()[1] + '\\structural\\' + 'metaToolDouble.exe'

exit_code = subprocess.call ([pathToMetatool, metatoolFile, resultFile])

#print te.readFromFile(resultFile)
def getElementaryModesDouble(resultFile):
    line_array = []
    with open(resultFile) as f:
        for lines in f:
            line_array.append(lines)
            
    start_pt = line_array.index("ELEMENTARY MODES\n")
    
    if line_array[start_pt+1] == ' \n':
Esempio n. 10
0
           linewidth=2.0,
           lineStyle='-',
           color='black',
           alpha=0.8)
    r.k1 = r.k1 + 0.2
# Turn the notices back on
te.noticesOn()

# #### File helpers for reading and writing

# In[3]:

# create tmp file
import tempfile

ftmp = tempfile.NamedTemporaryFile(suffix=".xml")
print(ftmp.name)
# load model
r = te.loada('S1 -> S2; k1*S1; k1 = 0.1; S1 = 10')
# save to file
te.saveToFile(ftmp.name, r.getMatlab())

# or easier via
r.exportToMatlab(ftmp.name)

# load file
sbmlstr = te.readFromFile(ftmp.name)
print(sbmlstr)

# In[4]:
                       str(i[0]) + ")\n")                         
     elif i[3] == 0:
         m.addReaction(["S" + str(i[0]), "S" + str(i[1])], 
                       ["S" + str(i[2])], "k" + str(count) + "*S" + 
                       str(i[0]) + "*S" + str(i[1]))
     elif i[1] == 0:
         m.addReaction(["S" + str(i[0])], ["S" + str(i[1]), 
                       "S" + str(i[2])], "k" + str(count) + "*S" + 
                       str(i[0]))
     else:
         m.addReaction(["S" + str(i[0]), "S" + str(i[1])], ["S" + str(i[2]),
                       "S" + str(i[3])], "k" + str(count) + "*S" + 
                       str(i[0]) + "*S" + str(i[1]))
         
 
 te.saveToFile('ProteinModel.xml', str(m))
 r = te.loadSBMLModel('ProteinModel.xml')
 
 try:
     if forbidZeros:
         r.simulate()
         for i in r.getSteadyStateValues():
             if i < 1e-5:
                 raise ValueError
     r.simulate(end=1000)
     steady = r.steadyState()
     if steady < 10e-6:            
         print "Success!"
         print ("Number of tries = " + str(zcount))
         zcount = 0 
         for i in data:
                m.addReaction([], [sp3], "(" + s.join([k1, sp1]) + "+" + 
                    s.join([k2, sp2]) + ")/(1+" + s.join([k1, sp1]) + "+" +
                    s.join([k2, sp2]) + "+" + s.join([k3, sp1, sp2]) + ")")
            elif i[6] == 8:
                m.addReaction([], [sp3], "(1+" + s.join([k1, sp1, sp2]) +  
                    ")/(1+" + s.join([k1, sp1]) + "+" + s.join([k2, sp2]) + "+"
                    + s.join([k3, sp1, sp2]) + ")")                     
            elif i[6] == 9:
                m.addReaction([], [sp3], "(" + s.join([k1, sp1]) + ")/(1+" +
                    s.join([k1, sp1]) + "+" + s.join([k2, sp2]) + "+" +
                    s.join([k3, sp1, sp2]) + ")")
                    
    decayData = [] # Holds protein decay information
    re.proteindecay()        
                
    te.saveToFile('GeneticModel.xml', str(m))

    r = te.loadSBMLModel('GeneticModel.xml')
    try:
        if forbidZeros:
            r.simulate()
            for i in r.getSteadyStateValues():
                if i < 1e-5:
                    raise ValueError
        steady = r.steadyState() # Determine if final concentrations steady out
        if steady < 10e-6: # If they do, then it's a successful model           
            print "Success!"
            print ("Number of tries = " + str(zcount))
            zcount = 0 
            for i in data:
                zcount += 1
Esempio n. 13
0
    r.k1 = r.k1 + 0.2
# Turn the notices back on
te.noticesOn()


# #### File helpers for reading and writing

# In[3]:

# create tmp file
import tempfile
ftmp = tempfile.NamedTemporaryFile(suffix=".xml")
print(ftmp.name)
# load model
r = te.loada('S1 -> S2; k1*S1; k1 = 0.1; S1 = 10')
# save to file
te.saveToFile(ftmp.name, r.getMatlab())

# or easier via
r.exportToMatlab(ftmp.name)

# load file
sbmlstr = te.readFromFile(ftmp.name)
print(sbmlstr)


# In[4]:



r = te.loada ('''
      # Reactions: 
      compartment cytoplasm = 1.5, mitochondria = 2.6
      const S1 in mitochondria
      var S2 in cytoplasm
      var S3 in cytoplasm
      var S4 in cytoplasm

      S1 -> S2; k1*S1
      S2 -> S3; k2*S2
      S3 -> S4; k3*S3

      # Species initializations: 
      S1 = 10;  S2 = 0;  S3 = 0; S4 = 0;  
      k1 = 1; k2 = 1; k3 = 1; 
''')


te.saveToFile ('mySBMLModel.xml', r.getCurrentSBML())

#result = r.simulate(0, 10, 50, ['Time', '[S4]'])
# note that plot only shows var species not const
result = r.simulate(0, 10, 50)



print(result)

r.plot (result)

Esempio n. 15
0
        at (time > 3600): dectog = 1;
        at (time % 1200 < 1): iprot = iprot/2, imRNA = imRNA / 2, gmRNA = gmRNA / 2, gprot = gprot / 2
        
        iprot = 0;
        imRNA = 0;
        gprot = 0;
        gmRNA = 0;
        dectog = 0;
        
    end
    
    model productionValues()
        proteinProduction(10, 10, 10, 10);
        proteinProduction(10, 100, 10, 100);
        proteinProduction(10, 1000, 10, 1000);
        proteinProduction(20, 10, 20, 10);
        proteinProduction(20, 100, 20, 100);
        proteinProduction(20, 1000, 20, 1000);
        #proteinProduction(30, 10, 30, 10);
        #proteinProduction(30, 100, 30, 100);
        #proteinProduction(30, 1000, 30, 1000);
    end
'''

r = te.loadAntimonyModel(model1)
output = r.simulate (0,32400,32400)
te.plotArray(output)
s = re.sub(' *\[*\]*', '', str(output))
te.saveToFile('C:\Users\Jared\Documents\CSE\CSE486\HW2\P2data.csv', s)

Esempio n. 16
0
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 11 14:04:56 2019

@author: nrhaw
"""

import tellurium as te
import roadrunner

r = te.loada("""
    ABCDEFG -> B; k1*ABCDEFG;
    B -> C + D; k1*B;
    C -> ABCDEFG; k3*C;
    C -> D + E; k4*C;
    D + B -> F; k5*D+B;
    
    k1 = 1; k2 = 1; k3 = 1; k4 = 1; k5 = 2
""")

te.saveToFile('c:\\tmp\\largerpathway.xml', r.getSBML())