Get CCLE CNA
    -2 = homozygous deletion
    -1 = hemizygous deletion
     0 = neutral / no change
     1 = gain
     2 = high level amplification
505095
def get_ccle_cna():
    
    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')
    cna = cbio_client.get_ccle_cna(gene_list, cell_lines)
    res = {'cna': cna}
    return res
1163375
def make_vslc_label(self, gene_label, allele1_label, allele2_label):
        

        vslc_label = ''

        if gene_label is None and allele1_label is None and allele2_label is None:
            LOG.error("Not enough info to make vslc label")
            return None

        top = self.make_variant_locus_label(gene_label, allele1_label)
        bottom = ''
        if allele2_label is not None:
            bottom = self.make_variant_locus_label(gene_label, allele2_label)

        vslc_label = '/'.join((top, bottom))

        return vslc_label
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"]
475557
def get_gene_info(ensembl_ids=None, hgnc_symbols=None):
    
    uniq_ensembl_ids = set(ensembl_id for ensembl_id in (ensembl_ids or []))
    uniq_hgnc_symbols = set(hgnc_symbol for hgnc_symbol in (hgnc_symbols or []))
    genes = []
    gene_data = []
    
    if uniq_ensembl_ids:
        for ensembl_id in uniq_ensembl_ids:
            for res in query_gene(ensembl_id=ensembl_id):
                gene_data.append(res) 

    elif uniq_hgnc_symbols:
        for hgnc_symbol in uniq_hgnc_symbols:
            query_res = query_gene(hgnc_symbol=hgnc_symbol)
            if query_res:
                for res in query_res:
                    gene_data.append(res)
            else:
                # If no result we add just the symbol
                gene_data.append({
                    'hgnc_symbol': hgnc_symbol,
                    'hgnc_id': None,
                    'ensembl_id': None,
                    'description': None,
                    'chrom': 'unknown',
                    'start': 0,
                    'stop': 0,
                    'hi_score': None,
                    'constraint_score': None,
                })
    for gene in gene_data:
        genes.append(Gene(
            symbol=gene ['hgnc_symbol'],
            hgnc_id=gene['hgnc_id'],
            ensembl_id=gene['ensembl_id'],
            description=gene['description'],
            chrom=gene['chrom'],
            start=gene['start'],
            stop=gene['stop'],
            location=get_cytoband_coord(gene['chrom'], gene['start']),
            hi_score=gene['hi_score'],
            constraint_score=gene['constraint_score'],
            omim_number=get_omim_number(gene['hgnc_symbol'])
            ))

    return genes
782760
def format_info(variant, variant_type='snv'):
    
    
    observations = variant.get('observations',0)

    homozygotes = variant.get('homozygote')
    hemizygotes = variant.get('hemizygote')

    
    vcf_info = f"Obs={observations}"
    if homozygotes:
        vcf_info += f";Hom={homozygotes}"
    if hemizygotes:
        vcf_info += f";Hem={hemizygotes}"

    # This is SV specific
    if variant_type == 'sv':
        end = int((variant['end_left'] + variant['end_right'])/2)
        
        vcf_info += f";SVTYPE={variant['sv_type']};END={end};SVLEN={variant['length']}"

    return vcf_info
254543
def get_coords(data):
    
    for category, vtypes in [("LOH", {"LOSS", "HETEROZYGOSITY"}),
                             ("amplification", {"AMPLIFICATION"})]:
        out = tz.get_in([category, dd.get_genome_build(data)], _COORDS, {})
        priority_file = dd.get_svprioritize(data)
        if priority_file:
            if os.path.basename(priority_file).find("civic") >= 0:
                for chrom, start, end, gene in _civic_regions(priority_file, vtypes, dd.get_disease(data)):
                    out[gene] = (chrom, start, end)
            elif os.path.basename(priority_file).find(".bed") >= 0:
                for line in utils.open_gzipsafe(priority_file):
                    parts = line.strip().split("\t")
                    if len(parts) >= 4:
                        chrom, start, end, gene = parts[:4]
                        out[gene] = (chrom, int(start), int(end))
        yield category, out
261322
def is_the_same_indel(self, other_record, ref_seq):
        ''''''
        if self.CHROM != other_record.CHROM or len(self.ALT) > 1 or len(other_record.ALT) > 1 or self.is_snp() or other_record.is_snp():
            return False

        # The number of nuleotides that have been added or removed
        # is a necessary condition of the indels being the same,
        # so check that before devling into the actual sequences
        if (len(self.REF) - len(self.ALT[0])) != (len(other_record.REF) - len(other_record.ALT[0])):
            return False

        # make records that start and end in the same place.
        # Then compare the REF and ALT sequences
        record1 = copy.copy(self)
        record2 = copy.copy(other_record)
        new_start = min(self.POS, other_record.POS)
        new_end = max(self.ref_end_pos(), other_record.ref_end_pos())
        record1.add_flanking_seqs(ref_seq, new_start, new_end)
        record2.add_flanking_seqs(ref_seq, new_start, new_end)
        return record1.REF == record2.REF and record1.ALT == record2.ALT
304549
def kma(inputfile_1, out_path, databases, db_path_kma, min_cov=0.6,
            threshold=0.9, kma_path="cge/kma/kma", sample_name="",
            inputfile_2=None, kma_mrs=None, kma_gapopen=None,
            kma_gapextend=None, kma_penalty=None, kma_reward=None, kma_pm=None,
            kma_fpm=None, kma_memmode=False, kma_nanopore=False, debug=False,
            kma_add_args=None):
        
        threshold = threshold * 100
        min_cov = min_cov * 100

        kma_results = dict()
        kma_results["excluded"] = dict()

        if(sample_name):
           sample_name = "_" + sample_name

        # Initiate output dicts.
        gene_align_sbjct = {}
        gene_align_query = {}
        gene_align_homo = {}

        for db in databases:
            kma_db = db_path_kma + "/" + db
            kma_outfile = out_path + "/kma_" + db + sample_name
            kma_cmd = ("%s -t_db %s -o %s -e 1.0" % (kma_path,
                       kma_db, kma_outfile))
            if(inputfile_2 is not None):
                kma_cmd += " -ipe " + inputfile_1 + " " + inputfile_2
            else:
                kma_cmd += " -i " + inputfile_1
            if(kma_mrs is not None):
                kma_cmd += " -mrs " + str(kma_mrs)
            if(kma_gapopen is not None):
                kma_cmd += " -gapopen " + str(kma_gapopen)
            if(kma_gapextend is not None):
                kma_cmd += " -gapextend " + str(kma_gapextend)
            if(kma_penalty is not None):
                kma_cmd += " -penalty " + str(kma_penalty)
            if(kma_reward is not None):
                kma_cmd += " -reward " + str(kma_reward)
            if(kma_pm is not None):
                kma_cmd += " -pm " + kma_pm
            if(kma_fpm is not None):
                kma_cmd += " -fpm " + kma_fpm
            if (kma_memmode):
                kma_cmd += " -mem_mode "
            if (kma_nanopore):
                kma_cmd += " -bcNano "
                kma_cmd += " -mp 20 "
            if (kma_add_args is not None):
                kma_cmd += " " + kma_add_args + " "

            # kma output files
            align_filename = kma_outfile + ".aln"
            res_filename = kma_outfile + ".res"

            # If .res file exists then skip mapping
            if os.path.isfile(res_filename) and os.access(res_filename, os.R_OK):
                print("Found " + res_filename + " skipping DB.")
            else:
                # Call KMA
                if(debug):
                    print("KMA cmd: " + kma_cmd)

                process = subprocess.Popen(kma_cmd, shell=True,
                                           stdout=subprocess.PIPE,
                                           stderr=subprocess.PIPE)
                out, err = process.communicate()

            kma_results[db] = 'No hit found'

            # Open res file
            try:
                res_file = open(res_filename, "r")
                header = res_file.readline()
            except IOError as error:
                sys.exit("Error: KMA did not run as expected.\n" +
                         "KMA finished with the following response:" +
                         "\n{}\n{}".format(out.decode("utf-8"),
                                           err.decode("utf-8")))

            for line in res_file:

                if kma_results[db] == 'No hit found':
                    kma_results[db] = dict()
                    # kma_results[db]["excluded"] = dict()
                    # continue

                data = [data.strip() for data in line.split("\t")]
                gene = data[0]

                sbjct_len = int(data[3])
                sbjct_ident = float(data[4])
                coverage = float(data[5])
                depth = float(data[-3])
                q_value = float(data[-2])
                p_value = float(data[-1])


                if gene not in kma_results[db]:
                    hit = gene
                else:
                    hit = gene + "_" + str(len(kma_results[db][gene]) + 1)

                exclude_reasons = []

                if(coverage < min_cov or sbjct_ident < threshold):
                    exclude_reasons.append(coverage)
                    exclude_reasons.append(sbjct_ident)

                if(exclude_reasons):
                    # kma_results[db]["excluded"][hit] = exclude_reasons
                    kma_results["excluded"][hit] = exclude_reasons

                kma_results[db][hit] = dict()
                kma_results[db][hit]['sbjct_length'] = sbjct_len
                kma_results[db][hit]["perc_coverage"] = coverage
                kma_results[db][hit]["sbjct_string"] = []
                kma_results[db][hit]["query_string"] = []
                kma_results[db][hit]["homo_string"] = []
                kma_results[db][hit]["sbjct_header"] = gene
                kma_results[db][hit]["perc_ident"] = sbjct_ident
                kma_results[db][hit]["query_start"] = "NA"
                kma_results[db][hit]["query_end"] = "NA"
                kma_results[db][hit]["contig_name"] = "NA"
                kma_results[db][hit]["HSP_length"] = ""
                kma_results[db][hit]["cal_score"] = q_value
                kma_results[db][hit]["depth"] = depth
                kma_results[db][hit]["p_value"] = p_value
            res_file.close()


            if kma_results[db] == 'No hit found':
                continue

            # Open align file
            with open(align_filename, "r") as align_file:
                hit_no = dict()
                gene = ""
                # Parse through alignments
                for line in align_file:
                    # Skip empty lines
                    if(not line.strip()):
                        continue

                    # Check when a new gene alignment start
                    if line.startswith("#"):
                        gene = line[1:].strip()

                        if gene not in hit_no:
                            hit_no[gene] = str(1)
                        else:
                            hit_no[gene] += str(int(hit_no[gene]) + 1)

                    else:
                        # Check if gene one of the user specified genes
                        if hit_no[gene] == '1':
                            hit = gene
                        else:
                            hit = gene + "_" + hit_no[gene]

                        if hit in kma_results[db]:
                            line_data = line.split("\t")[-1].strip()
                            if line.startswith("template"):
                                kma_results[db][hit]["sbjct_string"] += (
                                    [line_data])
                            elif line.startswith("query"):
                                kma_results[db][hit]["query_string"] += (
                                    [line_data])
                            else:
                                kma_results[db][hit]["homo_string"] += (
                                    [line_data])
                        else:
                            print(hit + " not in results: ", kma_results)

            # concatinate all sequences lists and find subject start
            # and subject end

            gene_align_sbjct[db] = {}
            gene_align_query[db] = {}
            gene_align_homo[db] = {}

            for hit in kma_results[db]:
                # if(hit == "excluded"):
                # continue
                align_sbjct = "".join(kma_results[db][hit]['sbjct_string'])
                align_query = "".join(kma_results[db][hit]['query_string'])
                align_homo = "".join(kma_results[db][hit]['homo_string'])

                # Extract only aligned sequences
                start = re.search("^-*(\w+)", align_query).start(1)
                end = re.search("\w+(-*)$", align_query).start(1)

                kma_results[db][hit]['sbjct_string'] = align_sbjct[start:end]
                kma_results[db][hit]['query_string'] = align_query[start:end]
                kma_results[db][hit]['homo_string'] = align_homo[start:end]

                # Save align start and stop positions relative to
                # subject sequence
                kma_results[db][hit]['sbjct_start'] = start + 1
                kma_results[db][hit]["sbjct_end"] = end + 1
                kma_results[db][hit]["HSP_length"] = end - start

                # Count gaps in the alignment
                kma_results[db][hit]["gaps"] = (
                    kma_results[db][hit]['sbjct_string'].count("-") +
                    kma_results[db][hit]['query_string'].count("-"))

                # Save sequences covering the entire subject sequence
                # in seperate variables
                gene_align_sbjct[db][hit] = align_sbjct
                gene_align_query[db][hit] = align_query
                gene_align_homo[db][hit] = align_homo

        return FinderResult(kma_results, gene_align_sbjct, gene_align_query,
                            gene_align_homo)
50835
def consecutive_exon_count(self1):
      
      best = 1
      consec = 1
      for i in range(0,len(self1.dif1)):
        if self1.dif1[i] == 1 and self1.dif2[i] == 1:
          consec += 1
        else: 
          consec = 1
        if consec > best:
          best = consec
      return best
956157
def assessOligo(seq):
    '''
    

    '''
    hairpin_out = calcHairpin(seq)
    homodimer_out = calcHomodimer(seq)
    return (hairpin_out, homodimer_out)
665948
def _chk_gene2go(assoc):
    """"""
    if not assoc:
        raise RuntimeError("NO ITEMS FOUND IN ASSOCIATIONS {A}".format(A=assoc))
    for key in assoc:
        if isinstance(key, str) and key[:3] == "GO:":
            raise Exception("ASSOCIATIONS EXPECTED TO BE gene2go, NOT go2gene: {EX}".format(
                EX=assoc.items()[:2]))
        return
184968
def _get_update(self, variant):
        
        update = {
                '$inc': {
                    'homozygote': variant.get('homozygote', 0),
                    'hemizygote': variant.get('hemizygote', 0),
                    'observations': 1
                },
                '$set': {
                    'chrom': variant.get('chrom'),
                    'start': variant.get('pos'),
                    'end': variant.get('end'),
                    'ref': variant.get('ref'),
                    'alt': variant.get('alt'),
                }
             }
        if variant.get('case_id'):
            update['$push'] = {
                                'families': {
                                '$each': [variant.get('case_id')],
                                '$slice': -50
                                }
                            }
        return update
499146
def calculate_mrcas(self, c1 : ClassId, c2 : ClassId) -> Set[ClassId]:
        
        G = self.G
        # reflexive ancestors
        ancs1 = self._ancestors(c1) | {c1}
        ancs2 = self._ancestors(c2) | {c2}
        common_ancestors = ancs1 & ancs2
        redundant = set()
        for a in common_ancestors:
            redundant = redundant | nx.ancestors(G, a)
        return common_ancestors - redundant
793399
private int lrAligned(Area a1, Area a2)
    {
        if (a1.getX1() == a2.getX1())
            return (a1.getX2() == a2.getX2()) ? 2 : 1;
        else if (a1.getX2() == a2.getX2())
            return 1;
        else
            return 0;
    }
1078188
def coupl_model8(self):
        
        self.Coupl = 0.5*self.Adj_signed
        # reduce the value of the coupling of the repressing genes
        # otherwise completely unstable solutions are obtained
        for x in np.nditer(self.Coupl,op_flags=['readwrite']):
            if x < -1e-6:
                x[...] = -0.2
1255136
def _get_site_amplification_term(self, C, vs30):
        
        s_b, s_c, s_d = self._get_site_dummy_variables(vs30)
        return (C["sB"] * s_b) + (C["sC"] * s_c) + (C["sD"] * s_d)
7124
private double[][] _step(double[][] state, char ch1, char ch2) {
    double cost;
    _shift(state);
    state[2][0] = state[1][0] + deletionDistance;
    for (int i = 0; i < morseBase.length(); i++) {
      cost = (morseBase.charAt(i) == ch1) ? 0 : replaceDistance;
      state[2][i + 1] = Math.min(state[2][i] + insertionDistance,
          state[1][i] + cost);
      state[2][i + 1] = Math.min(state[2][i + 1],
          state[1][i + 1] + deletionDistance);
      if (i > 0 && ch2 != 0x00 && (morseBase.charAt(i - 1) == ch1)
          && (morseBase.charAt(i) == ch2)) {
        state[2][i + 1] = Math.min(state[2][i + 1],
            state[0][i - 1] + transpositionDistance);
      }
    }
    return state;
  }