Ejemplo n.º 1
0
class View(QtGui.QWidget):
    def __init__(self, bodySize):
        super(View, self).__init__()
        self.phenotype = Phenotype(bodySize)
        self.initUI()

    def initUI(self):
        self.setGeometry(200, 200, WIDTH, HEIGHT)
        self.setWindowTitle('Organism')
        self.show()

    def paintEvent(self, e):
        qp = QtGui.QPainter()
        qp.begin(self)
        self.drawMatrix(qp)
        qp.end()

    def drawMatrix(self, qp):
        rgbColors = self.chooseColors()

        horizBoxSide = WIDTH // self.phenotype.size
        vertBoxSide = HEIGHT // self.phenotype.size

        boxSide = min(horizBoxSide, vertBoxSide)

        color = QtGui.QColor(0, 0, 0)
        qp.setPen(color)

        for col in range(self.phenotype.size):
            for row in range(self.phenotype.size):
                color = rgbColors[self.phenotype.body[col][row]]
                qp.setBrush(QtGui.QColor(color[0], color[1], color[2]))
                qp.drawRect(row * boxSide, col * boxSide, boxSide, boxSide)

    def chooseColors(self):
        rgbColors = []
        colorsNo = self.phenotype.GetConnectedComponentsNo()

        rgbColors.append((255, 255, 255))

        for i in range(1, colorsNo + 1):
            r = random.randint(0, 255)
            g = random.randint(0, 255)
            b = random.randint(0, 255)
            rgbColors.append((r, g, b))

        return rgbColors

    def UpdateData(self, genotype):
        self.phenotype.UseGenotype(genotype)
        self.update()
Ejemplo n.º 2
0
 def __init__(self, name, chromosomes):
     self.name = name
     self.chromosomes = chromosomes
     
     self.phenotype = Phenotype(self)
     self.parents = []
     self.children = []
Ejemplo n.º 3
0
    def ChooseBestIndividal(self):
        phenotype = Phenotype(self.bodySize)
        indexBest = -1
        adaptationBest = 0.0

        for i in range(self.muValue):
            phenotype.UseGenotype(self.population[i])
            if phenotype.GetAdaptation() > adaptationBest:
                indexBest = i
                adaptationBest = phenotype.GetAdaptation()

        self.lastAdaptationValue = self.currentAdaptationValue
        self.currentAdaptationValue = adaptationBest
        print("#" + str(self.lastAdaptationValuesBelowDelta) +
              "\tCurrent best: " + str(adaptationBest))

        self.view.UpdateData(self.population[indexBest])
Ejemplo n.º 4
0
    def CreateRouletteWheel(self, individualsToChoose):
        sum = 0.0

        adaptationValue = []

        for i in range(len(individualsToChoose)):
            phenotype = Phenotype(self.bodySize)
            phenotype.UseGenotype(individualsToChoose[i])
            adaptation = phenotype.GetAdaptation()

            adaptationValue.append(math.exp(adaptation))
            sum += math.exp(adaptation)

        rouletteWheel = []
        for i in range(len(individualsToChoose)):
            rouletteWheel.append(adaptationValue[i] / sum)

        for i in range(1, len(individualsToChoose)):
            rouletteWheel[i] += rouletteWheel[i - 1]

        return rouletteWheel
Ejemplo n.º 5
0
 def __init__(self, bodySize):
     super(View, self).__init__()
     self.phenotype = Phenotype(bodySize)
     self.initUI()
Ejemplo n.º 6
0
class Being:
    """
    Represent a being
    Can be human or else
    
    @args:
        name: string, being name
        chromosomes: 
    
    """
    
    def __init__(self, name, chromosomes):
        self.name = name
        self.chromosomes = chromosomes
        
        self.phenotype = Phenotype(self)
        self.parents = []
        self.children = []


    def getName(self):
        return self.name
        
    
    def getChildren(self):
        return self.children
        
        
    def getParents(self):
        return self.parents
        
        
    def getPhenotype(self):
        return self.phenotype
        
        
    def addParent(self, being):
        self.parents.append(being)
        
    
    def addChild(self, being):
        self.children.append(being)

    
    def removeChild(self, being):
        self.children.remove(being)
        
    
    def removeParent(self, being):
        self.children.remove(being)
            
            
    def getChromosomes(self):
        return self.chromosomes
        

    def addChromosome(self, chromosome):
        self.chromosomes.append(chromosome)
        
        
    def removeChromosome(self, chromosome):
        self.chromosomes.remove(chromosome)


    def getChromosomesByNames(self):
        chromosomesByNames = {}
        
        for chromosome in self.getChromosomes():

            if chromosome.getName() in chromosomesByNames:
                chromosomesByNames[chromosome.getName()].append(chromosome)
            else:
                #Python implicitely creates a key whenever you declare a property on a key that doesn't exist
                chromosomesByNames[chromosome.getName()] = [chromosome] 
                
        return chromosomesByNames
    

    def getChromosomesNameSet(self):
        return set(self.getChromosomesByNames().keys())


    def getSpecie(self):
        return self.phenotype.getSpecie()
        
        
    def isDescendant(self, being, maxDepth = 10, excludedBeings = []):
        if self == being:
            raise Exception("isDescendant cannot be called with self as argument")

        if being in self.parents:
            return True
            
        if not self.parents or not maxDepth:
            return False
        
        cleanedParents = [parent for parent in self.parents if not parent in excludedBeings]
        
        if not cleanedParents:
            return False
        
        return any([parent.isDescendant(being = being, maxDepth = maxDepth - 1, excludedBeings = excludedBeings + [self]) for parent in cleanedParents])
            

    def isAncestor(self, being, maxDepth = 10, excludedBeings = []):
        if self == being:
            raise Exception("isAncestor cannot be called with self as argument")
    
        if being in self.children:
            return True
            
        if not self.children or not maxDepth:
            return False
            
        cleanedChildren = [child for child in self.children if not child in excludedBeings]
        
        if not cleanedChildren:
            return False
        
        return any([child.isAncestor(being = being, maxDepth = maxDepth - 1, excludedBeings = excludedBeings + [self]) for child in cleanedChildren])
    
    
    def isConsanguineous(self, being, maxDepth = 10, excludedBeings = [], firstCall = True):
        if self == being:
            if firstCall:
                raise Exception("isConsanguineous cannot be called with self as argument")
            else:
                return True

        if self.isAncestor(being = being, maxDepth = maxDepth, excludedBeings = excludedBeings):
            return True    
        
        if not self.parents or not maxDepth:
            return False
            
        cleanedParents = [parent for parent in self.parents if not parent in excludedBeings]
        
        if not cleanedParents:
            return False
        
        return any([parent.isConsanguineous(being = being, maxDepth = maxDepth - 1, excludedBeings = excludedBeings + [self], firstCall = False) for parent in cleanedParents])
    
    
    def isInbred(self):
        return any([self.parents[0].isConsanguineous(otherParent) for otherParent in self.parents if not otherParent == self.parents[0]])


    def getGender(self):
        return Phenotype(self).getGender()


    def mate(self, being, name):
        child = Being(name, [])

        # Declaration of sets of chromosomes for each being
        intersectionSet = self.getChromosomesNameSet().intersection(being.getChromosomesNameSet())
        selfUniqueSet = self.getChromosomesNameSet().difference(being.getChromosomesNameSet())
        beingUniqueSet = being.getChromosomesNameSet().difference(self.getChromosomesNameSet())

        for chromosomeName in intersectionSet:

            for individual in [self, being]:
                chromosomes = individual.getChromosomesByNames()[chromosomeName]
                chromosomesMean = len(chromosomes) / 2

                #selectionSize is the number of chromosomes each parent is giving to his child for a certain chromosome type. It is used to create trisomic children
                if (chromosomesMean % 2 == 0):
                    selectionSize = int(chromosomesMean)

                else:
                    selectionSize = random.choice([int(chromosomesMean), int(chromosomesMean) + 1])

                #Randomly choose a certain number of chromosomes (number = selectionSize)
                for chromosome in random.sample(chromosomes, selectionSize):
                    child.addChromosome(chromosome)

        for individual, individualUniqueSet in [(self, selfUniqueSet), (being, selfUniqueSet)]:

            for chromosomeName in individualUniqueSet:
                chromosomes = individual.getChromosomesByNames()[chromosomeName]

                for chromosome in chromosomes:
                    child.addChromosome(chromosome)
                    
        self.addChild(child)
        being.addChild(child)
        
        child.addParent(self)
        child.addParent(being)
    
        return child
Ejemplo n.º 7
0
    def get_phenotypes(self,
                       gene,
                       diplotypes,
                       sample_variants,
                       uncallable,
                       extra_variants=None):
        g = gene.name

        # Load phenotype file into object
        phenotypes = Phenotype()

        results = []

        for sample, diplotype in diplotypes.items():
            haps = split_genotype(diplotype)
            haplotype_data = {}
            for i in range(len(haps)):
                h = haps[i]
                h_function = phenotypes.get_haplotype_function(g, h)
                h_presumptive = phenotypes.get_presumptive_haplotype_function(
                    g, h)

                haplotype_data["hap_%s" % i] = h
                haplotype_data["hap_%s_function" % i] = h_function
                haplotype_data["hap_%s_presumptive" % i] = h_presumptive

            phenotype = phenotypes.get_diplotype_function(g, haps[0], haps[1])
            presumptive_phenotype = phenotypes.get_diplotype_function(
                g, haps[0], haps[1], presumptive=True)
            activity_score = phenotypes.get_activity_score(g,
                                                           haps[0],
                                                           haps[1],
                                                           presumptive=True)
            #if phenotype != presumptive_phenotype:
            #    print(phenotype, presumptive_phenotype)
            #    exit()

            results.append({
                "sample":
                sample,
                "gene":
                g,
                "diplotype":
                diplotype,
                "hap_1":
                haplotype_data["hap_0"],
                "hap_2":
                haplotype_data["hap_1"],
                "hap_1_function":
                haplotype_data["hap_0_function"],
                "hap_2_function":
                haplotype_data["hap_1_function"],
                "hap_1_presumptive_function":
                haplotype_data["hap_0_presumptive"],
                "hap_2_presumptive_function":
                haplotype_data["hap_1_presumptive"],
                "hap_1_variants":
                sample_variants[sample][0],
                "hap_2_variants":
                sample_variants[sample][1],
                "phenotype":
                phenotype,
                "phenotype_presumptive":
                presumptive_phenotype,
                "activity_score":
                activity_score,
                "uncallable":
                ";".join(x.split("%")[0] for x in uncallable[sample]),
                "extra_variants":
                None if extra_variants is None else ";".join(
                    x.split("%")[0] for x in extra_variants[sample])
            })

        return results