示例#1
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)
示例#2
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)
示例#3
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)
示例#4
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)