Пример #1
0
def getCar():
	car = []
	car.append( gene(0) )
	car.append( gene(0) )
	car.append( gene(0) )
	car.append( gene(0) )
	car.append( gene(0) )
	return car
Пример #2
0
    def calculate_ssConc_(self):
        """
        This function calculates the steady state concentrations of both unspliced and spliced RNA in the given bin (cell type).
        Note that this steady state concentration will be used to initilize U and S concentration of this bin (if it's a master bin) and its children (if any)

        Half responses are also computed here by calling its function.
        """
        for level in range(self.maxLevels_, -1, -1):
            for binID in range(self.nBins_):
                currGenes = self.level2verts_[level]

                for g in currGenes:
                    if g[0].Type == 'MR':
                        currRate = self.graph_[g[0].ID]['rates'][binID]
                        self.binDict[binID][g[0].ID] = gene(
                            g[0].ID, 'MR', binID)
                        self.binDict[binID][g[0].ID].set_ss_conc_U(
                            np.true_divide(currRate,
                                           self.decayVector_[g[0].ID]))
                        self.binDict[binID][g[0].ID].set_ss_conc_S(
                            self.ratioSp_[g[0].ID] * np.true_divide(
                                currRate, self.decayVector_[g[0].ID]))
                    else:
                        params = self.graph_[g[0].ID]['params']
                        currRate = 0
                        for interTuple in params:
                            meanExp = self.meanExpression[interTuple[0], binID]
                            currRate += np.abs(interTuple[1]) * self.hill_(
                                meanExp, interTuple[3], interTuple[2],
                                interTuple[1] < 0)
                            #if binID == 0 and g[0].ID == 0:
                            #print meanExp
                            #print interTuple[3]
                            #print interTuple[2]
                            #print interTuple[1]
                            #print self.hill_(meanExp, interTuple[3], interTuple[2], interTuple[1] < 0)

                        self.binDict[binID][g[0].ID] = gene(
                            g[0].ID, 'T', binID)
                        self.binDict[binID][g[0].ID].set_ss_conc_U(
                            np.true_divide(currRate,
                                           self.decayVector_[g[0].ID]))
                        self.binDict[binID][g[0].ID].set_ss_conc_S(
                            self.ratioSp_[g[0].ID] * np.true_divide(
                                currRate, self.decayVector_[g[0].ID]))
                    # NOTE This is our assumption for dynamics simulations --> we estimate mean expression of g in b with steady state concentration of U_g in b
                    self.meanExpression[g[0].ID, binID] = self.binDict[binID][
                        g[0].ID].ss_U_
                    #if binID == 0 and g[0].ID == 0:
                    #    print currRate
                    #    print self.decayVector_[g[0].ID]
            if level > 0:
                self.calculate_half_response_(level - 1)
Пример #3
0
    def find_levels_(self, graph):
        """
        # This is a helper function that takes a graph and assigns layer to all
        # verticies. It uses longest path layering algorithm from
        # Hierarchical Graph Drawing by Healy and Nikolovself. A bottom-up
        # approach is implemented to optimize simulator run-time. Layer zero is
        # the last layer for which expression are simulated
        # U: verticies with an assigned layer
        # Z: vertizies assigned to a layer below the current layer
        # V: set of all verticies (genes)

        This also sets a dictionary that maps a level to a matrix (in form of python list)
        of all genes in that level versus all bins
        """

        U = set()
        Z = set()
        V = set(graph.keys())

        currLayer = 0
        self.level2verts_[currLayer] = []
        idx = 0

        while U != V:
            currVerts = set(
                filter(lambda v: set(graph[v]['targets']).issubset(Z), V - U))

            for v in currVerts:
                graph[v]['level'] = currLayer
                U.add(v)
                if {v}.issubset(self.master_regulators_idx_):
                    allBinList = [gene(v, 'MR', i) for i in range(self.nBins_)]
                    self.level2verts_[currLayer].append(allBinList)
                    self.gID_to_level_and_idx[v] = (currLayer, idx)
                    idx += 1
                else:
                    allBinList = [gene(v, 'T', i) for i in range(self.nBins_)]
                    self.level2verts_[currLayer].append(allBinList)
                    self.gID_to_level_and_idx[v] = (currLayer, idx)
                    idx += 1

            currLayer += 1
            Z = Z.union(U)
            self.level2verts_[currLayer] = []
            idx = 0

        self.level2verts_.pop(currLayer)
        self.maxLevels_ = currLayer - 1

        if not self.dyn_:
            self.set_scIndices_()
Пример #4
0
    def openGoalFile(self, filename=None, normalize=True):
##        test=tkFileDialog
##        print(test)
##        print(type(test))
##        print(dir(test))
##        filename=test.askopenfilename()
        # might want to replace it with:
        # http://stackoverflow.com/questions/9319317/quick-and-easy-file-dialog-in-python


        if filename==None:
            # get the file name using a file dialog!
##            t=Tk()
##            t.withdraw()
            filename=tkFileDialog.askopenfilename()
            print(filename)
##            t.quit()

        self.goalGene=gene()
        self.goalGene.normalized=normalize
        self.goalGene.load(filename)

        self.absoluteTruth=self.goalGene.solveODE()
        self.goalGene.absoluteTruth=self.absoluteTruth

        if self.analysableVariables==[]:
            self.analysableVariables=scipy.array(range(len(self.goalGene.getVariableList())))
Пример #5
0
from config import *
from population import population
from chromosome import chromosome
from gene import gene

circle = [(39, 0),(51, 58), (30, 58), (10, 25), (69, 24), (20, 7), (66, 44),(59, 7),(14, 46)]
random_points = [(73, -94), (25, 73),(-98, 22),(-50, -43),(16, 46),(16, 13),(-27, -71),(-13, -23),(58, -81),(-75, 43),(95, -86),(-43, -70),(44, 45), (-19, -94),(-37, 45),(-59, 12),(33, -26),(-58, 85),(92, -97)]
random_points_2 = [(49, 19),(87, -69),(29, 45),(-50, 56),(-66, -33),(22, -33),(27, -72),(82, 61),(97, 33),(58, 18),(-9, -19),(50, 58),(-38, 67),(98, 3)]

if __name__ == '__main__':
# input is x PUT YOUR INPUT HERE
    x = circle
    #plotting initial 
    starting_population = population(x)
    starting_chromosome = chromosome([starting_population])
    starting_distance = starting_population._totaldistance()
    starting_chromosome._plot_chromosome_tour()
    
    #Applying Genetic Algorithm
    g = gene(x)
    
    #plotting best
    final_best_population = g.overall_best
    final_best_chromosome = chromosome([final_best_population])
    final_best_distance = final_best_population._totaldistance()
    final_best_chromosome._plot_chromosome_tour()
    print('================== Results of Optimization ============================')
    print('Initial Distance : ', starting_distance)
    print('Optimized final Distance :', final_best_distance)
    print(((starting_distance - final_best_distance)*100/starting_distance),'% distance reduced')
    plt.show()

    print('------------------Settings-------------------')
    print('dirName : '+dirName)
    print('originalGeneFile : '+originalGeneFile)
    print('doLocalOptimize : '+str(doLocalOptimize))
    print('uniqueNumer : '+str(uniqueNumber))
    print('---------------------------------------------')


##    # get the command line parameters
##    dirname=sys.argv[0]
##    originalGeneFile=sys.argv[1]


    originalGene=gene()
    originalGene.load(originalGeneFile)
    goal=originalGene.solveODE()
    originalGene.absoluteTruth=goal


    # test fitness condition
    if originalGene.fitness() != 0:
        raise Exception('ERROR! this gene cannot predict its own ideal!!')

    # create the new dir
    import os
##    os.mkdir(dirName) # didnt work

    try:
        os.makedirs(dirName) # so lets try
Пример #7
0
#variable used to assign gene start and finish points
placeholder=0
#current gene name, used for transitioning between genes
CG=""
#reassign argv to not include 1st item (doesn't work for regex)
sys.argv=sys.argv[1:]
geneCount=0
for arg in sys.argv:
	#search file name for tree metadata
	#gene is group 1, run is group 2
	searchTerm="Alltaxa_(\w+)_r(\d)"
	regexobj=re.search(searchTerm,arg)
	#if the file doesn't match the current gene, make a new one and add it to genelist
	if regexobj.group(1) != CG:
		treelist.read_from_path(arg,'nexus')
		genelist.append(gene.gene(regexobj.group(1),placeholder,len(treelist)-1))
		geneCount+=1
	#if the next file is still the same gene, then extend finish on the gene
	else:
		genelist[-1].setFinish(len(treelist)-1)
		treelist.read_from_path(arg,'nexus')
		
	#assign metadata to the trees added from the current file specified in argv
	x=0
	for tree in treelist[placeholder:]:
		tree.name=regexobj.group(1)+"tree_"+str(x)
		x+=1
		tree.gene=regexobj.group(1)
		tree.geneNum=geneCount
		tree.run=regexobj.group(2)
		tree.freqCount=1
Пример #8
0
import gene
from datetime import timedelta


class population(GA_population.GA_population):
    """ implementation of GA_population

        todo: reload old population

    """
    def __init__(self):
        pass


if __name__ == '__main__':
    testgene = gene.gene()
    testgene.load(
        filename=
        'E:\\Documents\\Stage\\python\\models\\3geneWithVarProduction.model')
    testgene.absoluteTruth = testgene.solveODE()  #fill it with and objective
    print(testgene.fitness())  #should return perfect fitness!

    test = population()
    test.seed(testgene)
    test.maxTime = timedelta(minutes=5)
    test.maxGenerations = 100
    test.evolve()

    test.population[0].displayResults()

    filename2 = 'E:\\Documents\\Stage\\python\\models\\testmodel.model'
Пример #9
0
    simulator.initX()
    print simulator.run(1000)
    #print simulator.bookLimRun(100,opt.X)

elif first == 0:#reduction of Approximate Linear Programming
    
    reduction = rALP.rALP(demander.reader)
    reduction.construct()
    reduction.addVar()
    reduction.addOpt()
    reduction.addConstr()
    reduction.solve()

elif first == 2:#Gene Algorithm
    
    decisionSolver = decisionRule.decisionRule()
    decisionSolver.inputDemand(demander)    
    decisionSolver.x = {}
    simulator = simulation.simulation(decisionSolver,demander)

    realDemand = {}
    for i in range(0,100):
        realDemand[i] = demander.sim()

    opt = gene.gene(decisionSolver,simulator)
    opt.zeroX()
    opt.setSTD(realDemand)
    opt.evolve()
    #simulator.run(1000)
    print simulator.bookLimRun(100,opt.X)
Пример #10
0

    print('------------------Settings-------------------')
    print('dirName : '+dirName)
    print('originalGeneFile : '+originalGeneFile)
    print('doLocalOptimize : '+str(doLocalOptimize))
    print('uniqueNumer : '+str(uniqueNumber))
    print('---------------------------------------------')


##    # get the command line parameters
##    dirname=sys.argv[0]
##    originalGeneFile=sys.argv[1]


    originalGene=gene()
    originalGene.load(originalGeneFile)
    goal=originalGene.solveODE()
    originalGene.absoluteTruth=goal


    # test fitness condition
    if originalGene.fitness() != 0:
        raise Exception('ERROR! this gene cannot predict its own ideal!!')

    # create the new dir
    import os
##    os.mkdir(dirName) # didnt work

    try:
        os.makedirs(dirName) # so lets try
Пример #11
0
class population(GA_population.GA_population):
    """ implementation of GA_population

        todo: reload old population

    """



    def __init__(self):
        pass



if __name__ == '__main__':
    testgene=gene.gene()
    testgene.load(filename='E:\\Documents\\Stage\\python\\models\\3geneWithVarProduction.model')
    testgene.absoluteTruth=testgene.solveODE()#fill it with and objective
    print(testgene.fitness())#should return perfect fitness!


    test=population()
    test.seed(testgene)
    test.maxTime=timedelta(minutes=5)
    test.maxGenerations=100
    test.evolve()

    test.population[0].displayResults()

    filename2='E:\\Documents\\Stage\\python\\models\\testmodel.model'
    test.population[0].save(filename2)
    # wenn die anfangspopulation noch nicht fertig berechnet war:
    gene.berechneFitness(population, epochen)

    # dann die höchste generation holen, das +1 ist die durchlaufnummer.
    durchlaufNr = 1
    nextID = 0

    for element in population:
        if element.generation > durchlaufNr:
            durchlaufNr = element.generation
        if element.id > nextID:
            nextID = element.id

    nextID = durchlaufNr + num_population - 1
    for i in range(0, nextID):
        temp = gene.gene()

# Evolution
while (durchlaufNr <= anzahlDurchlaeufe):
    sel1, sel2 = gene.selektiereEltern(population)
    neuerKandidat = gene.rekombination(sel1, sel2, durchlaufNr)
    neuerKandidat = gene.mutation(neuerKandidat)

    # neues Individuum trainieren
    model_neu = Modelbuilder(neuerKandidat)
    model_neu.add_GenCode_To_Model()
    myFitness = model_neu.finalize_Model(epochen)

    # dann Fitness ermitteln
    gene.berechneFitnessEinzel(neuerKandidat, myFitness)
Пример #13
0
    def openFiles(self,filePaths=None):
        """ open files and adds them to the population, can be called multiple times...."""
        if self.absoluteTruth==None:
            raise Exception('first load original gene!!')

        if filePaths==None:
##            t=Tk()
##            t.withdraw()
            filePaths=tkFileDialog.askopenfilenames().split()
            print(filePaths)
##            t.quit()

##        print(type(filePaths))
##        print(filePaths)


        mi=self.goalGene.minParRangeList
        ma=self.goalGene.maxParRangeList

        nrOfMistFits=0


        for i in range(len(filePaths)):
            print('reading file '+str(i+1)+' of '+str(len(filePaths)))
            filename=filePaths[i]

            aGene=gene()
            aGene.normalized=self.goalGene.normalized
            aGene.load(filename)
            aGene.absoluteTruth=self.absoluteTruth


            # check if the individual is within the constraints

##            variables=aGene.getVariableList()
##            for i in range(len(mi)):
##                if variables[i]>ma[i] or variables[i]<mi[i]: # if out of bounds
##                    # put that individual in the trash bin
##                    self.misfits.append(aGene)
##            else:
##                aGene.fitness()
##                self.population.append(aGene)

##        print('nr of corrupted individuals:'+str(len(self.misfits)))
            isMisfit=False
            params=aGene.getVariableList()
            for i in range(len(mi)):
                # make sure it stays withing model constraints/bounds
                if params[i] < mi[i]:
                    print('correcting parameter from:' +str(params[i]) + ' to: '+ str(mi[i]))
                    params[i]=mi[i]
                    isMisfit=True

                if params[i] > ma[i]:
                    print('correcting parameter from:' +str(params[i]) + ' to: '+ str(ma[i]))
                    params[i]=ma[i]
                    isMisfit=True
            if isMisfit:
                nrOfMistFits+=1
            aGene.setVariableList(params)

            aGene.fitness()
            self.population.append(aGene)

        print('nr of corrupted individuals:'+str(nrOfMistFits))

        # sort it!
        self.sort()