Make a batch search for variants in the database
        
        Args:
            variant_ids(list(str)): List of variant ids
        
        Returns:
            res(pymngo.Cursor(variant_obj)): The result
323331
def search_variants(self, variant_ids):
        
        query = {'_id': {'$in': variant_ids}}
        
        return self.db.variant.find(query)
842500
def _get_variants(data):
    
    active_vs = []
    if "variants" in data:
        variants = data["variants"]
        # CWL based list of variants
        if isinstance(variants, dict) and "samples" in variants:
            variants = variants["samples"]
        for v in variants:
            # CWL -- a single variant file
            if isinstance(v, six.string_types) and os.path.exists(v):
                active_vs.append(_add_filename_details(v))
            elif (isinstance(v, (list, tuple)) and len(v) > 0 and
                  isinstance(v[0], six.string_types) and os.path.exists(v[0])):
                for subv in v:
                    active_vs.append(_add_filename_details(subv))
            elif isinstance(v, dict):
                if v.get("vrn_file"):
                    active_vs.append(v)
                elif v.get("population"):
                    vrnfile = v.get("population").get("vcf")
                    active_vs.append(_add_filename_details(vrnfile))
                elif v.get("vcf"):
                    active_vs.append(_add_filename_details(v.get("vcf")))
    return active_vs
1124608
def load_variants(manifest_path, database, **kwargs):
    ""
    manifest = ManifestReader(manifest_path)

    vcf_info = manifest.section('vcf')

    # No data regarding VCF
    if 'file' not in vcf_info:
        return

    cursor = connections[database].cursor()

    vcf_path = os.path.join(os.path.dirname(manifest_path), vcf_info['file'])

    with open(vcf_path) as fin:
        log.debug("opening {0} in {1}".format(vcf_path, __name__))
        stream = VariantStream(fin)
        columns = stream.output_columns
        db_table = Variant._meta.db_table
        pgcopy_batch(stream, db_table, columns, cursor, database)

    VARIANT_CHANNEL.publish(manifest_path=manifest_path, database=database)
459244
def variant_sequences_generator_to_dataframe(variant_sequences_generator):
    
    # TODO: Change VariantSequence.alt to VariantSequence.alt_nucleotides
    # or something else that doesn't clash with a variant's `alt` field
    return dataframe_from_generator(
        VariantSequence,
        variant_sequences_generator,
        rename_dict={"alt": "allele"},
        extra_column_fns={
            "gene": lambda variant, _: ";".join(variant.gene_names),
        })
1317944
def get_variant_value(identifier)
      data = Gxapi.with_error_handling do
        Timeout::timeout(2.0) do
          Gxapi.cache.fetch(self.cache_key(identifier)) do
            @interface.get_variant(identifier).to_hash
          end
        end
      end
      Ostruct.new(
        data.is_a?(Hash) ? data : self.default_values
      )
    end
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
1102576
def removeVariantSet(self, variantSet):
        
        for variantSetRecord in models.Variantset.select().where(
                        models.Variantset.id == variantSet.getId()):
            variantSetRecord.delete_instance(recursive=True)
1192977
def get_somatic_variantcallers(items):
    
    out = []
    for data in items:
        vcs = dd.get_variantcaller(data)
        if isinstance(vcs, dict) and "somatic" in vcs:
            vcs = vcs["somatic"]
        if not isinstance(vcs, (list, tuple)):
            vcs = [vcs]
        out += vcs
    return set(vcs)
117945
def annotate_snvs(adapter, vcf_obj):
    
    variants = {}
    
    for nr_variants, variant in enumerate(vcf_obj, 1):
        # Add the variant to current batch
        variants[get_variant_id(variant)] = variant
        # If batch len == 1000 we annotate the batch
        if (nr_variants % 1000) == 0:
            
            for var_obj in adapter.search_variants(list(variants.keys())):
                var_id = var_obj['_id']
                if var_id in variants:
                    annotate_variant(variants[var_id], var_obj)

            for variant_id in variants:
                yield variants[variant_id]
            
            variants = {}
    
    for var_obj in adapter.search_variants(list(variants.keys())):
        var_id = var_obj['_id']
        if var_id in variants:
            annotate_variant(variants[var_id], var_obj)

    for variant_id in variants:
        yield variants[variant_id]
91845
def get_variants(data, include_germline=False):
    
    data = utils.deepish_copy(data)
    supported = ["precalled", "vardict", "vardict-java", "vardict-perl",
                 "freebayes", "octopus", "strelka2"]
    # Right now mutect2 and mutect do not provide heterozygous germline calls
    # to be useful https://github.com/bcbio/bcbio-nextgen/issues/2464
    # supported += ["mutect2", "mutect"]
    if include_germline:
        supported.insert(1, "gatk-haplotype")
    out = []
    # CWL based input
    if isinstance(data.get("variants"), dict) and "samples" in data["variants"]:
        cur_vs = []
        # Unpack single sample list of files
        if (isinstance(data["variants"]["samples"], (list, tuple)) and
              len(data["variants"]["samples"]) == 1 and isinstance(data["variants"]["samples"][0], (list, tuple))):
            data["variants"]["samples"] = data["variants"]["samples"][0]
        for fname in data["variants"]["samples"]:
            variantcaller = utils.splitext_plus(os.path.basename(fname))[0]
            variantcaller = variantcaller.replace(dd.get_sample_name(data) + "-", "")
            for batch in dd.get_batches(data):
                variantcaller = variantcaller.replace(batch + "-", "")
            cur_vs.append({"vrn_file": fname, "variantcaller": variantcaller})
        data["variants"] = cur_vs
    for v in data.get("variants", []):
        if v["variantcaller"] in supported and v.get("vrn_file"):
            out.append((supported.index(v["variantcaller"]), v))
    out.sort()
    return [xs[1] for xs in out]
1091110
def comments(self, case_id=None, variant_id=None, username=None):
        
        logger.debug("Looking for comments")
        comment_objs = self.query(Comment)

        if case_id:
            comment_objs = comment_objs.filter_by(case_id=case_id)

        if variant_id:
            comment_objs = comment_objs.filter_by(variant_id=variant_id)
        elif case_id:
            comment_objs = comment_objs.filter_by(variant_id=None)

        return comment_objs
466653
def getVariantSet(self, id_):
        
        if id_ not in self._variantSetIdMap:
            raise exceptions.VariantSetNotFoundException(id_)
        return self._variantSetIdMap[id_]
533356
def get_variants(self, arch=None, types=None, recursive=False):
        
        types = types or []
        result = []

        if "self" in types:
            result.append(self)

        for variant in six.itervalues(self.variants):
            if types and variant.type not in types:
                continue
            if arch and arch not in variant.arches.union(["src"]):
                continue
            result.append(variant)
            if recursive:
                result.extend(variant.get_variants(types=[i for i in types if i != "self"], recursive=True))

        result.sort(key=lambda x: x.uid)
        return result
809486
def _get_genes(self, variant):
        
        transcripts = variant['transcripts']
        ensembl_ids = [transcript['ensembl_id'] for transcript in
                       transcripts if transcript['ensembl_id']]
        hgnc_symbols = [transcript['hgnc_symbol'] for transcript in
                        transcripts if transcript['hgnc_symbol']]
        genes = get_gene_info(ensembl_ids, hgnc_symbols)
        return genes
128022
def get_variant_id(variant_dict=None, variant_line=None):
    
    
    if variant_dict:
        chrom = variant_dict['CHROM']
        position = variant_dict['POS']
        ref = variant_dict['REF']
        alt = variant_dict['ALT']
    elif variant_line:
        splitted_line = variant_line.rstrip().split('\t')
        chrom = splitted_line[0]
        position = splitted_line[1]
        ref = splitted_line[3]
        alt = splitted_line[4]
    else:
        raise Exception("Have to provide variant dict or variant line")
    
    return '_'.join([
        chrom,
        position,
        ref,
        alt,
    ])
133089
def get_structural_variant(self, variant):
        
        # Create a query for the database
        # This will include more variants than we want
        # The rest of the calculations will be done in python
        query = {
                'chrom': variant['chrom'],
                'end_chrom': variant['end_chrom'],
                'sv_type': variant['sv_type'],
                '$and': [
                    {'pos_left': {'$lte': variant['pos']}},
                    {'pos_right': {'$gte': variant['pos']}},
                ]
            }

        res = self.db.structural_variant.find(query).sort('pos_left',1)
        match = None
        distance = None
        closest_hit = None
        # First we check that the coordinates are correct
        # Then we count the distance to mean on both ends to see which variant is closest
        for hit in res:
            # We know from the query that the variants position is larger than the left most part of
            # the cluster. 
            # If the right most part of the cluster is smaller than the variant position they do
            # not overlap
            if hit['end_left'] > variant['end']:
                continue
            if hit['end_right'] < variant['end']:
                continue

            # We need to calculate the distance to see what cluster that was closest to the variant
            distance = (abs(variant['pos'] - (hit['pos_left'] + hit['pos_right'])/2) + 
                        abs(variant['end'] - (hit['end_left'] + hit['end_right'])/2))

            # If we have no cluster yet we set the curent to be the hit
            if closest_hit is None:
                match = hit
                closest_hit = distance
                continue

            # If the distance is closer than previous we choose current cluster
            if distance < closest_hit:
                # Set match to the current closest hit
                match = hit
                # Update the closest distance
                closest_hit = distance

        return match
186211
def find_variant(name: str) -> Type[chess.Board]:
    """"""
    for variant in VARIANTS:
        if any(alias.lower() == name.lower() for alias in variant.aliases):
            return variant
    raise ValueError("unsupported variant: {}".format(name))