Convenience method to set the common fields in a GA Variant
        object from this variant set.
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
1102576
def removeVariantSet(self, variantSet):
        
        for variantSetRecord in models.Variantset.select().where(
                        models.Variantset.id == variantSet.getId()):
            variantSetRecord.delete_instance(recursive=True)
325965
def set_fields(self, **fields):
        
        for field_name, value in iteritems(fields):
            field = getattr(self, field_name)
            field.proxy_set(value)
1213550
def _add_variants(self, key, value, schema):
        ''' 
        '''
        variants = schema.get('variants')
        obj = {}
        if variants:
            for _key, func in variants.iteritems():
                _value = func(value, self.store)
                obj.update({_key: _value})
        return obj
268164
def _set_fields(self, fields):
        """"""
        for f in fields:
            if hasattr(self, f):
                setattr(self, f, fields[f])
            else:
                raise TypeError("'{arg}' is an invalid argument for {instance_type}".format(arg=f, instance_type=self.__class__.__name__))
863510
def _variants_dtype(fields, dtypes, arities, filter_ids, flatten_filter,
                    info_types):
    """"""
    dtype = list()
    for f, n, vcf_type in zip(fields, arities, info_types):
        if f == 'FILTER' and flatten_filter:
            # split FILTER into multiple boolean fields
            for flt in filter_ids:
                nm = 'FILTER_' + flt
                dtype.append((nm, 'b1'))
        elif f == 'FILTER' and not flatten_filter:
            # represent FILTER as a structured field
            t = [(flt, 'b1') for flt in filter_ids]
            dtype.append((f, t))
        else:
            if dtypes is not None and f in dtypes:
                # user overrides default dtype
                t = dtypes[f]
            elif f in config.STANDARD_VARIANT_FIELDS:
                t = config.DEFAULT_VARIANT_DTYPE[f]
            elif f in config.DEFAULT_INFO_DTYPE:
                # known INFO field
                t = config.DEFAULT_INFO_DTYPE[f]
            else:
                t = config.DEFAULT_TYPE_MAP[vcf_type]
            # deal with arity
            if n == 1:
                dtype.append((f, t))
            else:
                dtype.append((f, t, (n,)))
    return dtype
963194
void setFields(Field[] fields) {
    this.fields = fields;
    this.resultSetColumnNameIndexMap = null;
    this.cachedMaxResultRowSize = null;
    this.needUpdateFieldFormats = fields != null;
    this.hasBinaryFields = false; // just in case
  }
1280433
public static Map<String, VariantSet> concatVariants(Map<String, VariantSet> variantSet1,
			Map<String, VariantSet> variantSet2) {

		Map<String, VariantSet> result = new HashMap<>();
		if (!isEmpty(variantSet1) && isEmpty(variantSet2)) {
			result.putAll(variantSet1);
		} else if (isEmpty(variantSet1) && !isEmpty(variantSet2)) {
			result.putAll(variantSet2);
		} else if (!isEmpty(variantSet1) && !isEmpty(variantSet2)) {

			Set<String> keySet = new HashSet<>();
			keySet.addAll(variantSet1.keySet());
			keySet.addAll(variantSet2.keySet());
			for (String variantType : keySet) {
				VariantSet variants1 = variantSet1.get(variantType);
				VariantSet variants2 = variantSet2.get(variantType);
				Set<String> variants = new HashSet<>();
				String defaultVariant = null;

				if (variants1 != null && variants2 != null && !variants1.hasSameDefaultVariant(variants2)) {
					throw new BundlingProcessException("For the variant type '" + variantType
							+ "', the variant sets defined in your bundles don't have the same default value.");
				}

				if (variants1 != null) {
					variants.addAll(variants1);
					defaultVariant = variants1.getDefaultVariant();
				}
				if (variants2 != null) {
					variants.addAll(variants2);
					defaultVariant = variants2.getDefaultVariant();
				}

				VariantSet variantSet = new VariantSet(variantType, defaultVariant, variants);
				result.put(variantType, variantSet);
			}
		}

		return result;
	}
565949
def bundle_variant(args, l, rc):
    """"""

    from ambry.orm.exc import ConflictError

    ob = l.bundle(args.ref)

    d = dict(
        dataset=args.dataset or ob.identity.dataset,
        revision=args.revision,
        source=args.source or ob.identity.source,
        bspace=args.space or ob.identity.bspace,
        subset=args.subset or ob.identity.subset,
        btime=args.time or ob.identity.btime,
        variation=args.variation or ob.identity.variation)

    try:
        ambry_account = rc.accounts.get('ambry', {})
    except:
        ambry_account = None

    if not ambry_account:
        fatal("Failed to get an accounts.ambry entry from the configuration. ")

    if not ambry_account.get('name') or not ambry_account.get('email'):
        fatal('Must set accounts.ambry.email and accounts.ambry.name n account config file')

    try:
        b = l.new_bundle(assignment_class=args.key, **d)
        b.metadata.contacts.wrangler.name = ambry_account.get('name')
        b.metadata.contacts.wrangler.email = ambry_account.get('email')
        b.commit()

    except ConflictError:
        fatal("Can't create dataset; one with a conflicting name already exists")

    # Now, need to copy over all of the partitions into the new bundle.
    for p in ob.partitions:
        ds = b.dataset.new_source(p.name, ref=p.name, reftype='partition')
        print ds

    b.build_source_files.sources.objects_to_record()

    b.commit()
1291734
def _set_defaults(self):
        
        for field_name in self._fields:
            if field_name in self._init_fields:
                continue
            field = self.get_field(field_name)
            if hasattr(field, "default"):
                field.proxy_set(field.default)
924096
protected void copyFields() {
        for(Field field: copied_fields) {
            Object value=Util.getField(field,main_channel);
            Util.setField(field, this, value);
        }
    }
27400
private void initAnnotatedFields() {
        final Set<Field> hiddenFields = Reflections.getHiddenFields(beanClass);
        inject(hiddenFields);

        final Set<Field> inheritedFields = Reflections.getInheritedFields(beanClass);
        inject(inheritedFields);

        final Set<Field> ownFields = Reflections.getOwnFields(beanClass);
        inject(ownFields);
    }
478165
public void setupFields()
    {
        FieldInfo field = null;
        field = new FieldInfo(this, ID, Constants.DEFAULT_FIELD_LENGTH, null, null);
        field.setDataClass(Integer.class);
        field.setHidden(true);
        field = new FieldInfo(this, LAST_CHANGED, Constants.DEFAULT_FIELD_LENGTH, null, null);
        field.setDataClass(Date.class);
        field.setHidden(true);
        field = new FieldInfo(this, DELETED, 10, null, new Boolean(false));
        field.setDataClass(Boolean.class);
        field.setHidden(true);
        field = new FieldInfo(this, SCREEN_IN_PROG_NAME, 40, null, null);
        field = new FieldInfo(this, SCREEN_OUT_NUMBER, 2, null, null);
        field.setDataClass(Short.class);
        field = new FieldInfo(this, SCREEN_ITEM_NUMBER, 4, null, null);
        field.setDataClass(Short.class);
        field = new FieldInfo(this, SCREEN_FILE_NAME, 40, null, null);
        field = new FieldInfo(this, SCREEN_FIELD_NAME, 40, null, null);
        field = new FieldInfo(this, SCREEN_ROW, 8, null, null);
        field.setDataClass(Short.class);
        field = new FieldInfo(this, SCREEN_COL, 4, null, null);
        field.setDataClass(Short.class);
        field = new FieldInfo(this, SCREEN_GROUP, 4, null, null);
        field = new FieldInfo(this, SCREEN_PHYSICAL_NUM, 4, null, null);
        field.setDataClass(Short.class);
        field = new FieldInfo(this, SCREEN_LOCATION, 20, null, null);
        field = new FieldInfo(this, SCREEN_FIELD_DESC, 30, null, null);
        field = new FieldInfo(this, SCREEN_TEXT, 9999, null, null);
        field = new FieldInfo(this, SCREEN_ANCHOR, 20, null, null);
        field = new FieldInfo(this, SCREEN_CONTROL_TYPE, 20, null, null);
    }
80432
def _with_fields(*fields):
    
    dd = {}
    for x in fields:
        dd[x] = _COMMON_FIELDS[x]

    def wrap(cls):
        dd.update(cls.__dict__)
        return type(cls.__name__, cls.__bases__, dd)

    return wrap
982381
def merge(self, other):
        
        if not isinstance(other, NameVariants):
            raise TypeError("NameVariants isinstance can be merge with"
                            "other isinstance of the same class")
        for key in self.variants:
            self.variants[key] = self.variants[key] or other.variants[key]

        return self
1208848
private void mergeVariants(Variant current, List<Pair<Variant, List<AlternateCoordinate>>> varToAlts) {
        StudyEntry currentStudy = getStudy(current);

        // Build ALT index
        List<AlternateCoordinate> altList = buildAltsList(current, varToAlts);
        // Create a list of alternates as Integers to speed up the creation of the VariantAlternateRearranger
        List<Integer> altListHash = alternatesToHash(altList);
//        Map<AlternateCoordinate, Integer> altIdx = index(altList);

        // Check if the number of secondary alternates has increased. If so, rearrange the current study (files + samples)
        VariantAlternateRearranger currentStudyRearranger = null;
        if (altList.size() - 1 != currentStudy.getSecondaryAlternates().size()) {
            currentStudyRearranger = new VariantAlternateRearranger(alternatesToHash(buildAltList(current)), altListHash);
        }

        // Update SecALt list
        currentStudy.setSecondaryAlternates(altList.subList(1, altList.size()));

        // Find new formats
        final Map<String, Integer> newFormatPositions;
        final List<String> newFormat;
        if (expectedFormatsPosition.isEmpty()) {
            // Find all formats
            Set<String> allFormats = varToAlts.stream()
                    .map(Pair::getKey)
                    .map(this::getStudy)
                    .map(StudyEntry::getFormat)
                    .flatMap(Collection::stream)
                    .collect(Collectors.toSet());
            newFormatPositions = new HashMap<>(currentStudy.getFormatPositions());
//            newFormatPositions.putIfAbsent(getFilterKey(), newFormatPositions.size());
            for (String format : allFormats) {
                newFormatPositions.putIfAbsent(format, newFormatPositions.size());
            }
            newFormat = Arrays.asList(new String[newFormatPositions.size()]);
            newFormatPositions.forEach((format, formatIdx) -> {
                newFormat.set(formatIdx, format);
            });
        } else {
            // TODO: Try to avoid this copy
            newFormatPositions = new HashMap<>(expectedFormatsPosition);
            newFormat = new ArrayList<>(expectedFormatsPosition.keySet());
        }
        Map<String, Integer> extraFormats = newFormatPositions.entrySet()
                .stream()
                .filter(e -> !e.getKey().equals(getGtKey()) && !e.getKey().equals(getFilterKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        // Find new samples
        LinkedHashMap<String, Integer> newSamplesPosition;
        if (expectedSamplesPosition.isEmpty()) {
            newSamplesPosition = new LinkedHashMap<>(currentStudy.getSamplesPosition());
            varToAlts.stream()
                    .map(Pair::getKey)
                    .map(this::getStudy)
                    .map(StudyEntry::getOrderedSamplesName)
                    .flatMap(List::stream)
                    .forEach(sample -> newSamplesPosition.putIfAbsent(sample, newSamplesPosition.size()));
        } else {
            // TODO: Try to avoid this copy
            newSamplesPosition = new LinkedHashMap<>(expectedSamplesPosition);
        }

        Integer newGtIdx = newFormatPositions.get(getGtKey());
        Integer newFilterIdx = newFormatPositions.get(getFilterKey());

        // Create new Samples data
        List<List<String>> newSamplesData = newSamplesData(newSamplesPosition.size(), newFormatPositions);
        boolean[] alreadyMergedSamples = new boolean[newSamplesPosition.size()];
        // Copy current samples data into new samples data
        List<List<String>> currentSamplesData = currentStudy.getSamplesData();
        // If FT is required, but missing in the input variant, get FILTER from the File Attributes.
        String currentFilterValue = null;
        if (!currentStudy.getFormatPositions().containsKey(getFilterKey()) && newFormatPositions.containsKey(getFilterKey())) {
            currentFilterValue = currentStudy.getFiles().isEmpty() ? getDefaultValue(getFilterKey())
                    : currentStudy.getFiles().get(0).getAttributes().getOrDefault(getAnnotationFilterKey(), getDefaultValue(getFilterKey()));
        }
        int currentSampleIdx = 0;
        for (String sample : currentStudy.getOrderedSamplesName()) {
            List<String> currentSampleData = currentSamplesData.get(currentSampleIdx);
            Integer newSampleIdx = newSamplesPosition.get(sample);
            alreadyMergedSamples[newSampleIdx] = true;
            List<String> newSampleData = newSamplesData.get(newSampleIdx);
            int formatIdx = 0;
            int ploidy = 2; // Default ploidy. Required for the rearranger
            for (String format : currentStudy.getFormat()) {
                Integer newFormatIdx = newFormatPositions.get(format);
                if (newFormatIdx != null) {
                    if (currentSampleData.size() > formatIdx) {
                        String data = currentSampleData.get(formatIdx);
                        if (currentStudyRearranger != null) {
                            if (format.equals(VCFConstants.GENOTYPE_KEY)) {
                                Genotype genotype = new Genotype(data);
                                ploidy = genotype.getPloidy();
                                data = currentStudyRearranger.rearrangeGenotype(genotype).toString();
                            } else {
                                data = currentStudyRearranger.rearrange(format, data, ploidy);
                            }
                        }
                        newSampleData.set(newFormatIdx, data);
                    } else {
                        newSampleData.set(newFormatIdx, getDefaultValue(format));
                    }
                }
                formatIdx++;
            }
            // If FT is required, but missing in the input variant, add FILTER from the File Attributes.
            if (newFilterIdx != null && currentFilterValue != null) {
                newSampleData.set(newFilterIdx, currentFilterValue);
            }
            currentSampleIdx++;
        }
        if (currentStudyRearranger != null) {
            for (FileEntry file : currentStudy.getFiles()) {
                file.getAttributes().replaceAll(currentStudyRearranger::rearrange);
            }
        }

        for (Pair<Variant, List<AlternateCoordinate>> e : varToAlts) {
            Variant other = e.getKey();
            List<AlternateCoordinate> otherAlternates = e.getValue();


//            Map<Integer, AlternateCoordinate> otherAltIdx = index(alternates).entrySet().stream()
//                    .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
            final StudyEntry otherStudy = getStudy(other);
            Map<String, Integer> otherStudyFormatPositions = otherStudy.getFormatPositions();
            checkForDuplicates(current, other, currentStudy, otherStudy, otherAlternates);

            VariantAlternateRearranger rearranger;
            Map<String, String> rearrangedGenotypesCache = new HashMap<>(5);
            // It may happen that the new list of alternates does not contains some of the other alternates.
            // In that case, use the rearranger
            if (altList.size() == 1 && altList.equals(otherAlternates)) {
                rearranger = null;
            } else {
                rearranger = new VariantAlternateRearranger(
                        alternatesToHash(otherAlternates),
                        altListHash, rearrangerConf);
            }
            // Add GT data for each sample to current Variant

            List<String> otherOrderedSamplesName = otherStudy.getOrderedSamplesName();
            for (int sampleIdx = 0; sampleIdx < otherOrderedSamplesName.size(); sampleIdx++) {
                String sampleName = otherOrderedSamplesName.get(sampleIdx);
                List<String> otherSampleData = otherStudy.getSamplesData().get(sampleIdx);
                Integer newSampleIdx = newSamplesPosition.get(sampleName);
                List<String> newSampleData = newSamplesData.get(newSampleIdx);

                boolean alreadyMergedSample = alreadyMergedSamples[newSampleIdx];
                alreadyMergedSamples[newSampleIdx] = true;

                // GT data
                int ploidy = -1;
                boolean isGtUpdated = false;
                List<Integer> updatedGtPositions = Collections.emptyList();
                if (newGtIdx != null) {
                    String gt = otherSampleData.get(otherStudyFormatPositions.get(getGtKey()));
                    if (StringUtils.isBlank(gt)) {
                        throw new IllegalStateException(String.format(
                                "No GT [%s] found for sample %s in \nVariant: %s\nOtherSe:%s\nOtherSp:%s",
                                getGtKey(), sampleName, other.getImpl(), otherStudy.getSamplesData(),
                                otherStudy.getSamplesPosition()));
                    }
                    // Use a cache with rearranged genotypes to reuse rearranged genotypes
                    String updatedGt = rearrangedGenotypesCache.get(gt);
                    if (updatedGt == null) {
                        Genotype genotype;
                        if (rearranger != null) {
                            genotype = rearranger.rearrangeGenotype(new Genotype(gt));
                        } else {
                            genotype = new Genotype(gt);
                        }
                        if (!genotype.isPhased()) {
                            genotype.normalizeAllelesIdx();
                        }
                        if (collapseDeletions) {
                            int[] allelesIdx = genotype.getAllelesIdx();
                            for (int i = 0; i < allelesIdx.length; i++) {
                                if (allelesIdx[i] < 0) {
                                    allelesIdx[i] = 0; // change to '0' for 'missing' reference (missing because change to '0' GT)
                                }
                            }
                        }

//                    updatedGt = updateGT(gt, altIdx, otherAltIdx);
                        updatedGt = genotype.toString();
                        rearrangedGenotypesCache.put(gt, updatedGt);
                        ploidy = genotype.getPloidy();
                    } else {
                        ploidy = Genotype.getPloidy(gt);
                    }

                    if (alreadyMergedSample) {
                        String currGT = newSampleData.get(newGtIdx);
                        List<String> gtlst;
                        if (currGT.contains(",")) {
                            gtlst = new ArrayList<>(Arrays.asList(currGT.split(",")));
                        } else {
                            gtlst = new ArrayList<>(1);
                            gtlst.add(currGT);
                        }
                        if (!gtlst.contains(updatedGt)) {
                            gtlst.add(updatedGt);
                            updatedGtPositions = collapseGT(gtlst);
                            updatedGt = StringUtils.join(updatedGtPositions.stream()
                                    .map(gtlst::get).collect(Collectors.toList()), ',');
                            isGtUpdated = true;
                        }
                    }
                    newSampleData.set(newGtIdx, updatedGt);
                }

                // Filter
                if (newFilterIdx != null) {
                    Integer otherFilterIdx = otherStudyFormatPositions.get(getFilterKey());
                    String filter;
                    if (otherFilterIdx != null) {
                        filter = otherSampleData.get(otherFilterIdx);
                    } else {
                        filter = otherStudy.getFiles().get(0).getAttributes()
                                .getOrDefault(StudyEntry.FILTER, getDefaultValue(getFilterKey()));
                    }

                    if (alreadyMergedSample && isGtUpdated) {
                        String currFilter = newSampleData.get(newFilterIdx);
                        if (currFilter != null && !currFilter.equals(getDefaultValue(getFilterKey()))) {
                            List<String> filterLst = new ArrayList<>(Arrays.asList(currFilter.split(",")));
                            filterLst.add(filter);
                            if (/*Objects.isNull(sampleToGt)*/updatedGtPositions.isEmpty()) {
                                filter = StringUtils.join(filterLst, ',');
                            } else {
                                filter = StringUtils.join(updatedGtPositions.stream()
                                        .map(filterLst::get).collect(Collectors.toList()), ',');
                            }
                        }
                    }
                    newSampleData.set(newFilterIdx, filter);
                }

                // Additional data
                for (Map.Entry<String, Integer> entry : extraFormats.entrySet()) {
                    Integer idx = otherStudyFormatPositions.get(entry.getKey());
                    String data = idx == null || idx >= otherSampleData.size() ? getDefaultValue(entry.getKey()) : otherSampleData.get(idx);
                    if (StringUtils.isNotEmpty(data)) {
                        if (rearranger != null) {
                            data = rearranger.rearrange(entry.getKey(), data, ploidy);
                        }
                        String old = newSampleData.set(entry.getValue(), data);
//                        if (old != null) {
//                            throw new IllegalStateException("TODO - merge additional formats!!!");
//                        }
                    }
                }

            }
            mergeFile(current, other, rearranger, currentStudy, otherStudy);
        }
        currentStudy.setSamplesData(newSamplesData);
        currentStudy.setSortedSamplesPosition(newSamplesPosition);
        currentStudy.setFormat(newFormat);
    }
110115
def variantSetsGenerator(self, request):
        
        dataset = self.getDataRepository().getDataset(request.dataset_id)
        return self._topLevelObjectGenerator(
            request, dataset.getNumVariantSets(),
            dataset.getVariantSetByIndex)