Esempio n. 1
0
    def writeAnnotatedTargets(self,objective,model,annotationName,regex,iteration,oPrediction={},nPrediction={},outputFileName=None):
        
        if outputFileName == None:
            outputFileName = "Target_Report_T_%s_C_%s_M_%s_N_%s_S_%s_K_%s_I_%s.txt" % (self.resultTag,self.control,self.modelName,self.naturalObjectiveName,self.syntheticObjectiveName,self.con.controlMax,iteration)
            
        aValue = self._annotateObjective(objective, model, annotationName, regex)
        controlValues = self._condenseObjective(objective)
        controlValues = self._annotateGenes(controlValues, model, annotationName, regex)
        controlScores = self._controlScore(objective,oPrediction, nPrediction)
        controlScores = self._annotateGenes(controlScores, model, annotationName, regex)
        controlScore = self._condenseMap(controlScores,sum)
        
        report = Report()
        report.addColumnHash("Control", aValue)
        report.addColumnHash("Flux", controlScore)
        report.addColumnHash("Reaction Control", controlValues)
        report.addColumnHash("Flux Changes", controlScores)

        oName = self.resultDirectory + outputFileName
        try:
            writer = ReportWriter()
            writer.setFile(oName)
            writer.write(report) 
            writer.closeFile()
            if self.verbose: print "Report written [%s]" % (outputFileName)
        except:
            if self.verbose: print "Failed to write report [%s] " % (outputFileName)
        
        return None
Esempio n. 2
0
 def writeReport(self,ltReport,fluxModel, oPredVal,sPredVal,s2PredVal,neighborhood,iterations,fObjective,resultDir):
     if self.verbose: print "Preparing report ..."        
     report = Report()
     reactionNames = fluxModel.network.getOrderedReactionNames()
     reactionMap = fluxModel.network.getReactionMap()
     
     for reactionName in reactionNames:
         reaction = reactionMap[reactionName]
         equation = reaction.getEquation()
         pathway = reaction.getAnnotation("Subsystem")
         name = reaction.getName()#Currently sensitivity values can be too large for control factors.
         report.addElement(reactionName,"name",name)
         report.addElement(reactionName,"equation", equation)
         report.addElement(reactionName,"Subsystem", pathway)
         
     #--------------------
     #Analysis in report
     #--------------------
     report.addColumnHash("Original", oPredVal)
     report.addColumnHash("Synthetic", sPredVal)
     report.addColumnHash("Synthetic mBio", s2PredVal)
     report.extend(ltReport)
         
     report.addColumnHash("Final Objective", fObjective)
 
     #--------------------
     #Write Report
     #--------------------
     if self.verbose: print "Writing report ..."
     outputFileName = resultDir + "RD_" + self.resultTag + "_" + self.modelName + "_" + self.syntheticObjectiveName + "_" + str(neighborhood) + "_" + str(iterations) +  "_" + strftime('%Y%m%dT%H%M%S') + ".txt"  
     
     writer = ReportWriter()
     writer.setFile(outputFileName)
     writer.write(report) 
     writer.closeFile()
     if self.verbose: print "Report Written [%s]" % (outputFileName)
     
     return report 
     
def main_function():

    parser = OptionParser()

    parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="set verbose mode")

    parser.add_option(
        "--config",
        type="string",
        metavar="FILE",
        dest="config",
        default="redirector.config",
        help="Master configuration file that provides most setting for the Flux Balanace Analysis. Extra variable settings will be ingnored.  Hence the same config can be used for multiple analysis functions",
    )

    parser.add_option(
        "-c",
        "--modelConfig",
        type="string",
        metavar="FILE",
        dest="configFileName",
        default="model_config.txt",
        help="Configuration file which sets model files",
    )

    parser.add_option(
        "-n",
        "--configNames",
        type="string",
        metavar="String",
        dest="configNames",
        default="Default",
        help="A comma separated list of the names of configurations to use, as set out in the configuration file",
    )

    parser.add_option(
        "-m",
        "--modelname",
        type="string",
        metavar="String",
        dest="modelName",
        default="",
        help="Name of model(s) from the modelconfiguration file",
    )

    parser.add_option(
        "-b",
        "--bioObjective",
        type="string",
        dest="bioObj",
        default="Biomass",
        help="Name / ID of biological objective reaction",
        metavar="String",
    )

    parser.add_option(
        "-o",
        "--outputfile",
        dest="outputFileName",
        default=None,
        help="Name of report file to be generated",
        metavar="FILE",
    )

    parser.add_option(
        "-r",
        "--result_directory",
        type="string",
        metavar="directory",
        dest="resultDirectory",
        default="../../results/",
        help="Directory where results are stored",
    )

    parser.add_option(
        "--targets",
        type="string",
        metavar="String",
        dest="targets",
        default="",
        help="List of valid reaction target, if left blank will be automatically filled in from metabolic network file",
    )

    parser.add_option(
        "--report",
        action="store_true",
        dest="isReport",
        default=False,
        help="When this tag is used a report will be generated when the analysis is finished",
        metavar="boolean",
    )

    parser.add_option("--debug", action="store_true", dest="debug", default=False, help="turn on debug mode")

    parser.add_option("--gm", "--GeneMap", action="store_true", dest="useGeneMap", default=False, help="Use Gene Map")

    parser.add_option(
        "--section",
        type="string",
        metavar="String",
        dest="subSections",
        default="",
        help="Comma separated list of sections of the model files to use",
    )

    # -------------------------------
    # Parse options
    # -------------------------------

    (options, args) = parser.parse_args()
    config = ReflectionConfig()
    config.readfp(open("Redirector.config"))

    # ---------------------------
    # configure preset analysis
    # ---------------------------

    configNames = options.configNames.split(",")
    configNames.insert(0, "Redirector Model")
    for name in configNames:
        config.merge(name, "Redirector", append=True)

    # ----------------------------------------
    # reflect options from configuration
    # ----------------------------------------

    config.reflect("Redirector", options)
    config.load("Redirector", options.__dict__, override=False)

    # -----------------------------------------
    # Check and Build Storage Directories
    # -----------------------------------------

    dataDirectory = config.getValue("Redirector", "dataDirectory", classType="".__class__)
    resultsDirectory = config.getValue("Redirector", "resultDirectory", classType="".__class__)
    analysisDirectory = config.getValue("Redirector", "analysisDirectory", classType="".__class__)

    if not os.path.exists(dataDirectory):
        raise IOError("unable to find required data directory" % dataDirectory)
    if not os.path.exists(resultsDirectory):
        os.makedirs(resultsDirectory)
    if not os.path.exists(analysisDirectory):
        os.makedirs(analysisDirectory)

    # ----------------------------
    # Parse Inputs
    # ----------------------------

    verbose = options.verbose
    modelName = options.modelName
    objectiveName = options.bioObj
    outputFileName = options.outputFileName

    """
    #----------------------------------------------------
    # Initialize and set values for tools and factories
    #----------------------------------------------------
    """

    naturalObjective = {objectiveName: -1.0}

    if verbose:
        print "Flux Balanace Analysis Version 1.6"
    if verbose:
        print "Model names: [%s]" % (modelName)
    if verbose:
        print "Parsing data files for [%s]" % (modelName)

    """
    I. Parse data files and configuration settings
    """

    if verbose:
        print "----------------Loading Metabolic Models---------------"
    modelNames = modelName.split(",")
    modelFactory = ModelFactory()
    config.reflect("Redirector", modelFactory)
    (fluxModel, modelMatrix, reducer, geneReduction) = modelFactory.loadModel(modelNames)

    model = modelMatrix
    if verbose:
        print "removing objectives from target set"
    targets = modelMatrix.targets
    if verbose:
        print "Targets List Size [%s]" % len(targets)

    lps = LPSolver()
    predictions = lps.run(model, naturalObjective)
    objectiveValue = predictions[objectiveName]
    lps.clear()

    if verbose:
        print "Optimized Objective [%s] Value [%s]" % (objectiveName, objectiveValue)

    report = fluxModel.getReport()
    report.addColumnHash("Flux", predictions)

    if outputFileName == None or outputFileName == "":
        outputFileName = resultsDirectory + "FBA_%s_%s.txt" % (modelName, strftime("%Y%m%dT%H%M%S"))

    writer = ReportWriter()
    writer.setFile(outputFileName)
    writer.write(report)
    writer.closeFile()

    if verbose:
        print "Report Written [%s]" % (outputFileName)
def findBestTargetSets(targetFileObjectives,k,n):        
    targetdir = "../../results/"
    #reportTag = "Target_Report_M_%s,_N_%s_S_%s_K_%s_I_%s.txt"
    modelTag = "iAF1260,iAF1260_FattyAcids"
    #naturalTag = "Biomass"
    controls = ["flat","cp","T_cp_C_sense","T_cp_C_flat","T_cp_binary"]
    #controls = ["flat","cp","T_cp_C_flat"]
    #controlFilter = lambda x : x in [1.0,-1.0]
    controlFilter = lambda x: True
            
    #fileNameTag = targetdir + "Target_Report_T_flat_C_flat_iAF1260,iAF1260_FattyAcids_N_Biomass_S_%s_K_%s_I_%s.txt"
    fileNameTag = targetdir + "Target_Report_%s_M_iAF1260,iAF1260_FattyAcids_N_Biomass_S_%s_K_%s_I_%s.txt"

    sObjectiveTags = targetFileObjectives.split(",")
    (targetSummaryReport,targetProductReport) = loadVariousControlTable(fileNameTag, controls, sObjectiveTags, k, n, filter = controlFilter)
        
    targetReportFileName = "ControlSearches/Control_Target_Summary_Report_%s_%s_%s_%s_k%s_n%s.csv" % (resultTag,options.modelName,naturalObjectiveName,syntheticObjectiveName,k,n)
    print "Writing target report %s" % targetReportFileName
    writer = ReportWriter()
    writer.setFile(targetReportFileName)
    writer.write(targetSummaryReport) 
    writer.closeFile()
        
    targetProductReportFileName = "ControlSearches/Control_Target_Product_Report_%s_%s_%s_%s_k%s_n%s.csv" % (controls,modelTag,naturalObjectiveName,syntheticObjectiveName,k,n)
    print "Writing target product report %s" % targetProductReportFileName
    writer = ReportWriter()
    writer.setFile(targetProductReportFileName)
    writer.write(targetProductReport) 
    writer.closeFile()

    return None
 elif options.loadFlatDep != '':
     keyTag = "Row Names"
     controlTag = 'control values'
     productionTag = 'production'
     (dependencyMaps,dReport) = loadControlTable(options.loadFlatDep, keyTag, controlTag, productionTag)
 else:
     (dependencyMaps,dReport) = controlDependencies(modelMatrix,resultTag,options,targetPercent,verbose=True,usePersist=usePersist)
     
 if options.outputFileName != '':
     reportFileName = "ControlSearches/Control_dependency_%s_%s_%s_%s_k%s_n%s_s%s.csv" % (resultTag,options.modelName,naturalObjectiveName,syntheticObjectiveName,k,n,str(searchDepth))
 else:
     reportFileName = options.outputFileName
 
 if searchDepth != 0: 
     print "Writing dependency report"
     writer = ReportWriter()
     writer.setFile(reportFileName)
     writer.write(dReport) 
     writer.closeFile()
     
 '''
 Build undirected graph of dependency control sets
 '''
 
 if options.makeGraph:
     dgraph = buildDependencyControlGraph(dependencyMaps)
     graphFileName =  "ControlSearches/Dep_Graph_%s" % persistTag
     if verbose: "writing undirected dependency graph [%s]" % graphFileName
     dgraph.write_ps(graphFileName + ".eps")
     dgraph.write(graphFileName + ".dot")
     
Esempio n. 6
0
         isRecord = SeqRecord(iSeq,id=id)
         seqRegions.append(isRecord)
     
     sRegionHandel = open("OligoSequenceRegions.fasta","w")
     SeqIO.write(seqRegions,sRegionHandel,"fasta")
     sRegionHandel.close()
     
     seqTools = SequenceTools()
     seqTools.verbose = verbose
     primerReport = seqTools.findPrimers(seqData, targetMap, boundary=primerDistance, oligoSize=primerSize, searchSize=60, targetTm=primerTm)
     report.extend(primerReport)
     
     #----------------------------
     # Write Report
     #----------------------------
     writer = ReportWriter()
     writer.setFile(oligoFileName)
     writer.write(report)
     writer.closeFile()
     
 #-----------------------------------------
 # do comparison of recombination oligos
 #  to sequecing of strains
 #-----------------------------------------
 
 if mode == "sequence" or (mode == "auto" and recSeqFileName != ''):
     if verbose: print "blasting sequences of recombinations"
     #sequencingFeatures = seqTools.seqBlastToFeatures(blastDB, blastExe, seqResultFile, blastType = "blastn",scoreMin = 1e-5)
     blastRecords = seqTools.seqBlast(blastDB, blastExe, recSeqFileName, blastType = "blastn")
     if verbose: print "finsihed blasting"