Exemplo n.º 1
0
def ConvertSBML(sbmlfile, modelfile=""):
    """Converts an SBML file to a model file.
	"""
    if modelfile == "":
        modelfile = utils.uniqueFileName("newmodel.model")

    f = sbml.SBMLREAD([], INFILE=sbmlfile, OUTFILE=modelfile)
    return os.path.abspath(f)
Exemplo n.º 2
0
def ConvertSBML(sbmlfile, modelfile=""):
	"""Converts an SBML file to a model file.
	"""
	if modelfile=="":
		modelfile = utils.uniqueFileName("newmodel.model")
		
	f=sbml.SBMLREAD([], INFILE=sbmlfile, OUTFILE=modelfile)
	return os.path.abspath(f)
Exemplo n.º 3
0
def convert(inputfile="", outputfile=""):
    if ("-in" in sys.argv):
        i=(sys.argv).index("-in")+1
        if i < len(sys.argv):
            infile = sys.argv[i]
        else:
            print "Error: converter: expecting file name after -in option."
            raise SystemExit("Correct and resubmit job.")
    elif not inputfile == "":
        infile = inputfile
    else:
        print "Error: converter: expecting `python convert.py -in filename'"
        raise SystemExit("Correct and resubmit job.")
        
        
    dumpdb = "-dump" in sys.argv
    
    (output,rates,ics) = GetCelleratorNetwork(infile, dump=dumpdb)
 
    if ("-out" in sys.argv):
        i=(sys.argv).index("-out")+1
        if i < len(sys.argv):
            outfile = sys.argv[i]
        else:
            print "Warning: converter: expecting file name after -out option."
            outfile = "translated-model.nb"
    elif not outputfile == "":
        outfile = outputfile
    else:
        # print "Warning: converter: no output file specified."
        outfile = "translated-model.nb" 
    
    outfile = utils.uniqueFileName(outfile, type="nb")
    
    
    output = ",\n ".join(output)
    output = "<<xlr8r.m;\nmodel = {"+output+"}/.{Nil->\[EmptySet],inf->\[Infinity]};\n"
    output = output.replace("_","\[UnderBracket]")
        
    def dictpair(d,x):
        return str(x).replace("_","\[UnderBracket]")+"->"+str(d[x])
        
    therates = [dictpair(rates,x) for x in rates]
    therates ="therates = {"+",\n ".join(therates)+"};\n"

    theics = [dictpair(ics,x) for x in ics]
    theics = "theics = {" + ",\n ".join(theics) + "};\n"
    
    of = open(outfile,"w")
    of.write(output)
    of.write(therates)
    of.write(theics)
    of.close()
    
    fout = os.path.abspath(outfile)
    return fout
Exemplo n.º 4
0
def convert(inputfile="", outputfile=""):
    if ("-in" in sys.argv):
        i = (sys.argv).index("-in") + 1
        if i < len(sys.argv):
            infile = sys.argv[i]
        else:
            print "Error: converter: expecting file name after -in option."
            raise SystemExit("Correct and resubmit job.")
    elif not inputfile == "":
        infile = inputfile
    else:
        print "Error: converter: expecting `python convert.py -in filename'"
        raise SystemExit("Correct and resubmit job.")

    dumpdb = "-dump" in sys.argv

    (output, rates, ics) = GetCelleratorNetwork(infile, dump=dumpdb)

    if ("-out" in sys.argv):
        i = (sys.argv).index("-out") + 1
        if i < len(sys.argv):
            outfile = sys.argv[i]
        else:
            print "Warning: converter: expecting file name after -out option."
            outfile = "translated-model.nb"
    elif not outputfile == "":
        outfile = outputfile
    else:
        # print "Warning: converter: no output file specified."
        outfile = "translated-model.nb"

    outfile = utils.uniqueFileName(outfile, type="nb")

    output = ",\n ".join(output)
    output = "<<xlr8r.m;\nmodel = {" + output + "}/.{Nil->\[EmptySet],inf->\[Infinity]};\n"
    output = output.replace("_", "\[UnderBracket]")

    def dictpair(d, x):
        return str(x).replace("_", "\[UnderBracket]") + "->" + str(d[x])

    therates = [dictpair(rates, x) for x in rates]
    therates = "therates = {" + ",\n ".join(therates) + "};\n"

    theics = [dictpair(ics, x) for x in ics]
    theics = "theics = {" + ",\n ".join(theics) + "};\n"

    of = open(outfile, "w")
    of.write(output)
    of.write(therates)
    of.write(theics)
    of.close()

    fout = os.path.abspath(outfile)
    return fout
Exemplo n.º 5
0
def ToMathematica(infile, outfile=""):
	"""ToMathematica(infile, [outfile=""])
	converts the specified model file to legacy Cellerator 
	Mathematica notebook.
	"""
	if len(outfile)==0:
		outfile="translated-model.nb"
	
	out=utils.uniqueFileName(outfile, type="nb")
	
	fout = converter.convert(infile, outfile)
    
	return fout
Exemplo n.º 6
0
def ToMathematica(infile, outfile=""):
    """ToMathematica(infile, [outfile=""])
	converts the specified model file to legacy Cellerator 
	Mathematica notebook.
	"""
    if len(outfile) == 0:
        outfile = "translated-model.nb"

    out = utils.uniqueFileName(outfile, type="nb")

    fout = converter.convert(infile, outfile)

    return fout
Exemplo n.º 7
0
def GenerateSBML(infile, output=""):
    """GenerateSBML(inputfilename, output="")
    Reads the pyCellerator model infile and generates SBML.
    
    If output is specified, the SMBL is written to the specified
    file and the absolute path name of the file is returned.
    
    if the out is not specified, the SBML is returned as a single
    string (with embedded newline characters). 
    """
    s=sbmlwrite.genmodel(infile,"")
    
    if len(output)>0:
        filename = utils.uniqueFileName(output,type="xml")
        f=open(filename,"w")
        f.write(s)
        f.close()
        p = os.path.abspath(filename)
        return(p)
Exemplo n.º 8
0
def GenerateSBML(infile, output=""):
    """GenerateSBML(inputfilename, output="")
    Reads the pyCellerator model infile and generates SBML.
    
    If output is specified, the SMBL is written to the specified
    file and the absolute path name of the file is returned.
    
    if the out is not specified, the SBML is returned as a single
    string (with embedded newline characters). 
    """
    s = sbmlwrite.genmodel(infile, "")

    if len(output) > 0:
        filename = utils.uniqueFileName(output, type="xml")
        f = open(filename, "w")
        f.write(s)
        f.close()
        p = os.path.abspath(filename)
        return (p)
Exemplo n.º 9
0
def newModel(reactions,
             IC="",
             RATES="",
             FUNCTIONS="",
             ASSIGNMENTS="",
             output="newmodel"):
    """newModel(reactions, IC, RATES, FUNCTIONS, ASSIGNMENTS)
    creates a new model file from strings.
    """
    reactions = "$REACTIONS\n" + reactions
    ic = "$IC\n" + IC
    rates = "$RATES\n" + RATES
    funcs = "$FUNCTIONS\n" + FUNCTIONS
    assigns = "$ASSIGNMENTS\n" + ASSIGNMENTS

    model = "\n".join([reactions, ic, assigns, funcs, rates])
    model = model.replace(";", "\n")
    model = model.replace("\n\n", "\n")

    # clean up
    m = model.split("\n")
    newmodel = []
    for line in m:
        line = line.strip()
        if len(line) > 0:
            if line[0] == "$":
                newmodel.append(line)
            else:
                newmodel.append(" " + line)

    model = "\n".join(newmodel)

    outputfile = utils.uniqueFileName(output, type="model")
    f = open(outputfile, "w")
    f.write(model)
    f.close()

    fname = os.path.abspath(outputfile)

    return fname
Exemplo n.º 10
0
def newModel(reactions, IC="", RATES="", FUNCTIONS="", ASSIGNMENTS="", 
    output="newmodel"):
    """newModel(reactions, IC, RATES, FUNCTIONS, ASSIGNMENTS)
    creates a new model file from strings.
    """
    reactions = "$REACTIONS\n"+reactions
    ic = "$IC\n"+IC
    rates = "$RATES\n"+RATES
    funcs= "$FUNCTIONS\n"+FUNCTIONS
    assigns="$ASSIGNMENTS\n"+ASSIGNMENTS
    
    model = "\n".join([reactions, ic, assigns, funcs, rates])
    model = model.replace(";", "\n")
    model = model.replace("\n\n","\n")
    
    # clean up
    m = model.split("\n")
    newmodel=[]
    for line in m:
        line = line.strip()
        if len(line)>0:
            if line[0]=="$":
                newmodel.append(line)
            else:
                newmodel.append(" "+line)

    model = "\n".join(newmodel)
    
    outputfile = utils.uniqueFileName(output,type="model")
    f=open(outputfile,"w")
    f.write(model)
    f.close()
    
    fname=os.path.abspath(outputfile)

    return fname
Exemplo n.º 11
0
def Solve(inputfile, step=1, duration=100,  solverfile="",
    output="solution", mxstep=50000, scan=[], run=True, RATES={}, IC={}, 
    timer=False):
    """Solve(inputfile, step=1, duration=100, solverfile="newsolver.py",
             mxtep=50000, run=True, scan=[], RATES={}, IC={})
    
    input parameters:
    
    inputfile - pyCellerator input file containing a model
    step - (output) step size for integrator. The default integrator
		is odeint. The step size specifies the interpolated output
		values, not the actual values used by the integrator
    duration - duration of integration
    mxstep - maximum number of steps allowed by odeint. 
    solverfile - name of python program that will be automatically
		generated to solve the sytem
    run = True; if false, just generate the code, don't run simulation
    RATES={}: optional dictionary of paramaters that can be used to 
		override one or more rate values in the model
	IC={}: optional dictional of initial conditions that can be used
		to override zero or more initial conditions in the model
		
Return value: when run=True (default)
    tuple (t, variables, solutions)
	where
	t=numpy array of values at which the solution is interpolated.
	variables=list of nambed variables in the solution
	solution=numpy array of values. There is one column for each variable.
		the columns are in the same order as the variable
		names. The length of the columns is the same
		as the length of the values in t. The contents
		of each column contains the values of the corresponding
		variable at the corresponding times in t.
	when run=False, name of simulation code
    """
    
    # input: model file
    # return value: output of integrator
    
    hold=[]
    if len(scan)>0:
		if len(scan) == 4:
			scanparameter, scanstart, scanstop, scandelta = scan
			hold=[scanparameter]
			if not isinstance(scanparameter,str):
				sys.exit("Error: expecting a string for the name of the scan parameter")
		else:
			sys.exit("Error: expeciting scan=['parameter',start,stop,delta]")

    
    
    # if invoked from command line, "solver -in filename -run duration step"
    
    if timer:
        ttimer=time.time()
    (r, ic, rates, frozenvars, functions,assignments, filename)=solver.readmodel(INFILE=inputfile)
    
 
    
    if timer:
        tread=time.time()-ttimer
        
    #print "rates:",rates
    #print "ic:", ic
    for rate in RATES:
		if rate in rates:
			rates[rate]=RATES[rate]
		else:
			print "Warning: unexpected parameter ",rate,\
			" set in RATES not found in model was ignored."
    for variable in IC:
		if variable in ic:
			ic[variable]=IC[variable]
		else:
			print "Warning: unexpected variable ", variable,\
			" set in IC not found model was ignored."
    #print "rates:",rates
    #print "ic:", ic
		
    
    if timer:
        ttimer=time.time()
    (variables, y0, tmpdotpy) = solver.generatePythonFunction(r, rates, 
         ic, frozenvars, functions, assignments, holdrates=hold)

    # ----- begin addition 7/23/16
    #
    # look for replacements in assignments
    # these are needed in the wrapper program so that plots work
    #
    assignreplace=False
    assign_replace_info=[]
    ratekeys=set(rates.keys())
    ratesneeded=set()
    for ass in assignments:
		#
		# extract the assignment statement itself
		#
		setequal=ass.find("=")
		setvar=ass[:setequal].strip()
		set_rhs=ass[setequal+1:]
		#print "Cellerator>Solve>assigned var:",setvar, setvar in variables
		#
		# Extract the rate constants that are in this assignment statement
		# Note: variables in RHS expression that are not rates will be missed
		# 
		if setvar in variables:
			svarindex = variables.index(setvar)
			#print "Cellerator>Solve>",setvar, "is variable",svarindex,"in",variables
			#print "Cellerator > assignreplace > set_rhs: ", set_rhs
			# 
			# variables in assginment statement
			#
			vars_on_rhs=set(re.split("[\)\(\[\]<>\*\+-]|\s", set_rhs))
			# 
			# variables that are rates
			#
			ratestoset = ratekeys.intersection(vars_on_rhs)
			#
			# save the name of the rate needed
			#
			ratesneeded |= ratestoset
			#
			# save the assignment statement for later
			assignreplace=True
			assign_replace_info.append([svarindex,set_rhs])
	
	#
	# Generate a list of extra python commands to write to the 
	# driver program for the rate constants
	#		
    if assignreplace:
        ratestoset = list(ratestoset)
        xtra_rate_commands=[]
        for rate_constant in ratestoset:
            rate_value=rates[rate_constant]
            xtra_rate_commands.append(rate_constant+"="+str(rate_value))
    #
    # --- end addition 7/23/16 
		

    
    #
    # generatePythonFunction creates the file tmp.py
    #
    f=open(tmpdotpy,"r")
    rhs=f.readlines()
    f.close()
    #
    #clean up
    try:
        os.remove(tmpdotpy)
    except:
        print "Warning: unable to remove the file "+os.path.abspath(tmpdotpy)+"\n+"\
        +"Perhaps an authorization issue? You do not need to keep this file\nand it may be deleted"
    #
    # name the solver program
    #
    pyfile = solverfile
    #print "DBG>>>solverfile:", solverfile
    #print "DBG>>> INPUT >>>", inputfile

    if pyfile=="":
        inputdrive, inputpath = os.path.splitdrive(inputfile)
        inputpath, inputfilename = os.path.split(inputpath)
        #print "DBG:drive:", inputdrive
        #print "DBG:path:", inputpath
        #print "DBG:file:", inputfilename
        pyfile=utils.timed_file_name("solver-for-"+inputfilename,"py")
        pyfile = os.path.join(inputpath, pyfile)
        #print "DBG: resolved pyfile:", pyfile
    else:
        pyfile = utils.uniqueFileName(pyfile, type="py")   
    
    File2Import=(os.path.basename(pyfile).split("."))[0]
    #
    # generate the code for the solver
    #
    f=open(pyfile,"w")
    f.write("import numpy as np\n")
    # f.write("import solver\n")
    f.write("from scipy.integrate import odeint\n")
    f.write("\n")
    #
    #  paste in the contents of the file "tmp.py" that was produced by generatePythonFunction
    #  with the right hand side of the ode defined in it ode_function_rhs
    #
    for line in rhs: f.write(line)
    #
    # write driver function to run the solver just created 
    f.write("\n\n\n")
    f.write("def thesolver():\n")
    f.write("    filename =\""+filename+"\"\n")
    svars = str(map(utils.deindex, map(str, variables)))
    
		
    
    f.write("    variables="+svars+"\n")
    (runtime, stepsize)=solver.getRunParameters(default_duration=duration,default_step=step)
    f.write("    runtime = "+str(runtime)+" \n")
    f.write("    stepsize = "+str(stepsize)+" \n")
    times = np.arange(0,runtime+stepsize,stepsize)
    f.write("    times = np.arange(0,runtime+stepsize,stepsize)\n")
    f.write("    y0 = "+str(y0)+"\n")   
    
    if len(scan)>0:		
        if scanparameter in variables:
		    ic_index=variables.index(scanparameter)
		    varscan=True
        else:
            f.write("    global " + scanparameter + "\n")
            varscan=False
        f.write("    results=[]\n")
        f.write("    "+scanparameter+"="+str(scanstart)+"\n")
        f.write("    while "+ scanparameter+" <= " + str(scanstop) + ":\n") 
        if varscan:
			f.write("        y0["+str(ic_index)+"]="+scanparameter+"\n")
     
        f.write("        sol = odeint(ode_function_rhs, y0, times, mxstep="+str(mxstep)+")\n") 
        f.write("        "+scanparameter+"+="+str(scandelta)+"\n")
        f.write("        res=["+ scanparameter + "] + list(sol[-1])\n")
        f.write("        results.append(res)\n")
        # f.write("        print res\n")
        f.write("    return results\n")
    else:   
		f.write("    sol = odeint(ode_function_rhs, y0, times, mxstep="+str(mxstep)+")\n")   
		# --- added 7/23/16 to make plotting work for variables in assign
		if assignreplace:
			# 
			# replace held variables with assigned values in interpolation
			#
			# f.write("    print 'times', times\n")
			for command in xtra_rate_commands:
				f.write("    "+command+"\n")
			for information in assign_replace_info:
			    svarindex,set_rhs = information
			    # print svarindex, set_rhs
			    # f.write("    print 'values:', sol[:,"+str(svarindex)+"]\n")
	
			    f.write("    result=["+set_rhs+" for t in times]\n")
			    # f.write("    print result\n")
			    f.write("    sol[:,"+str(svarindex)+"]=result\n")
		# ---- end addition 7/23/16	
	
		f.write("    return sol\n\n")
    #
    # write main program
    #
    f.write("if __name__==\"__main__\":\n")
    f.write("    thesolver()\n\n")
    f.close()
    if timer:
        tgenerate=time.time()-ttimer
 
    #
    # stop here if all you want is the code
    #
    if not run:
        if timer:
            return (tread, tgenerate, os.path.abspath(File2Import))
        else:
            return os.path.abspath(File2Import)
    #    
    #
    # import the code just created
    #
    
    exec("import "+ File2Import)
    
    #
    # run the code just created
    #
    
    exec("temporary_solution = "+File2Import + ".thesolver()") 
    

    if len(scan)>0: 
	# returns a 2-tuple
    # names of the variables (column headers)
    # the solution - one variable per column. 
    # The first column gives the parameter scan from start to finish
    # each column j gives the value of variable j-1 at the end of the run  
	    return (variables, temporary_solution)		
    else:
	# return a tuple with a list of times (row headers)
    # names of the variables (column headers)
    # the solution - one variable per column. Each column is the time course for the corresponding variable in variables
    #  
		return (times, variables, temporary_solution)
Exemplo n.º 12
0
def generateSimulation(inputfile="", step=1, duration=100, plot=False, format="CSV", \
    output="", vars=[], plotcolumns=3, sameplot=True):
    formattype = {"CSV":"CSV","TABLE":"TXT", "TSV":"TSV"}
    # input: model file
    # return value: none
    # output: generates simulation plots from model file 
    # if invoked from command line, "solver -in filename -run duration step"
    
    
    holdrates=[]
    if "-scan" in sys.argv:
        i = (sys.argv).index("-scan")+1
        
        if i+3<len(sys.argv):
            holdrates.append(sys.argv[i])
            scanstart = sys.argv[i+1]
            scanstop = sys.argv[i+2]
            scandelta = sys.argv[i+3]
        else:
            sys.exit("Error: expecting 'K min max delta' after keyword -scan")
        
     
     
    
    (r, ic, rates, frozenvars, functions,assignments, filename)=readmodel(INFILE=inputfile)
    (variables, y0, tmpdotpy) = generatePythonFunction(r, rates, ic, frozenvars, 
        functions, assignments, holdrates)

    
    f=open(tmpdotpy,"r")
    rhs=f.readlines()
    f.close()
    
    try:
        os.remove(tmpdotpy)
    except:
        print "Warning: unable to delete "+os.path.abspath(tmpdotpy)
    
     
    
    
    pyfile = ""
    if ("-pyfile" in sys.argv):
        i = (sys.argv).index("-pyfile")+1
        if i<len(sys.argv):
            pyfile=sys.argv[i]
        else:
            print "Waring: solver: expecting file name after -pyfile option."
            pyfile = "newsolver.py"
    
    if pyfile=="":
        pyfile=utils.timed_file_name("solver-for-"+os.path.basename(filename),"py")

    
    #pyfile = utils.uniqueFileName(pyfile, type="py")   
    f=open(pyfile,"w")
    
    f.write("import numpy as np\n")
    f.write("import cellerator.solver\n")
    f.write("from scipy.integrate import odeint\n")
    f.write("\n")
    for line in rhs: f.write(line)
    f.write("\n\n\n")
    f.write("def thesolver():\n")
    f.write("    filename =\""+filename+"\"\n")
    svars = str(map(utils.deindex, map(str, variables)))

    f.write("    variables="+svars+"\n")
    (runtime, stepsize)=getRunParameters(default_duration=duration,default_step=step)
    f.write("    runtime = "+str(runtime)+" \n")
    f.write("    stepsize = "+str(stepsize)+" \n")
    f.write("    t = np.arange(0,runtime+stepsize,stepsize)\n")
    f.write("    y0 = "+str(y0)+"\n")
    
    if "-mxstep" in sys.argv:
        i=(sys.argv).index("-mxstep")+1
        if i<len(sys.argv):
            mxstep=sys.argv[i]
    else:
        mxstep = "500000"
    
    if len(holdrates)>0:
        f.write("    global " + holdrates[0] + "\n")
        f.write("    results=[]\n")
        f.write("    "+holdrates[0]+"="+str(scanstart)+"\n")
        f.write("    while "+ holdrates[0]+" <= " + str(scanstop) + ":\n")       
        f.write("        sol = odeint(ode_function_rhs, y0, t, mxstep="+mxstep+")\n") 
        f.write("        "+holdrates[0]+"+="+str(scandelta)+"\n")
        f.write("        res=["+ holdrates[0] + "] + list(sol[-1])\n")
        f.write("        results.append(res)\n")
        f.write("        print res\n")
        f.write("    return results\n")
        
    
        f.write("if __name__==\"__main__\":\n")
        f.write("    thesolver()\n\n")
        f.close()
        
           
        return os.path.abspath(pyfile)    
 
            
    f.write("    sol = odeint(ode_function_rhs, y0, t, mxstep="+mxstep+")\n") 
     
    fmt = format
    if "-format" in sys.argv:
        i = (sys.argv).index("-format")+1
        if i<len(sys.argv):
            fmt = sys.argv[i]
    fmt = fmt.upper()
    if not fmt in formattype:
        print "Error: solver: invalid format = ", fmt, " requested."
        fmt = "CSV"
    fmt = formattype[fmt]
    
    outfile=output
    if ("-out" in sys.argv):
        i = (sys.argv).index("-out")+1
        if i<len(sys.argv):
            outfile=sys.argv[i]
            output=utils.uniqueFileName(outfile, type=fmt)
        else:
            print "Warning: solver: expecting file name after -out option."
            #outfile = "solution."+fmt
    if output=="":        
        basename = os.path.basename(filename)
        #basename=basename.split(".")[0]
        outfile = utils.timed_file_name("Solution-for-"+basename,fmt)
           
    #f.write("    outfile = \""+utils.uniqueFileName(outfile, type=fmt)+"\"\n")
    f.write("    outfile = \""+outfile+"\"\n")
    f.write("    of = open(outfile,\"w\")\n")
    f.write("    for i in range(len(t)):\n")
    f.write("        time = t[i]\n")
    f.write("        data = map(str,sol[i])\n")
    demarcater={"CSV":"\",\"","TSV":"\"\t\"","TXT":"\" \""}
    f.write("        data = str(time) + " + demarcater[fmt] + "+(" + demarcater[fmt]+".join(data))\n")
    f.write("        of.write(data+\"\\n\")\n")
    f.write("    of.close()\n")
       
    
    #print "argv is: ", sys.argv
     
    if ("-plot" in sys.argv) or plot==True:
        plotvars = vars
        f.write("    plotvars = "+svars+"\n")
        
        
        if ("-plot" in sys.argv):
            i = (sys.argv).index("-plot")
            if i>0:
                i += 1
                while i<len(sys.argv):
                    nextvar = sys.argv[i]
                    i += 1
                    if nextvar[0]=="-": break
                    nextvar = utils.deindex(str(nextvar))
                    if nextvar in variables:
                        plotvars.append(nextvar)
                    else:
                        print "Error: requested plot variable: "+nextvar+ " does not "\
                        + " exist in the model."
                plotvars = list (set (plotvars) ) # remove any dupes 
                f.write("    plotvars = "+str(plotvars)+"\n")
        if len(plotvars)==0:
            plotvars = variables
            f.write("    plotvars = "+str(plotvars)+"\n")  

        
        plotcols = plotcolumns
        if ("-plotcolumns" in sys.argv):
            i = (sys.argv).index("-plotcolumns") + 1
            if i < len(sys.argv):
                plotcols=int(sys.argv[i])
        plotcols = max(plotcols, 1)
        if ("-sameplot" in sys.argv) or sameplot==True:
            f.write("    cellerator.solver.samePlot(sol, t, variables, filename, plotvars)\n")
        else:  
            f.write("    cellerator.solver.plotVariables(sol, t, variables, filename,"\
            +" plotvars, columns="+str(plotcols)+")\n")
        f.write("    return\n\n")
        
    f.write("if __name__==\"__main__\":\n")
    f.write("    thesolver()\n\n")
    f.close()
    
   
        
    return os.path.abspath(pyfile)    
Exemplo n.º 13
0
def Solve(inputfile,
          step=1,
          duration=100,
          solverfile="",
          output="solution",
          mxstep=50000,
          scan=[],
          run=True,
          RATES={},
          IC={},
          timer=False):
    """Solve(inputfile, step=1, duration=100, solverfile="newsolver.py",
             mxtep=50000, run=True, scan=[], RATES={}, IC={})
    
    input parameters:
    
    inputfile - pyCellerator input file containing a model
    step - (output) step size for integrator. The default integrator
		is odeint. The step size specifies the interpolated output
		values, not the actual values used by the integrator
    duration - duration of integration
    mxstep - maximum number of steps allowed by odeint. 
    solverfile - name of python program that will be automatically
		generated to solve the sytem
    run = True; if false, just generate the code, don't run simulation
    RATES={}: optional dictionary of paramaters that can be used to 
		override one or more rate values in the model
	IC={}: optional dictional of initial conditions that can be used
		to override zero or more initial conditions in the model
		
Return value: when run=True (default)
    tuple (t, variables, solutions)
	where
	t=numpy array of values at which the solution is interpolated.
	variables=list of nambed variables in the solution
	solution=numpy array of values. There is one column for each variable.
		the columns are in the same order as the variable
		names. The length of the columns is the same
		as the length of the values in t. The contents
		of each column contains the values of the corresponding
		variable at the corresponding times in t.
	when run=False, name of simulation code
    """

    # input: model file
    # return value: output of integrator

    hold = []
    if len(scan) > 0:
        if len(scan) == 4:
            scanparameter, scanstart, scanstop, scandelta = scan
            hold = [scanparameter]
            if not isinstance(scanparameter, str):
                sys.exit(
                    "Error: expecting a string for the name of the scan parameter"
                )
        else:
            sys.exit("Error: expeciting scan=['parameter',start,stop,delta]")

    # if invoked from command line, "solver -in filename -run duration step"

    if timer:
        ttimer = time.time()
    (r, ic, rates, frozenvars, functions, assignments,
     filename) = solver.readmodel(INFILE=inputfile)

    if timer:
        tread = time.time() - ttimer

    #print "rates:",rates
    #print "ic:", ic
    for rate in RATES:
        if rate in rates:
            rates[rate] = RATES[rate]
        else:
            print "Warning: unexpected parameter ",rate,\
            " set in RATES not found in model was ignored."
    for variable in IC:
        if variable in ic:
            ic[variable] = IC[variable]
        else:
            print "Warning: unexpected variable ", variable,\
            " set in IC not found model was ignored."
    #print "rates:",rates
    #print "ic:", ic

    if timer:
        ttimer = time.time()
    (variables, y0, tmpdotpy) = solver.generatePythonFunction(r,
                                                              rates,
                                                              ic,
                                                              frozenvars,
                                                              functions,
                                                              assignments,
                                                              holdrates=hold)

    # ----- begin addition 7/23/16
    #
    # look for replacements in assignments
    # these are needed in the wrapper program so that plots work
    #
    assignreplace = False
    assign_replace_info = []
    ratekeys = set(rates.keys())
    ratesneeded = set()
    for ass in assignments:
        #
        # extract the assignment statement itself
        #
        setequal = ass.find("=")
        setvar = ass[:setequal].strip()
        set_rhs = ass[setequal + 1:]
        #print "Cellerator>Solve>assigned var:",setvar, setvar in variables
        #
        # Extract the rate constants that are in this assignment statement
        # Note: variables in RHS expression that are not rates will be missed
        #
        if setvar in variables:
            svarindex = variables.index(setvar)
            #print "Cellerator>Solve>",setvar, "is variable",svarindex,"in",variables
            #print "Cellerator > assignreplace > set_rhs: ", set_rhs
            #
            # variables in assginment statement
            #
            vars_on_rhs = set(re.split("[\)\(\[\]<>\*\+-]|\s", set_rhs))
            #
            # variables that are rates
            #
            ratestoset = ratekeys.intersection(vars_on_rhs)
            #
            # save the name of the rate needed
            #
            ratesneeded |= ratestoset
            #
            # save the assignment statement for later
            assignreplace = True
            assign_replace_info.append([svarindex, set_rhs])

#
# Generate a list of extra python commands to write to the
# driver program for the rate constants
#
    if assignreplace:
        ratestoset = list(ratestoset)
        xtra_rate_commands = []
        for rate_constant in ratestoset:
            rate_value = rates[rate_constant]
            xtra_rate_commands.append(rate_constant + "=" + str(rate_value))
    #
    # --- end addition 7/23/16

    #
    # generatePythonFunction creates the file tmp.py
    #
    f = open(tmpdotpy, "r")
    rhs = f.readlines()
    f.close()
    #
    #clean up
    try:
        os.remove(tmpdotpy)
    except:
        print "Warning: unable to remove the file "+os.path.abspath(tmpdotpy)+"\n+"\
        +"Perhaps an authorization issue? You do not need to keep this file\nand it may be deleted"
    #
    # name the solver program
    #
    pyfile = solverfile
    #print "DBG>>>solverfile:", solverfile
    #print "DBG>>> INPUT >>>", inputfile

    if pyfile == "":
        inputdrive, inputpath = os.path.splitdrive(inputfile)
        inputpath, inputfilename = os.path.split(inputpath)
        #print "DBG:drive:", inputdrive
        #print "DBG:path:", inputpath
        #print "DBG:file:", inputfilename
        pyfile = utils.timed_file_name("solver-for-" + inputfilename, "py")
        pyfile = os.path.join(inputpath, pyfile)
        #print "DBG: resolved pyfile:", pyfile
    else:
        pyfile = utils.uniqueFileName(pyfile, type="py")

    File2Import = (os.path.basename(pyfile).split("."))[0]
    #
    # generate the code for the solver
    #
    f = open(pyfile, "w")
    f.write("import numpy as np\n")
    # f.write("import solver\n")
    f.write("from scipy.integrate import odeint\n")
    f.write("\n")
    #
    #  paste in the contents of the file "tmp.py" that was produced by generatePythonFunction
    #  with the right hand side of the ode defined in it ode_function_rhs
    #
    for line in rhs:
        f.write(line)
    #
    # write driver function to run the solver just created
    f.write("\n\n\n")
    f.write("def thesolver():\n")
    f.write("    filename =\"" + filename + "\"\n")
    svars = str(map(utils.deindex, map(str, variables)))

    f.write("    variables=" + svars + "\n")
    (runtime, stepsize) = solver.getRunParameters(default_duration=duration,
                                                  default_step=step)
    f.write("    runtime = " + str(runtime) + " \n")
    f.write("    stepsize = " + str(stepsize) + " \n")
    times = np.arange(0, runtime + stepsize, stepsize)
    f.write("    times = np.arange(0,runtime+stepsize,stepsize)\n")
    f.write("    y0 = " + str(y0) + "\n")

    if len(scan) > 0:
        if scanparameter in variables:
            ic_index = variables.index(scanparameter)
            varscan = True
        else:
            f.write("    global " + scanparameter + "\n")
            varscan = False
        f.write("    results=[]\n")
        f.write("    " + scanparameter + "=" + str(scanstart) + "\n")
        f.write("    while " + scanparameter + " <= " + str(scanstop) + ":\n")
        if varscan:
            f.write("        y0[" + str(ic_index) + "]=" + scanparameter +
                    "\n")

        f.write("        sol = odeint(ode_function_rhs, y0, times, mxstep=" +
                str(mxstep) + ")\n")
        f.write("        " + scanparameter + "+=" + str(scandelta) + "\n")
        f.write("        res=[" + scanparameter + "] + list(sol[-1])\n")
        f.write("        results.append(res)\n")
        # f.write("        print res\n")
        f.write("    return results\n")
    else:
        f.write("    sol = odeint(ode_function_rhs, y0, times, mxstep=" +
                str(mxstep) + ")\n")
        # --- added 7/23/16 to make plotting work for variables in assign
        if assignreplace:
            #
            # replace held variables with assigned values in interpolation
            #
            # f.write("    print 'times', times\n")
            for command in xtra_rate_commands:
                f.write("    " + command + "\n")
            for information in assign_replace_info:
                svarindex, set_rhs = information
                # print svarindex, set_rhs
                # f.write("    print 'values:', sol[:,"+str(svarindex)+"]\n")

                f.write("    result=[" + set_rhs + " for t in times]\n")
                # f.write("    print result\n")
                f.write("    sol[:," + str(svarindex) + "]=result\n")
        # ---- end addition 7/23/16

        f.write("    return sol\n\n")
    #
    # write main program
    #
    f.write("if __name__==\"__main__\":\n")
    f.write("    thesolver()\n\n")
    f.close()
    if timer:
        tgenerate = time.time() - ttimer

    #
    # stop here if all you want is the code
    #
    if not run:
        if timer:
            return (tread, tgenerate, os.path.abspath(File2Import))
        else:
            return os.path.abspath(File2Import)
    #
    #
    # import the code just created
    #

    exec("import " + File2Import)

    #
    # run the code just created
    #

    exec("temporary_solution = " + File2Import + ".thesolver()")

    if len(scan) > 0:
        # returns a 2-tuple
        # names of the variables (column headers)
        # the solution - one variable per column.
        # The first column gives the parameter scan from start to finish
        # each column j gives the value of variable j-1 at the end of the run
        return (variables, temporary_solution)
    else:
        # return a tuple with a list of times (row headers)
        # names of the variables (column headers)
        # the solution - one variable per column. Each column is the time course for the corresponding variable in variables
        #
        return (times, variables, temporary_solution)
Exemplo n.º 14
0
         if i< len(args):
            mfile=args[i+1]
            if isfile(mfile):
                print "Model: ", realpath(mfile)
            else:
                exit("the file " + mfile + " does not exist.")
         else:
             print "No model file."
    else:
        print "No Model file."
    if "-TISSUE" in upper_args:
         i = upper_args.index("-TISSUE")
         if i< len(args):
            tfile=args[i+1]
            if isfile(tfile):
                print "Tissue: ", realpath(tfile)

            else:
                exit("the file " + tfile + " does not exist.")
         else:
            print "No Tissue file."
    else:
        print "No Tissue file."   
    code = cellzillafy(mfile, tfile)
    oname = utils.uniqueFileName("multicellsolver.py")
    code = [line+"\n" for line in code]
    f=open(oname,"w")
    f.writelines(code)
    f.close()

Exemplo n.º 15
0
def generateSimulation(inputfile="", step=1, duration=100, plot=False, format="CSV", \
    output="", vars=[], plotcolumns=3, sameplot=True):
    formattype = {"CSV": "CSV", "TABLE": "TXT", "TSV": "TSV"}
    # input: model file
    # return value: none
    # output: generates simulation plots from model file
    # if invoked from command line, "solver -in filename -run duration step"

    holdrates = []
    if "-scan" in sys.argv:
        i = (sys.argv).index("-scan") + 1

        if i + 3 < len(sys.argv):
            holdrates.append(sys.argv[i])
            scanstart = sys.argv[i + 1]
            scanstop = sys.argv[i + 2]
            scandelta = sys.argv[i + 3]
        else:
            sys.exit("Error: expecting 'K min max delta' after keyword -scan")

    (r, ic, rates, frozenvars, functions, assignments,
     filename) = readmodel(INFILE=inputfile)
    (variables, y0, tmpdotpy) = generatePythonFunction(r, rates, ic,
                                                       frozenvars, functions,
                                                       assignments, holdrates)

    f = open(tmpdotpy, "r")
    rhs = f.readlines()
    f.close()

    try:
        os.remove(tmpdotpy)
    except:
        print "Warning: unable to delete " + os.path.abspath(tmpdotpy)

    pyfile = ""
    if ("-pyfile" in sys.argv):
        i = (sys.argv).index("-pyfile") + 1
        if i < len(sys.argv):
            pyfile = sys.argv[i]
        else:
            print "Waring: solver: expecting file name after -pyfile option."
            pyfile = "newsolver.py"

    if pyfile == "":
        pyfile = utils.timed_file_name(
            "solver-for-" + os.path.basename(filename), "py")

    #pyfile = utils.uniqueFileName(pyfile, type="py")
    f = open(pyfile, "w")

    f.write("import numpy as np\n")
    f.write("import cellerator.solver\n")
    f.write("from scipy.integrate import odeint\n")
    f.write("\n")
    for line in rhs:
        f.write(line)
    f.write("\n\n\n")
    f.write("def thesolver():\n")
    f.write("    filename =\"" + filename + "\"\n")
    svars = str(map(utils.deindex, map(str, variables)))

    f.write("    variables=" + svars + "\n")
    (runtime, stepsize) = getRunParameters(default_duration=duration,
                                           default_step=step)
    f.write("    runtime = " + str(runtime) + " \n")
    f.write("    stepsize = " + str(stepsize) + " \n")
    f.write("    t = np.arange(0,runtime+stepsize,stepsize)\n")
    f.write("    y0 = " + str(y0) + "\n")

    if "-mxstep" in sys.argv:
        i = (sys.argv).index("-mxstep") + 1
        if i < len(sys.argv):
            mxstep = sys.argv[i]
    else:
        mxstep = "500000"

    if len(holdrates) > 0:
        f.write("    global " + holdrates[0] + "\n")
        f.write("    results=[]\n")
        f.write("    " + holdrates[0] + "=" + str(scanstart) + "\n")
        f.write("    while " + holdrates[0] + " <= " + str(scanstop) + ":\n")
        f.write("        sol = odeint(ode_function_rhs, y0, t, mxstep=" +
                mxstep + ")\n")
        f.write("        " + holdrates[0] + "+=" + str(scandelta) + "\n")
        f.write("        res=[" + holdrates[0] + "] + list(sol[-1])\n")
        f.write("        results.append(res)\n")
        f.write("        print res\n")
        f.write("    return results\n")

        f.write("if __name__==\"__main__\":\n")
        f.write("    thesolver()\n\n")
        f.close()

        return os.path.abspath(pyfile)

    f.write("    sol = odeint(ode_function_rhs, y0, t, mxstep=" + mxstep +
            ")\n")

    fmt = format
    if "-format" in sys.argv:
        i = (sys.argv).index("-format") + 1
        if i < len(sys.argv):
            fmt = sys.argv[i]
    fmt = fmt.upper()
    if not fmt in formattype:
        print "Error: solver: invalid format = ", fmt, " requested."
        fmt = "CSV"
    fmt = formattype[fmt]

    outfile = output
    if ("-out" in sys.argv):
        i = (sys.argv).index("-out") + 1
        if i < len(sys.argv):
            outfile = sys.argv[i]
            output = utils.uniqueFileName(outfile, type=fmt)
        else:
            print "Warning: solver: expecting file name after -out option."
            #outfile = "solution."+fmt
    if output == "":
        basename = os.path.basename(filename)
        #basename=basename.split(".")[0]
        outfile = utils.timed_file_name("Solution-for-" + basename, fmt)

    #f.write("    outfile = \""+utils.uniqueFileName(outfile, type=fmt)+"\"\n")
    f.write("    outfile = \"" + outfile + "\"\n")
    f.write("    of = open(outfile,\"w\")\n")
    f.write("    for i in range(len(t)):\n")
    f.write("        time = t[i]\n")
    f.write("        data = map(str,sol[i])\n")
    demarcater = {"CSV": "\",\"", "TSV": "\"\t\"", "TXT": "\" \""}
    f.write("        data = str(time) + " + demarcater[fmt] + "+(" +
            demarcater[fmt] + ".join(data))\n")
    f.write("        of.write(data+\"\\n\")\n")
    f.write("    of.close()\n")

    #print "argv is: ", sys.argv

    if ("-plot" in sys.argv) or plot == True:
        plotvars = vars
        f.write("    plotvars = " + svars + "\n")

        if ("-plot" in sys.argv):
            i = (sys.argv).index("-plot")
            if i > 0:
                i += 1
                while i < len(sys.argv):
                    nextvar = sys.argv[i]
                    i += 1
                    if nextvar[0] == "-": break
                    nextvar = utils.deindex(str(nextvar))
                    if nextvar in variables:
                        plotvars.append(nextvar)
                    else:
                        print "Error: requested plot variable: "+nextvar+ " does not "\
                        + " exist in the model."
                plotvars = list(set(plotvars))  # remove any dupes
                f.write("    plotvars = " + str(plotvars) + "\n")
        if len(plotvars) == 0:
            plotvars = variables
            f.write("    plotvars = " + str(plotvars) + "\n")

        plotcols = plotcolumns
        if ("-plotcolumns" in sys.argv):
            i = (sys.argv).index("-plotcolumns") + 1
            if i < len(sys.argv):
                plotcols = int(sys.argv[i])
        plotcols = max(plotcols, 1)
        if ("-sameplot" in sys.argv) or sameplot == True:
            f.write(
                "    cellerator.solver.samePlot(sol, t, variables, filename, plotvars)\n"
            )
        else:
            f.write("    cellerator.solver.plotVariables(sol, t, variables, filename,"\
            +" plotvars, columns="+str(plotcols)+")\n")
        f.write("    return\n\n")

    f.write("if __name__==\"__main__\":\n")
    f.write("    thesolver()\n\n")
    f.close()

    return os.path.abspath(pyfile)
Exemplo n.º 16
0
def generatePythonFunction(reactions,
                           rates,
                           ics,
                           frozenvars,
                           functions,
                           assignments,
                           holdrates=[],
                           substituteRates=False):
    """
    input: reactions - list of reactions in cellerator text form
           inputrates - list of rate constants in dictionary form
    output: writes a function to file tmp.py that is solver-compatible
        return values: (y, y0)
        y: list of string names of variables ["y1", "y2",...]
        y0: list of values of variables at initial time
    """

    #print "solver:assignments:",assignments
    #print "solver:frozenvars:",frozenvars

    d = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    codefile = utils.uniqueFileName("tmp.py")

    f = open(codefile, "w")
    f.write("from math import *\n")
    if len(functions) > 0:
        f.write("\n")
        for funct in functions:
            f.write(funct + "\n")
        f.write("\n")
    f.write("def ode_function_rhs(y,t):\n")
    f.write("  # \n")
    f.write("  # this odeint(..) compatible function was \n")
    f.write("  # automatically generated by Cellerator " + d + " \n")
    ver = sys.version.replace("\n", " ")
    f.write("  # " + ver + "\n")
    f.write("  # " + sys.platform + "\n")
    f.write("  # \n")
    f.write(
        "  # =============================================================\n")
    f.write("  # Model: \n  #\n")

    #
    # there may be a whole boatload of reactions to print
    # define a generator
    def printable_reaction(k):
        for j in xrange(k):
            reaction = reactions[j]
            yield "  # " + reaction.strip() + "\n"

    for r in printable_reaction(len(reactions)):
        f.write(r)
    #for reaction in reactions:
    #    f.write("  # " + reaction.strip() + "\n")
    #
    # write a whole shitload of comments with the rate constants, unless
    # the rate constants are themselves written out
    #
    if substituteRates:
        f.write("  #\n  # Parameter values used: \n  #\n")
        for r in rates:
            f.write("  # " + r + "=" + str(rates[r]) + "\n")
    if len(holdrates) > 0:
        f.write("  global " + holdrates[0] + "\n")
    if len(frozenvars) > 0:
        f.write(
            "  #\n  # Frozen Variables (species with fixed derivatives):\n  #\n"
        )
        for v in frozenvars:
            f.write("  # " + str(v) + "\n")
    f.write(
        "  # =============================================================\n")

    results = interpreter.invokeParser(reactions, dump=False)
    results = expand(results)
    s = interpreter.makeSymbolDictionary(results, rates, ics)
    odeterms = interpreter.makeODETerms(results, s, frozen=frozenvars)

    if substituteRates:
        newterms = substituteRateConstants(odeterms, rates, s, holdrates)
        na = []
        # rate constants also appear in assignment rules
        for a in assignments:
            value, assignment = a.split("=")
            assignment = sympify(assignment)
            newassignment = value + "=" + str(
                applyReplacementRules(assignment, rates, s))
            na.append(newassignment)
        assignments = na
    else:  # better this way because applyReplacementRules grows superquadratically
        newterms = odeterms
        ks = rates.keys()
        ks.sort()
        f.write("  # rate constants\n")
        for k in ks:
            if k in holdrates:
                continue
            v = rates[k]
            nextline = "  " + k + " = " + str(v) + "\n"
            f.write(nextline)

    (y, yprime, ics) = makeODEfunc(newterms, s, ics)

    y = map(str, y)
    yprime = map(str, yprime)
    f.write("# pick up values from previous iteration\n")
    n = len(y)
    for i in range(n):
        nextline = "  " + y[i] + " = " + "max(0, y[" + str(i) + "])\n"
        #
        nextline = nextline.replace("{", "[").replace("}", "]")
        #
        f.write(nextline)
    if (len(assignments) > 0):
        f.write("# apply boundary conditions / assignment rules \n")
    for a in assignments:
        f.write("  " + a + "\n")
    f.write("# calculate derivatives of all variables\n")
    f.write("  yp=[0 for i in range(" + str(n) + ")]\n")
    for i in range(n):
        nextline = "  yp[" + str(i) + "] = " + yprime[i] + "\n"
        #
        #
        #
        nextline = nextline.replace("{", "[").replace("}", "]")
        #
        #
        f.write(nextline)
        #print "solver:",nextline

    f.write("  return yp\n")
    f.close()

    #sys.exit()
    return (y, ics, codefile)
Exemplo n.º 17
0
        i = upper_args.index("-IN")
        if i < len(args):
            mfile = args[i + 1]
            if isfile(mfile):
                print "Model: ", realpath(mfile)
            else:
                exit("the file " + mfile + " does not exist.")
        else:
            print "No model file."
    else:
        print "No Model file."
    if "-TISSUE" in upper_args:
        i = upper_args.index("-TISSUE")
        if i < len(args):
            tfile = args[i + 1]
            if isfile(tfile):
                print "Tissue: ", realpath(tfile)

            else:
                exit("the file " + tfile + " does not exist.")
        else:
            print "No Tissue file."
    else:
        print "No Tissue file."
    code = cellzillafy(mfile, tfile)
    oname = utils.uniqueFileName("multicellsolver.py")
    code = [line + "\n" for line in code]
    f = open(oname, "w")
    f.writelines(code)
    f.close()
Exemplo n.º 18
0
def generatePythonFunction(reactions,  rates, ics, frozenvars, functions, 
    assignments, holdrates=[], substituteRates=False):
    """
    input: reactions - list of reactions in cellerator text form
           inputrates - list of rate constants in dictionary form
    output: writes a function to file tmp.py that is solver-compatible
        return values: (y, y0)
        y: list of string names of variables ["y1", "y2",...]
        y0: list of values of variables at initial time
    """    
  
    #print "solver:assignments:",assignments
    #print "solver:frozenvars:",frozenvars
    
    d=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    codefile=utils.uniqueFileName("tmp.py")
    
    f=open(codefile,"w")
    f.write("from math import *\n")
    if len(functions)>0:
        f.write("\n")
        for funct in functions: f.write(funct+"\n")
        f.write("\n")
    f.write("def ode_function_rhs(y,t):\n")
    f.write("  # \n")
    f.write("  # this odeint(..) compatible function was \n")
    f.write("  # automatically generated by Cellerator "+d+" \n")
    ver = sys.version.replace("\n"," ")
    f.write("  # " + ver + "\n")
    f.write("  # " + sys.platform + "\n")
    f.write("  # \n")
    f.write("  # =============================================================\n")
    f.write("  # Model: \n  #\n")
    #
    # there may be a whole boatload of reactions to print 
    # define a generator
    def printable_reaction(k):
        for j in xrange(k):
            reaction=reactions[j]
            yield "  # " + reaction.strip() + "\n"
    for r in printable_reaction(len(reactions)):
        f.write(r)
    #for reaction in reactions:
    #    f.write("  # " + reaction.strip() + "\n")
    #
    # write a whole shitload of comments with the rate constants, unless
    # the rate constants are themselves written out
    #
    if substituteRates:
        f.write("  #\n  # Parameter values used: \n  #\n")
        for r in rates:
            f.write("  # " + r + "=" + str(rates[r]) + "\n")
    if len(holdrates)>0:
        f.write("  global "+holdrates[0]+"\n")
    if len(frozenvars) >0:
        f.write("  #\n  # Frozen Variables (species with fixed derivatives):\n  #\n") 
        for v in frozenvars: f.write("  # "+str(v)+ "\n")
    f.write("  # =============================================================\n")
    
    
    results = interpreter.invokeParser(reactions, dump=False)
    results = expand(results)
    s=interpreter.makeSymbolDictionary(results, rates, ics)
    odeterms = interpreter.makeODETerms(results, s, frozen=frozenvars)
    
    if substituteRates:
        newterms = substituteRateConstants(odeterms, rates, s, holdrates)
        na = []
       # rate constants also appear in assignment rules
        for a in assignments:
            value,assignment = a.split("=")
            assignment = sympify(assignment)
            newassignment = value+"="+str(applyReplacementRules(assignment, rates, s))
            na.append(newassignment)
        assignments = na
    else:  # better this way because applyReplacementRules grows superquadratically
        newterms = odeterms
        ks=rates.keys()
        ks.sort()
        f.write("  # rate constants\n")
        for k in ks:
            if k in holdrates:
                continue
            v=rates[k]
            nextline="  "+k+" = " + str(v)+"\n"
            f.write(nextline)
   
    (y, yprime, ics) = makeODEfunc(newterms, s, ics)
   
    
    y = map(str, y)
    yprime = map(str,yprime)
    f.write("# pick up values from previous iteration\n")  
    n = len(y)
    for i in range(n):
        nextline = "  "+y[i]+" = "+"max(0, y["+str(i)+"])\n"
        #
        nextline = nextline.replace("{","[").replace("}","]")
        #
        f.write(nextline)
    if (len(assignments)>0):
        f.write("# apply boundary conditions / assignment rules \n")
    for a in assignments:
        f.write("  "+a+"\n")
    f.write("# calculate derivatives of all variables\n")
    f.write("  yp=[0 for i in range("+str(n)+")]\n")
    for i in range(n):
        nextline = "  yp["+str(i)+"] = " + yprime[i]+"\n"
        #   
        #
        #
        nextline = nextline.replace("{","[").replace("}","]")
        #
        #
        f.write(nextline)
        #print "solver:",nextline

    
    
    f.write("  return yp\n")
    f.close()
    
    #sys.exit()
    return (y, ics, codefile)