Prioritize VCF calls based on external annotations supplied through GEMINI.
508390
def handle_vcf_calls(vcf_file, data, orig_items):
    
    if not _do_prioritize(orig_items):
        return vcf_file
    else:
        ann_vcf = population.run_vcfanno(vcf_file, data)
        if ann_vcf:
            priority_file = _prep_priority_filter_vcfanno(ann_vcf, data)
            return _apply_priority_filter(ann_vcf, priority_file, data)
        # No data available for filtering, return original file
        else:
            return vcf_file
858605
def _add_impact_severity(self, variant_obj, gemini_variant):
        
        gemini_impact = gemini_variant['impact_severity']
        if gemini_impact == 'MED':
            gemini_impact = 'MEDIUM'
        variant_obj.impact_severity = gemini_impact
1159011
def prioritized_iter(cls, flag_val, env_val, config_val, config_default_val,
                       hardcoded_val, default):
    """"""
    if flag_val is not None:
      yield RankedValue(cls.FLAG, flag_val)
    if env_val is not None:
      yield RankedValue(cls.ENVIRONMENT, env_val)
    if config_val is not None:
      yield RankedValue(cls.CONFIG, config_val)
    if config_default_val is not None:
      yield RankedValue(cls.CONFIG_DEFAULT, config_default_val)
    if hardcoded_val is not None:
      yield RankedValue(cls.HARDCODED, hardcoded_val)
    yield RankedValue(cls.NONE, default)
129313
def write_vcf(path, callset, rename=None, number=None, description=None,
              fill=None, write_header=True):
    """"""

    names, callset = normalize_callset(callset)

    with open(path, 'w') as vcf_file:
        if write_header:
            write_vcf_header(vcf_file, names, callset=callset, rename=rename,
                             number=number, description=description)
        write_vcf_data(vcf_file, names, callset=callset, rename=rename, fill=fill)
375389
public static void rcvXAPrepare(CommsByteBuffer request,
                                   Conversation conversation,
                                   int requestNumber,
                                   boolean allocatedFromBufferPool,
                                   boolean partOfExchange)
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "rcvXAPrepare",
                                           new Object[]
                                           {
                                              request,
                                              conversation,
                                              ""+requestNumber,
                                              ""+allocatedFromBufferPool,
                                              ""+partOfExchange
                                            });

      // PK61176 We need to clean up tran state in catch block if required. Scope vars appropriately.
      ConversationState convState = (ConversationState) conversation.getAttachment();
      ServerLinkLevelState linkState = (ServerLinkLevelState) conversation.getLinkLevelAttachment();
      SITransaction tran = null;
      int clientTransactionId = 0;
      XidProxy xid = null;

      final boolean optimizedTx = CommsUtils.requiresOptimizedTransaction(conversation);

      try
      {
         clientTransactionId = request.getInt();
         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
         {
            SibTr.debug(tc, "XAResource Object ID", clientTransactionId);
         }

         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Getting Xid");
         xid = (XidProxy) request.getXid();
         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Completed:", xid);

         boolean endRequired = false;
         int endFlags = 0;
         if (optimizedTx)
         {
            endRequired = request.get() == 0x01;
            endFlags = request.getInt();

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            {
               SibTr.debug(tc, "End Required:", ""+endRequired);
               SibTr.debug(tc, "End Flags:", ""+endFlags);
            }
         }

         boolean requiresMSResource = false;
         if (conversation.getHandshakeProperties().getFapLevel() >= JFapChannelConstants.FAP_VERSION_5)
         {
            requiresMSResource = request.get() == 0x01;
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Requires MS Resource:", ""+requiresMSResource);
         }

         // Get the transaction out of the table
         if (endRequired) linkState.getTransactionTable().endOptimizedGlobalTransactionBranch(clientTransactionId, endFlags);
         tran = linkState.getTransactionTable().getResourceForGlobalTransactionBranch(clientTransactionId, xid);

         // If the UOW was never created (because we were running with the
         // optimization that gets an XAResource and enlists it as part of the
         // first piece of transacted work and this failed) then throw
         // an exception notifying the caller that the UOW has been rolled back.
         if (tran == IdToTransactionTable.INVALID_TRANSACTION)
         {
            Throwable throwable =
               linkState.getTransactionTable().getExceptionForRollbackOnlyGlobalTransactionBranch(clientTransactionId, xid);
            String errorMsg =
               nls.getFormattedMessage("TRANSACTION_MARKED_AS_ERROR_SICO2029",
                     new Object[]{ throwable },
                     null);

            XAException xa = new XAException(errorMsg);
            xa.initCause(throwable);
            xa.errorCode = XAException.XA_RBOTHER;
            throw xa;
         }

         // Get the actual transaction ...
         SIXAResource xaResource = getResourceFromTran(tran, convState, requiresMSResource);

         boolean isUnitOfWorkInError = false;
         if (tran != null)
         {
            isUnitOfWorkInError =
               linkState.getTransactionTable().isGlobalTransactionBranchRollbackOnly(clientTransactionId, xid);
         }

         if (isUnitOfWorkInError)
         {
            // PK59276 Rollback the transaction, as after we throw a XA_RB* error the
            // transaction manager will not call us with xa_rollback.
            xaResource.rollback(xid);

            Throwable throwable = linkState.getTransactionTable().getExceptionForRollbackOnlyGlobalTransactionBranch(clientTransactionId, xid);

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "The transaction was marked as error due to",
                                                 throwable);

            // And respond with an error
            XAException xa = new XAException(
               nls.getFormattedMessage("TRANSACTION_MARKED_AS_ERROR_SICO2029",
                                       new Object[]{ throwable },
                                       null)
            );
            xa.initCause(throwable);
            xa.errorCode = XAException.XA_RBOTHER;

            throw xa;
         }

         int rc = 0;
         try
         {
            // Now call the method on the XA resource
            rc = xaResource.prepare(xid);
         }
         finally
         {
            // Now mark the transaction as no longer in doubt. Ensure we always do this
            if (tran != null)
            {
               // Remove transaction from table - as it is no longer in flight
               linkState.getTransactionTable().removeGlobalTransactionBranch(clientTransactionId, xid);
            }
         }

         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Prepare returned: " + rc);

         // PM23626 If we have enlisted in a read only transaction, for example when the only action within
         // the transaction is a synchronous receive that returned null, we also need to remove
         // the transaction from the dispatchable map - as we will not be called with commit/rollback.
         if (rc == XAException.XA_RDONLY)
         {
            linkState.getDispatchableMap().removeDispatchableForGlobalTransaction(clientTransactionId, xid);
         }

         CommsByteBuffer reply = poolManager.allocate();
         reply.putInt(rc);

         try
         {
            conversation.send(reply,
                              JFapChannelConstants.SEG_XAPREPARE_R,
                              requestNumber,
                              JFapChannelConstants.PRIORITY_MEDIUM,
                              true,
                              ThrottlingPolicy.BLOCK_THREAD,
                              null);
         }
         catch (SIException e)
         {
            FFDCFilter.processException(e,
                                        CLASS_NAME + ".rcvXAPrepare",
                                        CommsConstants.STATICCATXATRANSACTION_XAPREPARE_01);

            SibTr.error(tc, "COMMUNICATION_ERROR_SICO2027", e);
         }
      }
      catch (XAException e)
      {
         FFDCFilter.processException(e, CLASS_NAME + ".rcvXAPrepare", CommsConstants.STATICCATXATRANSACTION_XAPREPARE_02);
         
         // PK61176 If the XAException is a XA_RBXXXX then this will be the last time we will get called.
         // Remove transaction from table - as it is no longer in flight
         if (tran != null &&
             e.errorCode >= XAException.XA_RBBASE && e.errorCode <= XAException.XA_RBEND)
         {
           try
           {
             linkState.getTransactionTable().removeGlobalTransactionBranch(clientTransactionId, xid);
           }
           catch (SIErrorException sie)
           {
             // No FFDC Code Needed
             // We could potentially throw this exception because we have already called removeGlobalTransactionBranch in
             //  the finally block of the xaResource.prepare call. As other calls outside of that try-finally block can
             //  throw XAExceptions then we have no guarantee that we even called prepare so we still need this call here in
             //  the catch. We can't add a finally block to this call as we only want to remove the global tran in the case were
             //  we called prepare. The safest fix is just to catch this exception and move on.
             if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Caught SIErrorException when calling remoteGlobalTransactionBranch: " + sie);
           }
           
           linkState.getDispatchableMap().removeDispatchableForGlobalTransaction(clientTransactionId, xid);
         }

         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "XAException - RC: " + e.errorCode, e);

         StaticCATHelper.sendExceptionToClient(e,
                                               CommsConstants.STATICCATXATRANSACTION_XAPREPARE_02,
                                               conversation, requestNumber);
      }

      request.release(allocatedFromBufferPool);

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "rcvXAPrepare");
   }
614743
def get_gemini_files(data):
    
    try:
        from gemini import annotations, config
    except ImportError:
        return {}
    return {"base": config.read_gemini_config()["annotation_dir"],
            "files": annotations.get_anno_files().values()}
257282
protected ImmutableList<Variable> prioritizeVariables(IntermediateQuery query, JoinLikeNode joinLikeNode) {

        /*
         * Sequential (order matters)
         */
        return extractAncestors(query, joinLikeNode).stream()
                .sequential()
                .flatMap(p -> extractPriorityVariables(query, p.parent, p.position))
                .distinct()
                .collect(ImmutableCollectors.toList());
    }
349521
def _populateFromVariantFile(self, varFile, dataUrl, indexFile):
        
        if varFile.index is None:
            raise exceptions.NotIndexedException(dataUrl)
        for chrom in varFile.index:
            # Unlike Tabix indices, CSI indices include all contigs defined
            # in the BCF header.  Thus we must test each one to see if
            # records exist or else they are likely to trigger spurious
            # overlapping errors.
            chrom, _, _ = self.sanitizeVariantFileFetch(chrom)
            if not isEmptyIter(varFile.fetch(chrom)):
                if chrom in self._chromFileMap:
                    raise exceptions.OverlappingVcfException(dataUrl, chrom)
            self._chromFileMap[chrom] = dataUrl, indexFile
        self._updateMetadata(varFile)
        self._updateCallSetIds(varFile)
        self._updateVariantAnnotationSets(varFile, dataUrl)
1012875
private void prioritizeFromEntryNode(DiGraphNode<Node, Branch> entry) {
    PriorityQueue<DiGraphNode<Node, Branch>> worklist =
        new PriorityQueue<>(10, priorityComparator);
    worklist.add(entry);

    while (!worklist.isEmpty()) {
      DiGraphNode<Node, Branch> current = worklist.remove();
      if (nodePriorities.containsKey(current)) {
        continue;
      }

      nodePriorities.put(current, ++priorityCounter);

      List<DiGraphNode<Node, Branch>> successors = cfg.getDirectedSuccNodes(current);
      worklist.addAll(successors);
    }
  }
1276040
def _callable_from_gvcf(data, vrn_file, out_dir):
    
    methods = {"freebayes": "freebayes", "platypus": "platypus",
               "gatk-haplotype": "gatk"}
    gvcf_type = methods.get(dd.get_variantcaller(data))
    if gvcf_type:
        out_file = os.path.join(out_dir, "%s-gcvf-coverage.bed" %
                                utils.splitext_plus(os.path.basename(vrn_file))[0])
        if not utils.file_uptodate(out_file, vrn_file):
            with file_transaction(data, out_file) as tx_out_file:
                cmd = ("gvcf_regions.py --gvcf_type {gvcf_type} {vrn_file} "
                       "| bedtools merge > {tx_out_file}")
                do.run(cmd.format(**locals()), "Convert gVCF to BED file of callable regions")
        return out_file
770607
def _handle_multiple_svcallers(data, stage):
    
    svs = get_svcallers(data)
    # special cases -- prioritization
    if stage == "ensemble" and dd.get_svprioritize(data):
        svs.append("prioritize")
    out = []
    for svcaller in svs:
        if svcaller in _get_callers([data], stage):
            base = copy.deepcopy(data)
            # clean SV callers present in multiple rounds and not this caller
            final_svs = []
            for sv in data.get("sv", []):
                if (stage == "ensemble" or sv["variantcaller"] == svcaller or sv["variantcaller"] not in svs
                      or svcaller not in _get_callers([data], stage, special_cases=True)):
                    final_svs.append(sv)
            base["sv"] = final_svs
            base["config"]["algorithm"]["svcaller"] = svcaller
            base["config"]["algorithm"]["svcaller_orig"] = svs
            out.append(base)
    return out
356633
public static void callOnPriorityChanged(@Nullable List<ProducerContextCallbacks> callbacks) {
    if (callbacks == null) {
      return;
    }
    for (ProducerContextCallbacks callback : callbacks) {
      callback.onPriorityChanged();
    }
  }
654935
def vcs_command(self, fnames, action):
        """"""
        try:
            for path in sorted(fnames):
                vcs.run_vcs_tool(path, action)
        except vcs.ActionToolNotFound as error:
            msg = _("For %s support, please install one of the<br/> "
                    "following tools:<br/><br/>  %s")\
                        % (error.vcsname, ', '.join(error.tools))
            QMessageBox.critical(self, _("Error"),
                _("""<b>Unable to find external program.</b><br><br>%s""")
                    % to_text_string(msg))
1147255
def index():
    """"""
    gene_lists = app.db.gene_lists() if app.config['STORE_ENABLED'] else []
    queries = app.db.gemini_queries() if app.config['STORE_ENABLED'] else []

    case_groups = {}
    for case in app.db.cases():
        key = (case.variant_source, case.variant_type, case.variant_mode)
        if key not in case_groups:
            case_groups[key] = []
        case_groups[key].append(case)

    return render_template('index.html', case_groups=case_groups,
                           gene_lists=gene_lists, queries=queries)
857431
def build_vcf_parts(feature, genome_2bit, info=None):
    
    base1 = genome_2bit[feature.chrom1].get(
        feature.start1, feature.start1 + 1).upper()
    id1 = "hydra{0}a".format(feature.name)
    base2 = genome_2bit[feature.chrom2].get(
        feature.start2, feature.start2 + 1).upper()
    id2 = "hydra{0}b".format(feature.name)
    orientation = _breakend_orientation(feature.strand1, feature.strand2)
    return (VcfLine(feature.chrom1, feature.start1, id1, base1,
                    _vcf_alt(base1, feature.chrom2, feature.start2,
                             orientation.is_rc1, orientation.is_first1),
                    _vcf_info(feature.start1, feature.end1, id2, info)),
            VcfLine(feature.chrom2, feature.start2, id2, base2,
                    _vcf_alt(base2, feature.chrom1, feature.start1,
                             orientation.is_rc2, orientation.is_first2),
                    _vcf_info(feature.start2, feature.end2, id1, info)))
63971
def pyvcf_calls_to_sample_info_list(calls):
    
    return OrderedDict(
        (call.sample, call.data._asdict()) for call in calls)
829985
def vafter_ts(self):
        """"""
        logger.debug("Song finishing")
        future = asyncio.run_coroutine_threadsafe(self.vafter(), client.loop)
        try:
            future.result()
        except Exception as e:
            logger.exception(e)