Ejemplo n.º 1
0
def fluxreport(fluxdict,
               expfluxdict=load.ExpFluxesfromXML('expdata.xml', 'Perrenoud',
                                                 'Batch', 'aerobe'),
               exp_errordict=load.ExpErrorsfromXML('expdata.xml', 'Perrenoud',
                                                   'Batch', 'aerobe')):

    fluxdictcopy = copy.deepcopy(fluxdict)
    for key in fluxdictcopy:
        if key not in expfluxdict:
            del fluxdict[key]

    diff_dict = {key: (expfluxdict[key] - fluxdict[key]) for key in fluxdict}
    #bug here: KeyError: '26'

    #uncertfraction = difference / experrors
    uncertfrac_dict = {
        key: (np.divide(diff_dict[key], exp_errordict[key]))
        for key in fluxdict
    }

    textheader = [
        "Ex rxn #", "Com. flux", "Exp flux", "Diff.", "Exp. uncert.",
        "Diff/uncert."
    ]

    outsidefluxes = 0
    for key in uncertfrac_dict:
        if (abs(uncertfrac_dict[key]) >
                1) and (~np.isinf(abs(uncertfrac_dict[key]))):
            outsidefluxes += 1

    import datetime
    now = datetime.datetime.now()
    print("Flux report generated at:", now)
    print("Solver:")
    print("Model:")
    print("Objective:")
    print("Constraints:")
    print("Number of computed fluxes outside experimental uncertainty bounds:",
          outsidefluxes)

    #print 'fluxdict:',fluxdict #DEBUG
    #print 'expfluxdict:',expfluxdict #DEBUG

    print("%15s %15s %15s %15s %15s %15s" % tuple(textheader))

    #for key in fluxdict:
    #print key #DEBUG
    #print fluxdict[key]
    #print expfluxdict[key]
    #print diff_dict[key]
    #print exp_errordict[key]
    #print uncertfrac_dict[key]
    #print uncertfrac_dict
    #print "%s %15.1f %15.1f %15.1f %15.1f %15.1f" % (key,float(fluxdict[key]),float(expfluxdict[key]),float(diff_dict[key]),float(exp_errordict[key]),float(uncertfrac_dict[key]))
    #Commenting out above line for the moment, as not sure how the Pythn 3 syntax for this is.

    return diff_dict
def compdistdict(fluxdict, expdata=None, options=None, sense=None):
    if expdata == None:
        expdata = load.ExpFluxesfromXML('expdata.xml', 'Perrenoud', 'Batch',
                                        'aerobe')

    fluxvector = []
    fluxvalues = []

    for key in fluxdict:
        if (key in expdata):
            fluxvector.append(fluxdict[key])
            fluxvalues.append(float(expdata[key]))

    dist = np.linalg.norm(np.array(fluxvector) - np.array(fluxvalues))
    return dist
def compdist(fluxvector,
             expdata=None,
             options=None,
             sense=None,
             extract=True,
             rmap='Default'):
    rmap = load.ReactionMapfromXML('reactionmaps.xml', 'Perrenoud', 'SCHUETZR')
    if extract:
        fluxvector = extractflux.extractfluxvector(fluxvector, rmap)

    if expdata == None:
        expdata = load.ExpFluxesfromXML('expdata.xml',
                                        'Perrenoud',
                                        'Batch',
                                        'aerobe',
                                        vector=True)
    dist = np.linalg.norm(np.array(fluxvector) - np.array(expdata))
    return dist
Ejemplo n.º 4
0
def compdistcomplete(rawfluxvector,model, debug = False):
    if debug:
        print('compdistcomplete: Calculating distance...')
    import loadData as load
    import extractflux
    #print 'Loading experimental data...'
    expdata = load.ExpFluxesfromXML('expdata.xml','Perrenoud','Batch','aerobe')
    #print 'Loading reaction map...'
    rmap = load.ReactionMapfromXML('reactionmaps.xml','Perrenoud','SCHUETZR')

    tup = zip([reaction.id for reaction in model.reactions],rawfluxvector,) #
    rawfluxdict = {reactionid:fluxvalue for reactionid,fluxvalue in tup}
    extractfluxdict = extractflux.extractfluxdict(rawfluxdict,rmap)
    fluxvector = []
    fluxvalues = []

    for key in extractfluxdict:
        if (key in expdata):
            fluxvector.append(extractfluxdict[key])
            fluxvalues.append(float(expdata[key]))
 
    dist = np.linalg.norm(np.array(fluxvector)-np.array(fluxvalues))

    return dist

def printsplits(splits):

    keys = splits.keys()
    keys.sort(key=int)
    for key in keys:
        print key,'%.2f' %splits[key]

if __name__ == "__main__":

    import loadData as load
    from cobra.io.sbml import create_cobra_model_from_sbml_file
    import extractflux as extract

    expfluxes = load.ExpFluxesfromXML('expdata.xml','Perrenoud','Batch','aerobe')

    splitmap = load.SplitMapfromXML('reactionmaps.xml','SCHUETZR','EXPDATA')

    splits = computesplits(expfluxes,splitmap)
    print 'Experimental splits:'
    printsplits(splits)
    splitmap = load.SplitMapfromXML('reactionmaps.xml','SCHUETZR','SCHUETZR')

    cobramodel = create_cobra_model_from_sbml_file('../SBML/SCHUETZR.xml')
    cobramodel.optimize(solver='gurobi')

    compfluxes = extract.vectorToDict(cobramodel.solution.x,cobramodel)
    
    compsplits = computesplits(compfluxes,splitmap)
    print 'SCHUETZR FBA result splits:'
Ejemplo n.º 6
0
def optreqanalysis(modeldicts,
                   objectives,
                   experiments,
                   steps=10,
                   makeplots=True,
                   expfluxdict="Default",
                   plotter="easyviz"):
    '''Function for evaluating how the minimally achievable distance between a flux solution and a set of experimental fluxes
    changes when varying the required relative FBA objective-optimality of the flux solution.

    syntax: optreqanalysis(modeldicts,objectives,experiments,steps = 10,makeplots = True,expfluxdict)

    arguments:
    modeldicts: An array of python dictionaries with the following fields:
        modelobject: A CobraPy model object for the model in question.
        reactionmap: A reaction map array mapping between model reactions and experimental reactions for the model and experiment in question.
    objectives: A list of objectives to be used in the analysis.
    experiments: A list of experiments to be used in the analysis
    steps: The granularity of the analysis and produced plots.
    makeplots: Whether plots should be produced or not
    expfluxdict: A python dictionary with experiment-ids as keys and the corresponding flux value arrays as values.
    '''
    for objective in objectives:
        pass  #Placeholder

    for experiment in experiments:
        pass  #Placeholder

    if expfluxdict == "Default":  #This section should be rewritten to use an "expflux" dict.
        expdata = scipy.io.loadmat('expdata.mat')  #load experimentaldata
        perrenoud = expdata['expdata']['perrenoud']
        fluxvalarray = perrenoud[0][0][0][0][0][0][0][0][0][0][0][0][0][0]
        fluxvalues = [row[0] for row in fluxvalarray
                      ]  #expdata.perrenoud.abs.batch.aerobe.fluxvalues

        expfluxdict = load.ExpFluxesfromXML('expdata.xml', 'Perrenoud',
                                            'Batch', 'aerobe')

    resultlist = []
    for modeldict in modeldicts:
        cobramodel = modeldict['modelobject']
        #print 'modeldict:',modeldict
        reactionmap = modeldict['reactionmap']
        #print 'cobramodel:',cobramodel
        #print type(cobramodel)

        optreqs = []
        for i in range(steps + 1):
            optreqs.append(float(i) / steps)
        results = []
        #print 'opreqs:',optreqs
        #q = raw_input('Continue?')
        for optreq in optreqs:
            optimizedmodel = QPmindist(cobramodel, fluxvalues, reactionmap,
                                       optreq)
            results.append(math.sqrt(optimizedmodel.ObjVal))
        resultlist.append(results)
        #Using easyviz
        #ev.plot(optreqs,results)
        #ev.hold()

        #Using prettyplotlib
        #fig, ax = plt.subplots(1)
        #ppl.scatter(ax, x, y)
        #ppl.plot(optreqs,results)
    return resultlist