Add the genotype calls for the variant

        Args:
            variant_obj (puzzle.models.Variant)
            variant_dict (dict): A variant dictionary
            case_obj (puzzle.models.Case)
439098
def _add_genotype_calls(self, variant_obj, variant_line, case_obj):
        
        variant_line = variant_line.split('\t')
        #if there is gt calls we have no individuals to add
        if len(variant_line) > 8:
            gt_format = variant_line[8].split(':')
            for individual in case_obj.individuals:
                sample_id = individual.ind_id
                index = individual.ind_index

                gt_call = variant_line[9+index].split(':')

                raw_call = dict(zip(gt_format, gt_call))

                genotype = Genotype(**raw_call)

                variant_obj.add_individual(puzzle_genotype(
                    sample_id = sample_id,
                    genotype = genotype.genotype,
                    case_id = case_obj.name,
                    phenotype = individual.phenotype,
                    ref_depth = genotype.ref_depth,
                    alt_depth = genotype.alt_depth,
                    genotype_quality = genotype.genotype_quality,
                    depth = genotype.depth_of_coverage,
                    supporting_evidence = genotype.supporting_evidence,
                    pe_support = genotype.pe_support,
                    sr_support = genotype.sr_support,
                ))
664161
def addVariantSet(self):
        
        self._openRepo()
        dataset = self._repo.getDatasetByName(self._args.datasetName)
        dataUrls = self._args.dataFiles
        name = self._args.name
        if len(dataUrls) == 1:
            if self._args.name is None:
                name = getNameFromPath(dataUrls[0])
            if os.path.isdir(dataUrls[0]):
                # Read in the VCF files from the directory.
                # TODO support uncompressed VCF and BCF files
                vcfDir = dataUrls[0]
                pattern = os.path.join(vcfDir, "*.vcf.gz")
                dataUrls = glob.glob(pattern)
                if len(dataUrls) == 0:
                    raise exceptions.RepoManagerException(
                        "Cannot find any VCF files in the directory "
                        "'{}'.".format(vcfDir))
                dataUrls[0] = self._getFilePath(dataUrls[0],
                                                self._args.relativePath)
        elif self._args.name is None:
            raise exceptions.RepoManagerException(
                "Cannot infer the intended name of the VariantSet when "
                "more than one VCF file is provided. Please provide a "
                "name argument using --name.")
        parsed = urlparse.urlparse(dataUrls[0])
        if parsed.scheme not in ['http', 'ftp']:
            dataUrls = map(lambda url: self._getFilePath(
                url, self._args.relativePath), dataUrls)
        # Now, get the index files for the data files that we've now obtained.
        indexFiles = self._args.indexFiles
        if indexFiles is None:
            # First check if all the paths exist locally, as they must
            # if we are making a default index path.
            for dataUrl in dataUrls:
                if not os.path.exists(dataUrl):
                    raise exceptions.MissingIndexException(
                        "Cannot find file '{}'. All variant files must be "
                        "stored locally if the default index location is "
                        "used. If you are trying to create a VariantSet "
                        "based on remote URLs, please download the index "
                        "files to the local file system and provide them "
                        "with the --indexFiles argument".format(dataUrl))
            # We assume that the indexes are made by adding .tbi
            indexSuffix = ".tbi"
            # TODO support BCF input properly here by adding .csi
            indexFiles = [filename + indexSuffix for filename in dataUrls]
        indexFiles = map(lambda url: self._getFilePath(
            url, self._args.relativePath), indexFiles)
        variantSet = variants.HtslibVariantSet(dataset, name)
        variantSet.populateFromFile(dataUrls, indexFiles)
        # Get the reference set that is associated with the variant set.
        referenceSetName = self._args.referenceSetName
        if referenceSetName is None:
            # Try to find a reference set name from the VCF header.
            referenceSetName = variantSet.getVcfHeaderReferenceSetName()
        if referenceSetName is None:
            raise exceptions.RepoManagerException(
                "Cannot infer the ReferenceSet from the VCF header. Please "
                "specify the ReferenceSet to associate with this "
                "VariantSet using the --referenceSetName option")
        referenceSet = self._repo.getReferenceSetByName(referenceSetName)
        variantSet.setReferenceSet(referenceSet)
        variantSet.setAttributes(json.loads(self._args.attributes))
        # Now check for annotations
        annotationSets = []
        if variantSet.isAnnotated() and self._args.addAnnotationSets:
            ontologyName = self._args.ontologyName
            if ontologyName is None:
                raise exceptions.RepoManagerException(
                    "A sequence ontology name must be provided")
            ontology = self._repo.getOntologyByName(ontologyName)
            self._checkSequenceOntology(ontology)
            for annotationSet in variantSet.getVariantAnnotationSets():
                annotationSet.setOntology(ontology)
                annotationSets.append(annotationSet)

        # Add the annotation sets and the variant set as an atomic update
        def updateRepo():
            self._repo.insertVariantSet(variantSet)
            for annotationSet in annotationSets:
                self._repo.insertVariantAnnotationSet(annotationSet)
        self._updateRepo(updateRepo)
270999
def _add_genes(self, variant_obj):
        """"""
        genes = []
        ensembl_ids = []
        hgnc_symbols = []
        
        if variant_obj.transcripts:
            for transcript in variant_obj.transcripts:
                if transcript.ensembl_id:
                    ensembl_ids.append(transcript.ensembl_id)
                if transcript.hgnc_symbol:
                    hgnc_symbols.append(transcript.hgnc_symbol)

        else:
            hgnc_symbols = variant_obj.gene_symbols
        
        genes = get_gene_info(
                        ensembl_ids=ensembl_ids, 
                        hgnc_symbols=hgnc_symbols
                        )
            
        for gene in genes:
            variant_obj.add_gene(gene)
705644
def _textOutput(self, gaObjects):
        
        for variant in gaObjects:
            print(
                variant.id, variant.variant_set_id, variant.names,
                variant.reference_name, variant.start, variant.end,
                variant.reference_bases, variant.alternate_bases,
                sep="\t", end="\t")
            for key, value in variant.attributes.attr.items():
                val = value.values[0].string_value
                print(key, val, sep="=", end=";")
            print("\t", end="")
            for c in variant.calls:
                print(
                    c.call_set_id,
                    c.genotype.__str__().replace('\n', ''),
                    c.genotype_likelihood, c.attributes,
                    c.phaseset, sep=":", end="\t")
            print()
1129037
def _create_variant(self,
                        start,
                        end,
                        ref,
                        alt,
                        fsext_len=None,
                        is_dup=False,
                        acc=None,
                        is_ambiguous=False,
                        is_sub=False,
                        is_ext=False,
                        is_no_protein=False,
                        is_init_met=False):
        """"""

        if is_init_met:
            posedit = AARefAlt(ref=ref, alt=alt, init_met=True)
        elif is_ambiguous:
            posedit = None
        else:
            interval = Interval(start=start, end=end)
            # Note - order matters
            if is_no_protein:
                edit = '0'
            elif is_sub:
                edit = AASub(ref=ref, alt=alt)
            elif is_ext:
                edit = AAExt(ref=ref, alt=alt, aaterm='*', length=fsext_len)
            elif self._is_frameshift:
                edit = AAFs(ref=ref, alt=alt, length=fsext_len)
            elif is_dup:
                edit = Dup()
            elif ref == alt == '':
                edit = AARefAlt(ref='', alt='')
            else:
                edit = AARefAlt(ref=ref, alt=alt)
            posedit = PosEdit(
                pos=interval,
                edit=edit,
                uncertain=hgvs.global_config.mapping.inferred_p_is_uncertain)
        var_p = hgvs.sequencevariant.SequenceVariant(acc, 'p', posedit)
        return var_p
855591
public void addVariantDatasetMetadata(VariantStudyMetadata variantStudyMetadata) {
        if (variantStudyMetadata != null) {
            VariantStudyMetadata found = getVariantStudyMetadata(variantStudyMetadata.getId());
            // if there is not any study with that ID then we add the new one
            // TODO we need to think what to do when it exists, should we throw an exception?
            if (found == null) {
                if (variantMetadata.getStudies() == null) {
                    variantMetadata.setStudies(new ArrayList<>());
                }
                variantMetadata.getStudies().add(variantStudyMetadata);
            } else {
                logger.error("Study ID already exists");
            }
        }
    }
668550
def set_variant(self, identity, experiment_name, variant_name):
        
        try:
            experiment = model.Experiment.get_by(name=experiment_name)
            variant = model.Variant.get_by(name=variant_name)
            if experiment and variant and model.Participant.query.filter(and_(
                model.Participant.identity == identity,
                model.Participant.experiment_id == experiment.id,
                model.Participant.variant_id == variant.id
            )).count() == 0:
                model.Participant(
                    identity=identity,
                    experiment=experiment,
                    variant=variant
                )
                self.Session.commit()
        finally:
            self.Session.close()
245124
def _add_exac(self, variant_obj, info_dict):
        
        exac = None
        exac_keys = ['ExAC', 'EXAC', 'ExACAF', 'EXACAF']
        for key in exac_keys:
            if info_dict.get(key):
                exac = float(info_dict[key])
        #If not found in vcf search transcripts
        if not exac:
            for transcript in variant_obj.transcripts:
                exac_raw = transcript.ExAC_MAF
                if exac_raw:
                    exac = float(exac_raw.split(':')[-1])
        
        if exac:
            variant_obj.add_frequency('ExAC', exac)
875101
def add_individual(self, genotype):
        
        logger.debug("Adding genotype {0} to variant {1}".format(
            genotype, self['variant_id']))
        self['individuals'].append(genotype)
1301740
def add_suspect(self, case_obj, variant_obj):
        """"""
        new_suspect = Suspect(case=case_obj, variant_id=variant_obj.variant_id,
                              name=variant_obj.display_name)
        self.session.add(new_suspect)
        self.save()
        return new_suspect
301357
def _dup_samples_by_variantcaller(samples, require_bam=True):
    
    samples = [utils.to_single_data(x) for x in samples]
    samples = germline.split_somatic(samples)
    to_process = []
    extras = []
    for data in samples:
        added = False
        for i, add in enumerate(handle_multiple_callers(data, "variantcaller", require_bam=require_bam)):
            added = True
            add = dd.set_variantcaller_order(add, i)
            to_process.append([add])
        if not added:
            data = _handle_precalled(data)
            data = dd.set_variantcaller_order(data, 0)
            extras.append([data])
    return to_process, extras
425821
def _createGaVariant(self):
        
        ret = protocol.Variant()
        if self._creationTime:
            ret.created = self._creationTime
        if self._updatedTime:
            ret.updated = self._updatedTime
        ret.variant_set_id = self.getId()
        return ret
316444
async def variant(self, elem=None, elem_type=None, params=None, obj=None):
        
        elem_type = elem_type if elem_type else elem.__class__

        if hasattr(elem_type, 'kv_serialize'):
            elem = elem_type() if elem is None else elem
            return await elem.kv_serialize(self, elem=elem, elem_type=elem_type, params=params, obj=obj)

        if self.writing:
            return await self.dump_variant(elem=elem,
                                           elem_type=elem_type if elem_type else elem.__class__, params=params, obj=obj)
        else:
            return await self.load_variant(elem_type=elem_type if elem_type else elem.__class__,
                                           params=params, elem=elem, obj=obj)
251479
async def load_variant(obj, elem, elem_type=None, params=None, field_archiver=None, wrapped=None):
    
    field_archiver = field_archiver if field_archiver else load_field
    is_wrapped = elem_type.WRAPS_VALUE if wrapped is None else wrapped

    if is_wrapped:
        elem = elem_type() if elem is None else elem

    fname = list(obj.keys())[0]
    for field in elem_type.f_specs():
        if field[0] != fname:
            continue

        fvalue = await field_archiver(obj[fname], field[1], field[2:], elem if not is_wrapped else None)
        if is_wrapped:
            elem.set_variant(field[0], fvalue)

        return elem if is_wrapped else fvalue
    raise ValueError('Unknown tag: %s' % fname)
763360
def add_name_variant(self, name):
        
        self._ensure_field('name', {})
        self.obj['name'].setdefault('name_variants', []).append(name)
325976
def create(self, request):
        

        variant_id = request.data.get("variant_id", None)
        if variant_id is not None:
            variant = ProductVariant.objects.get(id=variant_id)
            product_request = ProductRequest(variant=variant)
            product_request.save()
            serializer = self.serializer_class(product_request)
            response = Response(data=serializer.data, status=status.HTTP_201_CREATED)
        else:
            response = Response(
                {"message": "Missing 'variant_id'"},
                status=status.HTTP_400_BAD_REQUEST)

        return response
456991
def insertVariantAnnotationSet(self, variantAnnotationSet):
        
        analysisJson = json.dumps(
            protocol.toJsonDict(variantAnnotationSet.getAnalysis()))
        try:
            models.Variantannotationset.create(
                id=variantAnnotationSet.getId(),
                variantsetid=variantAnnotationSet.getParentContainer().getId(),
                ontologyid=variantAnnotationSet.getOntology().getId(),
                name=variantAnnotationSet.getLocalId(),
                analysis=analysisJson,
                annotationtype=variantAnnotationSet.getAnnotationType(),
                created=variantAnnotationSet.getCreationTime(),
                updated=variantAnnotationSet.getUpdatedTime(),
                attributes=json.dumps(variantAnnotationSet.getAttributes()))
        except Exception as e:
            raise exceptions.RepoManagerException(e)