Natural Selection on Sickle Cell Anemia

    If anyone carries a pair of sickle betaglobin genes, they die of
    sickle cell anemia.

    Individuals with 1x betaglobin, 1x sickle betaglobin are immune to
    malaria.
350055
def install(
        engine,
        n_creatures=5,
        n_sickles=3,
        malaria_chance=.05,
        mate_chance=.05,
        mapsize=(1, 1),
        startpos=(0, 0)
):
    
    initmap = nx.grid_2d_graph(*mapsize)
    phys = engine.new_character("physical", data=initmap)
    species = engine.new_character(
        "species",
        mate_chance=mate_chance,
        malaria_chance=malaria_chance,
        n_creatures=n_creatures,
    )
    for n in range(0, n_creatures):
        name = "critter" + str(n)
        phys.add_thing(
            name=name,
            location=startpos,
            sickle_a=(n < n_sickles),
            sickle_b=False,
            male=engine.coinflip(),
            last_mate_turn=-1
        )
        assert name in phys.thing
        assert name not in phys.place
        assert name in phys.node, "couldn't add node {} to phys.node".format(name)
        assert hasattr(phys.node[name], 'location')
        species.add_avatar("physical", name)
        assert hasattr(species.avatar['physical'][name], 'location')

    # putting dieoff earlier in the code than mate means that dieoff will
    # be followed before mate is
    @species.avatar.rule
    def dieoff(critter):
        critter.delete()
        assert (critter.name not in critter.character.node)
        if critter['from_malaria']:
            return 'malaria'
        else:
            return 'anemia'

    @species.avatar.rule
    def mate(critter):
        """If I share my location with another critter, attempt to mate"""
        suitors = list(
            oc for oc in critter.location.contents()
            if oc['male'] != critter['male']
        )
        assert (len(suitors) > 0)
        other_critter = critter.engine.choice(suitors)
        sickles = [
            critter['sickle_a'],
            critter['sickle_b'],
            other_critter['sickle_a'],
            other_critter['sickle_b']
        ]
        engine.shuffle(sickles)
        name = "critter" + str(species.stat["n_creatures"])
        species.stat["n_creatures"] += 1
        engine.character["physical"].add_thing(
            name,
            critter["location"],
            sickle_a=sickles.pop(),
            sickle_b=sickles.pop(),
            male=engine.coinflip(),
            last_mate_turn=engine.turn
        )
        species.add_avatar("physical", name)
        critter['last_mate_turn'] = other_critter['last_mate_turn'] = \
            engine.turn
        return 'mated'

    @mate.prereq
    def once_per_turn(critter):
        return critter['last_mate_turn'] < critter.engine.turn

    @mate.prereq
    def mate_present(critter):
        for oc in critter.location.contents():
            if oc['male'] != critter['male']:
                return True
        return False

    @mate.trigger
    def in_the_mood(critter):
        return critter.engine.random() < critter.user.stat['mate_chance']

    @dieoff.trigger
    def sickle2(critter):
        r = critter['sickle_a'] and critter['sickle_b']
        if r:
            critter['from_malaria'] = False
        return r

    @dieoff.trigger
    def malaria(critter):
        r = (
                critter.engine.random() < critter.user.stat['malaria_chance'] and not
        (critter['sickle_a'] or critter['sickle_b'])
        )
        if r:
            critter['from_malaria'] = True
        return r

    # it would make more sense to keep using species.avatar.rule, this
    # is just a test
    @phys.thing.rule
    def wander(critter):
        dests = list(critter.character.place.keys())
        dests.remove(critter['location'])
        dest = critter.engine.choice(dests)
        critter.travel_to(dest)

    @wander.trigger
    def not_travelling(critter):
        return critter.next_location is None

    @wander.prereq
    def big_map(critter):
        return len(critter.character.place) > 1
921205
def get_ccle_mutations():
    
    if request.method == 'OPTIONS':
        return {}
    response = request.body.read().decode('utf-8')
    body = json.loads(response)
    gene_list = body.get('gene_list')
    cell_lines = body.get('cell_lines')
    mutations = cbio_client.get_ccle_mutations(gene_list, cell_lines)
    res = {'mutations': mutations}
    return res
569219
def fetch(self, is_dl_forced=False):
        
        self.get_files(is_dl_forced)

        ncbi = NCBIGene(self.graph_type, self.are_bnodes_skized)
        # ncbi.fetch()
        gene_group = ncbi.files['gene_group']
        self.fetch_from_url(
            gene_group['url'], '/'.join((ncbi.rawdir, gene_group['file'])), False)

        # load and tag a list of OMIM IDs with types
        # side effect of populating omim replaced
        self.omim_type = self.find_omim_type()

        return
538324
private static double pGenotype(Genotype g, double refProb) {
    switch(g) {
      case REF_HOMOZYGOUS:
        return refProb * refProb;
      case HETEROZYGOUS:
        return refProb * (1.0 - refProb);
      case NONREF_HOMOZYGOUS:
        return (1.0 - refProb) * (1.0 - refProb);
      default:
        throw new IllegalArgumentException("Illegal genotype");
    }
  }
14146
def getNbVariants(self, x1, x2 = -1) :
		""""""
		if x2 == -1 :
			xx2 = len(self.defaultSequence)
		else :
			xx2 = x2
		
		nbP = 1
		for p in self.polymorphisms:
			if x1 <= p[0] and p[0] <= xx2 :
				nbP *= len(p[1])
		
		return nbP
1312076
def gene_ids(self):
        
        return self.ensembl.gene_ids_at_locus(
            self.contig, self.start, self.end)
1080987
def _genotype_in_background(rec, base_name, back_samples):
    
    def passes(rec):
        return not rec.FILTER or len(rec.FILTER) == 0
    return (passes(rec) and
            any(rec.genotype(base_name).gt_alleles == rec.genotype(back_name).gt_alleles
                for back_name in back_samples))
1052606
def matches_truth(call_alleles, truth_alleles, data):
    
    if not truth_alleles:
        return ""
    else:
        def _remove_p(x):
            return x[:-1] if x.endswith("P") else x
        t_cmp = set([_remove_p(hla_groups.hla_protein(x, data)) for x in truth_alleles])
        c_cmp = set([_remove_p(hla_groups.hla_protein(x, data)) for x in call_alleles])
        return "yes" if len(t_cmp.intersection(c_cmp)) == len(t_cmp) else "no"
683988
def gffatributes2ids(s):
    
    Name,gene_id,transcript_id,protein_id,exon_id=np.nan,np.nan,np.nan,np.nan,np.nan
    if '=' in s:
        d=dict([i.split('=') for i in s.split(';')])
        if 'Parent' in d:
            d[d['Parent'].split(':')[0]+'_id']=d['Parent'].split(':')[1]
        Name,gene_id,transcript_id,protein_id,exon_id=np.nan,np.nan,np.nan,np.nan,np.nan
        if 'Name' in d:    
            Name=d['Name']
        if 'gene_id' in d:    
            gene_id=d['gene_id']
        if 'transcript_id' in d:    
            transcript_id=d['transcript_id']
        if 'protein_id' in d:    
            protein_id=d['protein_id']
        if 'exon_id' in d:    
            exon_id=d['exon_id']
    return Name,gene_id,transcript_id,protein_id,exon_id
819512
def supported_alleles(self):
        
        if 'supported_alleles' not in self._cache:
            result = set(self.allele_to_allele_specific_models)
            if self.allele_to_fixed_length_sequence:
                result = result.union(self.allele_to_fixed_length_sequence)
            self._cache["supported_alleles"] = sorted(result)
        return self._cache["supported_alleles"]
148223
def _get_other_allele_by_zygosity(allele_id, zygosity):
        
        other_allele = None
        if zygosity == 'homozygous':
            other_allele = allele_id
        elif zygosity == 'hemizygous':
            other_allele = '0'
        elif zygosity == 'unknown':  # we'll use this as a convention
            other_allele = '?'
        elif zygosity == 'complex':  # transgenics
            other_allele = '0'
        elif zygosity == 'heterozygous':
            # passing on hets until a different fxn
            pass
        else:
            LOG.warning("Unconfigured zygosity: %s", zygosity)

        return other_allele
83840
def complement_alleles(self):
        
        self.alleles = self._encode_alleles(
            [complement_alleles(i) for i in self.alleles]
        )
176579
def gene_ids_of_gene_name(self, gene_name):
        
        results = self._query_gene_ids("gene_name", gene_name)
        if len(results) == 0:
            raise ValueError("Gene name not found: %s" % gene_name)
        return results
478395
def _compatible_small_variants(data, items):
    
    from bcbio import heterogeneity
    VarFile = collections.namedtuple("VarFile", ["name", "sample", "normal"])
    out = []
    paired = vcfutils.get_paired(items)
    for v in heterogeneity.get_variants(data, include_germline=not paired):
        vrn_file = v["vrn_file"]
        base, ext = utils.splitext_plus(os.path.basename(vrn_file))
        if paired:
            out.append(VarFile(vrn_file, paired.tumor_name, paired.normal_name))
        else:
            out.append(VarFile(vrn_file, dd.get_sample_name(data), None))
    return out
535025
def mutation(self,strength = 0.1):
		'''
		
		'''
		# Mutation du gene - real
		mutStrengthReal = strength
		mutMaxSizeReal = self.gLength/2
		mutSizeReal = int(numpy.random.random_integers(1,mutMaxSizeReal))
		mutationPosReal = int(numpy.random.random_integers(0+mutSizeReal-1,self.y.shape[0]-1-mutSizeReal))
		mutationSignReal = pl.rand()
		mutationReal = pl.rand()

		# Mutation du gene - imag
		mutStrengthImag = strength
		mutMaxSizeImag = self.gLength/2
		mutSizeImag = int(numpy.random.random_integers(1,mutMaxSizeImag))
		mutationPosImag = int(numpy.random.random_integers(0+mutSizeImag-1,self.y.shape[0]-1-mutSizeImag))
		mutationSignImag = pl.rand()
		mutationImag = pl.rand()

		if mutationSignReal > 0.5:
			for i in range(-mutSizeReal/2, mutSizeReal/2):
				self.y.real[mutationPosReal+i] = self.y.real[mutationPosReal+i] + mutStrengthReal*self.y.real[mutationPosReal+i]*mutationReal
		else:
			for i in range(-mutSizeReal/2, mutSizeReal/2):
				self.y.real[mutationPosReal+i] = self.y.real[mutationPosReal+i] - mutStrengthReal*self.y.real[mutationPosReal+i]*mutationReal

		if mutationSignImag > 0.5:
			for i in range(-mutSizeImag/2, mutSizeImag/2):
				self.y.imag[mutationPosImag+i] = self.y.imag[mutationPosImag+i] + mutStrengthImag*self.y.imag[mutationPosImag+i]*mutationImag
		else:
			for i in range(-mutSizeImag/2, mutSizeImag/2):
				self.y.imag[mutationPosImag+i] = self.y.imag[mutationPosImag+i] - mutStrengthImag*self.y.imag[mutationPosImag+i]*mutationImag

		# Compute the individual
		self.birth()
1067776
def nr_genes(self):
        """"""
        if self['genes']:
            nr_genes = len(self['genes'])
        else:
            nr_genes = len(self['gene_symbols'])
        return nr_genes
1257589
def get_gene2section2gos(gene2gos, sec2gos):
        """"""
        gene2section2gos = {}
        for geneid, gos_gene in gene2gos.items():
            section2gos = {}
            for section_name, gos_sec in sec2gos.items():
                gos_secgene = gos_gene.intersection(gos_sec)
                if gos_secgene:
                    section2gos[section_name] = gos_secgene
            gene2section2gos[geneid] = section2gos
        return gene2section2gos