def build_wil(self, withdb = False, verbose=False):
        if self.start_type.upper() == "YAML":
            self.model.buildfromyaml(self.infile,self.exchangefname)
            self.model.setbiomass(self.biomassfname)
            self.model.convertMet2KeggIDs()
            self.model.addTransports()
            self.model.writeWil(self.outprefix + "Working.wil")
            self.write = True
        elif self.start_type.upper() == "SBML" or self.start_type.upper() == "SEED":
            self.model.read_sbml(self.infile) 
            self.model.convertMet2KeggIDs()  #adds "M_" to metabolite names
            name, reversible, notes, equation = self.model.REACTIONS[biomassReactionID] 
            self.model.add_reaction("R_biomass_target", "BiomassRxn", False, notes, equation) 
            self.model.delete_reaction(biomassReactionID)
            self.model.addTransports()
            self.model.writeWil(self.outprefix + "Working.wil")
            self.write = True
        elif self.start_type.upper() == "TEXT" or self.start_type.upper() == "TXT":
            self.model.build_from_textfiles(modelfile=self.infile, exchangesfile=self.exchangefname, biomassfile=self.biomassfname, sourcesfile=self.sourcesfname, escapesfile=self.escapesfname)
            self.model.convertMet2KeggIDs()
            self.model.addTransports()
            self.model.writeWil(self.outprefix + "Working.wil")
            self.model.writeWil(self.outprefix + "Stable.wil")
            self.write = False
        del self.model
        self.model = mg.gurobicb()
        w2m.wil2metmodel(self.wilfname)
        self.model.build_from_textfiles(modelfile=self.modelname + ".reactions", biomassfile=self.modelname + ".biomass", sourcesfile=self.modelname+".sources", escapesfile=self.modelname +".escapes",exchangesfile="")
        if self.write:
            self.model.writeWil(self.outprefix + "Working.wil")
            self.model.writeWil(self.outprefix + "Stable.wil")

        self.model.solve(verbose=verbose,out=self.outprefix + 'draft')

        if self.model.OBJECTIVE_VALUE < self.epsilon:
            model2 = deepcopy(self.model)
        if withdb:
            model2.fbagapdb(out=self.outprefix)
        else:
            model2.fbagapnodb(out=self.outprefix)

        self.model.writeECfile(self.outprefix  + "ec1.txt")
        metfile = open(self.outprefix + "metabolites1.txt","w")
        numspecies = 0
        for species in self.model.SPECIES.keys():
            if not species.endswith("_b"):
                metfile.write("%s\n" % (species))
                numspecies += 1
        numreactions = 0
        for reactions in self.model.REACTIONS.keys():
            if (not reactions.startswith("R_SRC")) and (not reactions.startswith("R_ESC")) and (not reactions.startswith("R_EXCH")):
                numreactions += 1
        del model2
        del self.model
        return numspecies,numreactions
 def mapFlux(self):
     self.model = mg.gurobicb()
     
     w2m.wil2metmodel(self.wilfname)
     self.model.build_from_textfiles(modelfile=self.modelname + ".reactions", biomassfile=self.modelname + ".biomass", sourcesfile=self.modelname+".sources", escapesfile=self.modelname +".escapes",exchangesfile="")
     self.model.solve(maps=True,out=self.outprefix)
     self.model.writeECfile(self.outprefix + "ec4.txt")
     metfile = open(self.outprefix+"metabolites4.txt", "w")
     numspecies = 0
     for species in self.model.SPECIES.keys():
       if not species.endswith("_b"):
         metfile.write("%s\n" % (species))
         numspecies += 1
     numreactions = 0
     for reactions in self.model.REACTIONS.keys():
       if (not reactions.startswith("R_SRC")) and (not reactions.startswith("R_ESC")) and (not reactions.startswith("R_EXCH")):
         numreactions += 1
     return numspecies,numreactions
 def metabolite_integration(self, metfile=args.met, threshold=args.thr):
   # if metabolite present, sum of reactions producing that metabolite is at least epsilon
     self.model = mg.gurobicb()
     
     w2m.wil2metmodel(self.wilfname)
     self.model.build_from_textfiles(modelfile=self.modelname + ".reactions", biomassfile=self.modelname + ".biomass", sourcesfile=self.modelname+".sources", escapesfile=self.modelname +".escapes",exchangesfile="")
     self.model.metaboliteIntegration(metfile, threshold)
     self.model.writeECfile(self.outprefix + "ec5.txt")
     metfile = open(self.outprefix+"metabolites5.txt", "w")
     numspecies = 0
     for species in self.model.SPECIES.keys():
       if not species.endswith("_b"):
         metfile.write("%s\n" % (species))
         numspecies += 1
     numreactions = 0
     for reactions in self.model.REACTIONS.keys():
       if (not reactions.startswith("R_SRC")) and (not reactions.startswith("R_ESC")) and (not reactions.startswith("R_EXCH")):
         numreactions += 1
model.convertMet2KeggIDs() # get this to use the database                                                                                                        

model.addTransports()

# write .wil file                                                                                                                                    

model.writeWil(outprefix + "Working.wil")

###############                                                                                                                     
# build from .wil file                                                                                                               
###############                                                                                                                    

del model
model = SW_metmodel.gurobicb()
wilfname = outprefix + "Working.wil"
wil2metmodelpy.wil2metmodel(wilfname)
modelname = wilfname[0:(len(wilfname)-4)]
model.build_from_textfiles(modelfile=modelname + ".reactions", biomassfile=modelname + ".biomass", sourcesfile=modelname+".sources", escapesfile=modelname +".escapes",exchangesfile="")

# write .wil file with exchanges                                                                                                    
model.writeWil(outprefix + "Working.wil")
model.writeWil(outprefix + "Stable.wil")

#####################                                                                                                               
# add constraints   #                                                                                                                
#####################                                                                                                                
# reaction id, lower bound, upper bound                                                                                             

#model.set_constraint('R_SRC_C00185',10,10) 

model.solve(verbose=False, out=outprefix + "draft")
    def data_integration(self,gammas = (-0.1,0.1),exprfile = args.exp,forceBiomass = True, verbose = False):
        """
        Ruppin  analysis of syw using the datasets from Tetu et al., 2009 about phosphate stress.
        """
        gprfname = self.infile + '.gpr'
        #gap_Exchanges = "gapSRC_ESC.txt"
        def makeCallsDict( allRxns, hirxns, lorxns ):
            calls = {}
            for r in hirxns:
                assert r in allRxns and r not in lorxns
            for r in lorxns:
                assert r in allRxns and r not in hirxns
            for r in allRxns:
                if r in hirxns:
                    calls[r] = "On"
                elif r in lorxns:
                    calls[r] = "Off"
                else: 
                    calls[r] = "No call"
            for r in allRxns:
                assert not calls[r] == None
            return calls
        
        organism = raw_input("What is the organism's name in PubMed? ")
        self.model = mg.gurobicb()
        w2m.wil2metmodel(self.wilfname)
        #self.model.build_from_textfiles(modelfile=self.modelname + ".reactions", biomassfile=self.modelname + ".biomass", sourcesfile=self.modelname+".sources", escapesfile=self.modelname +".escapes", exchangesfile="", gapexfile=gap_Exchanges)
        self.model.build_from_textfiles(modelfile=self.modelname + ".reactions", biomassfile=self.modelname + ".biomass", sourcesfile=self.modelname+".sources", escapesfile=self.modelname +".escapes", exchangesfile="")
        if verbose:
            rq = False
        else:
            rq = True
        self.model.gpr2(gprfname,readquiet=rq)

        fluxes = {}
        calls = {}

        self.model.solve(verbose=verbose)
        fluxes['fba'] = deepcopy(self.model.REACTION2FLUXVALUE)

        self.model.ruppin(exprfile,gammas,forceBiomass=forceBiomass)
        #self.model.scoringExpData(exprfile)
        #self.model.webScrapping(organism)

        calls[self.outprefix] = makeCallsDict(self.model.REACTIONS,self.model.hirxnset,self.model.lowrxnset)
        fluxes[self.outprefix] = deepcopy(self.model.REACTION2FLUXVALUE)
        cache = {}
        for reaction in self.model.REACTIONS:
            name, reversible, notes, equation = self.model.REACTIONS[reaction]
            reactionequation = eq_current.makestring(equation, reversible)
            confidence,gpr = '?','?'
            holder = {'pathways':{}, 'ecs':{}}
            ref, prr = '.', '.'
            for note in notes:
                if 'SUBSYSTEM: ' in note:
                    holder['pathways'][note[11:]] = 1
                if 'EC: ' in note:
                    holder['ecs'][note[4:]] = 1
                if 'SCORES: ' in note:
                    print ("THIS IS THE SCORE", notes['SCORES: '])
                    Avg = notes['SCORES: '] + Avg
                    count += 1
                if 'CONFIDENCE: ' in note:
                    confidence = note[12:]
                if 'GPR: ' in note:
                    gpr = note[5:]
                if 'Protein_reaction_relation: ' in note:
                    prr = note[note.find(' == ') + 4:]
                if 'PMID: ' in note: # and not 'review' in note and not 'related_organism' in note 
                    ref = ref + note.split(',')[0][6:] + ' '
            if not ref == '.':
                ref = 'PMIDs: ' + ref[1:-1]

            grr = prr
            for i in prr.split():
                if '(' in i:
                    i = i[1:]
                if ')' in i:
                    i = i[:-1]
                if i in self.model.PROTEIN2GENE:
                    grr = grr.replace(i, model.PROTEIN2GENE[i])
                    
            #add to cache for printing...                                                                       
            for pathwayname in holder['pathways']:
                for ec in holder['ecs']:
                    if not pathwayname in cache:
                        cache[pathwayname] = {}
                    if not ec in cache[pathwayname]:
                        cache[pathwayname][ec] = {}

                    cache[pathwayname][ec][ ('\t').join((reaction, name, str(reversible), pathwayname, ec, fluxes['fba'][reaction], fluxes[self.outprefix][reaction], reactionequation)) ] = 1
        paths = cache.keys()
        paths.sort()
        outfile = open(self.outprefix+"integrated.xls","w")

        for path in paths:
            ecs = cache[path].keys()
            ecs.sort()
            for ec in ecs:
                for r in cache[path][ec]:
                    outfile.write("%s\n" % r)
                    
        #Average = float(Avg)/float(count)
        #print ('\n\n', "Average Score of Model: ", Avg, '\n')
        #print ("Average Score of Model per Gene: ", Average, '\n')
        self.model.writeECfile(self.outprefix + "ec3.txt")
        metfile = open(self.outprefix + "metabolites3.txt","w")
        numspecies = 0
        for species in self.model.SPECIES.keys():
            if not species.endswith("_b"):
                metfile.write("%s\n" % (species))
                numspecies += 1
        numreactions = 0
        for reactions in self.model.REACTIONS.keys():
            if (not reactions.startswith("R_SRC")) and (not reactions.startswith("R_ESC")) and (not reactions.startswith("R_EXCH")):
                numreactions += 1
        
        del self.model
        return numspecies,numreactions
        
        del self.model
    def fba_gap(self, verbose=False, withdb=False):
        self.model = mg.gurobicb()
        w2m.wil2metmodel(self.wilfname)
        gapSRC_ESC = open("gapSRC_ESC.txt", 'w')
        self.model.build_from_textfiles(modelfile=self.modelname + ".reactions", biomassfile=self.modelname + ".biomass", sourcesfile=self.modelname+".sources", escapesfile=self.modelname +".escapes", exchangesfile="")
        try:
            print ("Reading reactions to add")
            gapfile = open(self.outprefix + ".gap.xls", "r")
            reactionsToAdd = []
            source = 0
            escape = 0
            reaction = 0
            for line in gapfile.readlines():
                if "added sources:" in line:
                    source = 1
                    continue
                if "added escapes:" in line:
                    escape = 1
                    source = 0
                    continue
                if "added reactions:" in line:
                    reaction = 1
                    escape = 0
                    continue
                if reaction == 1:
                    reactionsToAdd.append(line.rstrip())
                if escape == 1:
                    escapeToAdd = line.rstrip()
                    gapSRC_ESC.write(escapeToAdd)
                    gapSRC_ESC.write("\n")
                    self.model.ESCAPES.append(escapeToAdd)
                if source == 1:
                    sourceToAdd = line.rstrip()
                    gapSRC_ESC.write(sourceToAdd)
                    gapSRC_ESC.write("\n")
                    self.model.SOURCES.append(sourceToAdd)
                self.model.addReactionsFromDB(reactionsToAdd)  
                self.model.set_sources(self.model.SOURCES)
                self.model.set_escapes(self.model.ESCAPES)
            gapfile.close()
        except:
            print ("No .gap.xls file")
        self.model.writeWil(filename=self.outprefix+"Working.wil")
        self.model.solve(verbose=verbose,out=self.outprefix + 'draft')
        if self.model.OBJECTIVE_VALUE < self.epsilon:
            print ("Flux was zero, gap filling")
            model2 = deepcopy(self.model)
            if withdb:
                model2.fbagapdb(out=self.outprefix)
            else:
                model2.fbagapnodb(out=self.outprefix)
        else:
            print ("Flux was positive")
            gapfile = open(self.outprefix + ".gap.xls", "w")
            gapfile.write("added sources:\nadded escapes:\nadded reactions:\n")
            gapfile.close()

        self.model.writeECfile(self.outprefix + "ec2.txt")
        metfile = open(self.outprefix + "metabolites2.txt","w")
        numspecies = 0
        for species in self.model.SPECIES.keys():
            if not species.endswith("_b"):
                metfile.write("%s\n" % (species))
                numspecies += 1
        numreactions = 0
        for reactions in self.model.REACTIONS.keys():
            if (not reactions.startswith("R_SRC")) and (not reactions.startswith("R_ESC")) and (not reactions.startswith("R_EXCH")):
                numreactions += 1
        
        del self.model
        return numspecies,numreactions