return a function that will look up the biotype of a feature
    this checks for either gene_biotype or biotype being set or for the source
    column to have biotype information
347100
def _biotype_lookup_fn(gtf):
    
    db = get_gtf_db(gtf)
    sources = set([feature.source for feature in db.all_features()])
    gene_biotypes = set([feature.attributes.get("gene_biotype", [None])[0]
                         for feature in db.all_features()])
    biotypes = set([feature.attributes.get("biotype", [None])[0]
                    for feature in db.all_features()])
    if "protein_coding" in sources:
        return lambda feature: feature.source
    elif "protein_coding" in biotypes:
        return lambda feature: feature.attributes.get("biotype", [None])[0]
    elif "protein_coding" in gene_biotypes:
        return lambda feature: feature.attributes.get("gene_biotype", [None])[0]
    else:
        return None
482399
def go_aspect(self, go_term):
        
        if not go_term.startswith("GO:"):
            return None
        else:
            # Check ancestors for root terms
            if self.is_molecular_function(go_term):
                return 'F'
            elif self.is_cellular_component(go_term):
                return 'C'
            elif self.is_biological_process(go_term):
                return 'P'
186892
def featuresQuery(self, **kwargs):
        
        # TODO: Optimize by refactoring out string concatenation
        sql = ""
        sql_rows = "SELECT * FROM FEATURE WHERE id > 1 "
        sql_args = ()
        if 'name' in kwargs and kwargs['name']:
            sql += "AND name = ? "
            sql_args += (kwargs.get('name'),)
        if 'geneSymbol' in kwargs and kwargs['geneSymbol']:
            sql += "AND gene_name = ? "
            sql_args += (kwargs.get('geneSymbol'),)
        if 'start' in kwargs and kwargs['start'] is not None:
            sql += "AND end > ? "
            sql_args += (kwargs.get('start'),)
        if 'end' in kwargs and kwargs['end'] is not None:
            sql += "AND start < ? "
            sql_args += (kwargs.get('end'),)
        if 'referenceName' in kwargs and kwargs['referenceName']:
            sql += "AND reference_name = ?"
            sql_args += (kwargs.get('referenceName'),)
        if 'parentId' in kwargs and kwargs['parentId']:
            sql += "AND parent_id = ? "
            sql_args += (kwargs['parentId'],)
        if kwargs.get('featureTypes') is not None \
                and len(kwargs['featureTypes']) > 0:
            sql += "AND type IN ("
            sql += ", ".join(["?", ] * len(kwargs.get('featureTypes')))
            sql += ") "
            sql_args += tuple(kwargs.get('featureTypes'))
        sql_rows += sql
        sql_rows += " ORDER BY reference_name, start, end ASC "
        return sql_rows, sql_args
81197
def v_type_if_feature(ctx, stmt, no_error_report=False):
    """"""
    stmt.i_feature = None
    # Verify the argument type
    expr = syntax.parse_if_feature_expr(stmt.arg)
    if stmt.i_module.i_version == '1':
        # version 1 allows only a single value as if-feature
        if type(expr) != type(''):
            err_add(ctx.errors, stmt.pos,
                    'BAD_VALUE', (stmt.arg, 'identifier-ref'))
            return

    def eval(expr):
        if type(expr) == type(''):
            return has_feature(expr)
        else:
            (op, op1, op2) = expr
            if op == 'not':
                return not eval(op1)
            elif op == 'and':
                return eval(op1) and eval(op2)
            elif op == 'or':
                return eval(op1) or eval(op2)

    def has_feature(name):
        # raises Abort if the feature is not defined
        # returns True if we compile with the feature
        # returns False if we compile without the feature
        found = None
        if name.find(":") == -1:
            prefix = None
        else:
            [prefix, name] = name.split(':', 1)
        if prefix is None or stmt.i_module.i_prefix == prefix:
            # check local features
            pmodule = stmt.i_module
        else:
            # this is a prefixed name, check the imported modules
            pmodule = prefix_to_module(stmt.i_module, prefix,
                                       stmt.pos, ctx.errors)
            if pmodule is None:
                raise Abort
        if name in pmodule.i_features:
            f = pmodule.i_features[name]
            if prefix is None and not is_submodule_included(stmt, f):
                pass
            else:
                found = pmodule.i_features[name]
                v_type_feature(ctx, found)
                if pmodule.i_modulename in ctx.features:
                    if name not in ctx.features[pmodule.i_modulename]:
                        return False

        if found is None and no_error_report == False:
            err_add(ctx.errors, stmt.pos,
                    'FEATURE_NOT_FOUND', (name, pmodule.arg))
            raise Abort
        return found is not None

    # Evaluate the if-feature expression, and verify that all
    # referenced features exist.
    try:
        if eval(expr) == False:
            # prune the parent.
            # since the parent can have more than one if-feature
            # statement, we must check if the parent
            # already has been scheduled for removal
            if stmt.parent not in stmt.i_module.i_prune:
                stmt.i_module.i_prune.append(stmt.parent)
    except Abort:
        pass
1005798
def getFeatureById(self, featureId):
        
        sql = "SELECT * FROM FEATURE WHERE id = ?"
        query = self._dbconn.execute(sql, (featureId,))
        ret = query.fetchone()
        if ret is None:
            return None
        return sqlite_backend.sqliteRowToDict(ret)
331213
def fetch_feature_type(self):
        """"""
        query = self.query().add_query_parameter(req='featureType')
        return self.get_query(query).content
1300581
def locus_of_gene_id(self, gene_id):
        
        return self.db.query_locus(
            filter_column="gene_id",
            filter_value=gene_id,
            feature="gene")
470748
def referencegenomefinder(self):
        
        # Initialise dictionaries
        referencematch = defaultdict(make_dict)
        referencehits = defaultdict(make_dict)
        # Set the name of the reference profile file
        referencegenomeprofile = '{}rMLST_referenceprofile.json'.format(self.referenceprofilepath)
        # Open the reference profile and load the profile into memory
        with open(referencegenomeprofile) as referencefile:
            referencetypes = json.load(referencefile)
        # Iterate through the samples
        for sample in self.metadata:
            if sample[self.analysistype].reportdir != 'NA':
                # Iterate through the reference genomes in the profile
                for genome in referencetypes:
                    # Initialise the number of identical alleles between the assembly of interest and the
                    # reference genome to 0
                    referencehits[sample.name][genome] = 0
                    # Iterate through all the genes in the analysis
                    for gene in self.bestdict[sample.name]:
                        # If the alleles match between the assembly of interest and the reference genome, increment
                        # the number of matches by 1
                        if list(self.bestdict[sample.name][gene].keys())[0] == referencetypes[genome][gene]:
                            referencematch[sample.name][genome][gene] = 1
                            referencehits[sample.name][genome] += 1
                        else:
                            referencematch[sample.name][genome][gene] = 0
        #
        for sample in self.metadata:
            if sample[self.analysistype].reportdir != 'NA':
                # Get the best number of matches
                # From: https://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value
                try:
                    matches = sorted(referencehits[sample.name].items(),
                                     key=operator.itemgetter(1), reverse=True)
                    most_matches = matches[0][1]
                    i = 0
                    match_list = list()
                    while matches[i][1] == most_matches:
                        match_list.append(matches[i])
                        i += 1
                    sorted_list = sorted(match_list)
                    sortedmatches = sorted_list[0]
                except IndexError:
                    sortedmatches = (0, 0)
                # If there are fewer matches than the total number of genes in the typing scheme
                if 0 < int(sortedmatches[1]) < len(sample[self.analysistype].allelenames):
                    mismatches = []
                    # Iterate through the gene in the analysis
                    for gene, allele in referencetypes[sortedmatches[0]].items():
                        # Populate :self.referencegenome with the genome name, best reference match, number of matches,
                        # gene, query allele(s), and percent identity
                        percentidentity = '{:.2f}'.format(list(self.bestdict[sample.name][gene].values())[0])
                        self.referencegenome[sample.name][sortedmatches[0]][sortedmatches[1]][gene][list(self.bestdict[
                            sample.name][gene].keys())[0]] = percentidentity
                        if list(self.bestdict[sample.name][gene].keys())[0] != allele:
                            sample[self.analysistype].referencegenome = sortedmatches[0]
                            sample.general.referencegenus = sortedmatches[0].split('_')[0]
                            sample[self.analysistype].referencegenomepath = '{}{}.fa' \
                                .format(self.referenceprofilepath, sortedmatches[0])
                            sample[self.analysistype].matchestoreferencegenome = sortedmatches[1]
                            mismatches.append(({gene: ('{} ({})'.format(list(self.bestdict[sample.name][gene]
                                                                        .keys())[0], allele))}))
                        # sample[self.analysistype].mismatchestoreferencegenome = sorted(mismatches)
                        sample[self.analysistype].mismatchestoreferencegenome = mismatches
                elif sortedmatches == 0:
                    for gene in sample[self.analysistype].allelenames:
                        # Populate the profile of results with 'negative' values for sequence type and sorted matches
                        self.referencegenome[sample.name][sortedmatches[0]][0][gene]['NA'] = 0
                        sample[self.analysistype].referencegenome = 'NA'
                        sample.general.referencegenus = 'NA'
                        sample[self.analysistype].referencegenomepath = 'NA'
                        sample[self.analysistype].matchestoreferencegenome = 0
                        sample[self.analysistype].mismatchestoreferencegenome = [0]
                # Otherwise, the query profile matches the reference profile
                else:
                    for gene in referencetypes[sortedmatches[0]]:
                        # Populate self.referencegenome as above
                        self.referencegenome[sample.name][sortedmatches[0]][sortedmatches[1]][gene][list(self.bestdict[
                            sample.name][gene].keys())[0]] = '{:.2f}'.format(list(self.bestdict[
                                                                                sample.name][gene].values())[0])
                        sample[self.analysistype].referencegenome = sortedmatches[0]
                        sample[self.analysistype].referencegenomepath = '{}{}.fa' \
                            .format(self.referenceprofilepath, sortedmatches[0])
                        sample.general.referencegenus = sortedmatches[0].split('_')[0]
                        sample[self.analysistype].matchestoreferencegenome = sortedmatches[1]
                        sample[self.analysistype].mismatchestoreferencegenome = [0]
        # Print the results to file
        make_path(self.reportpath)
        with open('{}referencegenomes.csv'.format(self.reportpath), 'w') as referencegenomereport:
            row = 'Strain,referencegenome,numberofmatches\n'
            for sample in self.metadata:
                if sample[self.analysistype].reportdir != 'NA':
                    row += '{},{},{}\n'.format(sample.name, sample[self.analysistype].referencegenome,
                                               sample[self.analysistype].matchestoreferencegenome)
            referencegenomereport.write(row)
            dotter()
1027475
private static int getFeatureTypeIndex(String feature) {
    if (feature.endsWith("|C")) {
      return 0;
    } else if (feature.endsWith("|CpC")) {
      return 1;
    } else if (feature.endsWith("|Cp2C")) {
      return 2;
    } else if (feature.endsWith("|Cp3C")) {
      return 3;
    } else if (feature.endsWith("|Cp4C")) {
      return 4;
    } else if (feature.endsWith("|Cp5C")) {
      return 5;
    } else {
      throw new RuntimeException("Unknown feature type " + feature);
    }
  }
107456
def check_species_object(species_name_or_object):
    
    if isinstance(species_name_or_object, Species):
        return species_name_or_object
    elif isinstance(species_name_or_object, str):
        return find_species_by_name(species_name_or_object)
    else:
        raise ValueError("Unexpected type for species: %s : %s" % (
            species_name_or_object, type(species_name_or_object)))
378567
def get_rRNA(gtf):
    
    rRNA_biotypes = ["rRNA", "Mt_rRNA", "tRNA", "MT_tRNA"]
    features = set()
    with open_gzipsafe(gtf) as in_handle:
        for line in in_handle:
            if not "gene_id" in line or not "transcript_id" in line:
                continue
            if any(x in line for x in rRNA_biotypes):
                geneid = line.split("gene_id")[1].split(" ")[1]
                geneid = _strip_non_alphanumeric(geneid)
                geneid = _strip_feature_version(geneid)
                txid = line.split("transcript_id")[1].split(" ")[1]
                txid = _strip_non_alphanumeric(txid)
                txid = _strip_feature_version(txid)
                features.add((geneid, txid))
    return features
210350
def _check_feature_types(self):
        
        if self.default_feature_type is not None and self.default_feature_type not in self.allowed_feature_types:
            raise ValueError('Default feature type parameter must be one of the allowed feature types')

        for feature_type in self.feature_collection:
            if feature_type is not None and feature_type not in self.allowed_feature_types:
                raise ValueError('Feature type has to be one of {}, but {} found'.format(self.allowed_feature_types,
                                                                                         feature_type))
722542
def getSpec(cls):
    
    spec = dict(
      description=ColumnPoolerRegion.__doc__,
      singleNodeOnly=True,
      inputs=dict(
        feedforwardInput=dict(
          description="The primary feed-forward input to the layer, this is a"
                      " binary array containing 0's and 1's",
          dataType="Real32",
          count=0,
          required=True,
          regionLevel=True,
          isDefaultInput=True,
          requireSplitterMap=False),

        feedforwardGrowthCandidates=dict(
          description=("An array of 0's and 1's representing feedforward input " +
                       "that can be learned on new proximal synapses. If this " +
                       "input isn't provided, the whole feedforwardInput is "
                       "used."),
          dataType="Real32",
          count=0,
          required=False,
          regionLevel=True,
          isDefaultInput=False,
          requireSplitterMap=False),

        predictedInput=dict(
          description=("An array of 0s and 1s representing input cells that " +
                       "are predicted to become active in the next time step. " +
                       "If this input is not provided, some features related " +
                       "to online learning may not function properly."),
          dataType="Real32",
          count=0,
          required=False,
          regionLevel=True,
          isDefaultInput=False,
          requireSplitterMap=False),

        lateralInput=dict(
          description="Lateral binary input into this column, presumably from"
                      " other neighboring columns.",
          dataType="Real32",
          count=0,
          required=False,
          regionLevel=True,
          isDefaultInput=False,
          requireSplitterMap=False),

        resetIn=dict(
          description="A boolean flag that indicates whether"
                      " or not the input vector received in this compute cycle"
                      " represents the first presentation in a"
                      " new temporal sequence.",
          dataType='Real32',
          count=1,
          required=False,
          regionLevel=True,
          isDefaultInput=False,
          requireSplitterMap=False),

      ),
      outputs=dict(
        feedForwardOutput=dict(
          description="The default output of ColumnPoolerRegion. By default this"
                      " outputs the active cells. You can change this "
                      " dynamically using the defaultOutputType parameter.",
          dataType="Real32",
          count=0,
          regionLevel=True,
          isDefaultOutput=True),

        activeCells=dict(
          description="A binary output containing a 1 for every"
                      " cell that is currently active.",
          dataType="Real32",
          count=0,
          regionLevel=True,
          isDefaultOutput=False),

      ),
      parameters=dict(
        learningMode=dict(
          description="Whether the node is learning (default True).",
          accessMode="ReadWrite",
          dataType="Bool",
          count=1,
          defaultValue="true"),
        onlineLearning=dict(
          description="Whether to use onlineLearning or not (default False).",
          accessMode="ReadWrite",
          dataType="Bool",
          count=1,
          defaultValue="false"),
        learningTolerance=dict(
          description="How much variation in SDR size to accept when learning. "
                      "Only has an effect if online learning is enabled. "
                      "Should be at most 1 - inertiaFactor.",
          accessMode="ReadWrite",
          dataType="Real32",
          count=1,
          defaultValue="false"),
        cellCount=dict(
          description="Number of cells in this layer",
          accessMode="Read",
          dataType="UInt32",
          count=1,
          constraints=""),
        inputWidth=dict(
          description='Number of inputs to the layer.',
          accessMode='Read',
          dataType='UInt32',
          count=1,
          constraints=''),
        numOtherCorticalColumns=dict(
          description="The number of lateral inputs that this L2 will receive. "
                      "This region assumes that every lateral input is of size "
                      "'cellCount'.",
          accessMode="Read",
          dataType="UInt32",
          count=1,
          constraints=""),
        sdrSize=dict(
          description="The number of active cells invoked per object",
          accessMode="Read",
          dataType="UInt32",
          count=1,
          constraints=""),
        maxSdrSize=dict(
          description="The largest number of active cells in an SDR tolerated "
                      "during learning. Stops learning when unions are active.",
          accessMode="Read",
          dataType="UInt32",
          count=1,
          constraints=""),
        minSdrSize=dict(
          description="The smallest number of active cells in an SDR tolerated "
                      "during learning.  Stops learning when possibly on a "
                      "different object or sequence",
          accessMode="Read",
          dataType="UInt32",
          count=1,
          constraints=""),

        #
        # Proximal
        #
        synPermProximalInc=dict(
          description="Amount by which permanences of proximal synapses are "
                      "incremented during learning.",
          accessMode="Read",
          dataType="Real32",
          count=1),
        synPermProximalDec=dict(
          description="Amount by which permanences of proximal synapses are "
                      "decremented during learning.",
          accessMode="Read",
          dataType="Real32",
          count=1),
        initialProximalPermanence=dict(
          description="Initial permanence of a new proximal synapse.",
          accessMode="Read",
          dataType="Real32",
          count=1,
          constraints=""),
        sampleSizeProximal=dict(
          description="The desired number of active synapses for an active cell",
          accessMode="Read",
          dataType="Int32",
          count=1),
        minThresholdProximal=dict(
          description="If the number of synapses active on a proximal segment "
                      "is at least this threshold, it is considered as a "
                      "candidate active cell",
          accessMode="Read",
          dataType="UInt32",
          count=1,
          constraints=""),
        connectedPermanenceProximal=dict(
          description="If the permanence value for a synapse is greater "
                      "than this value, it is said to be connected.",
          accessMode="Read",
          dataType="Real32",
          count=1,
          constraints=""),
        predictedInhibitionThreshold=dict(
          description="How many predicted cells are required to cause "
                      "inhibition in the pooler.  Only has an effect if online "
                      "learning is enabled.",
          accessMode="Read",
          dataType="Real32",
          count=1,
          constraints=""),

        #
        # Distal
        #
        synPermDistalInc=dict(
          description="Amount by which permanences of synapses are "
                      "incremented during learning.",
          accessMode="Read",
          dataType="Real32",
          count=1),
        synPermDistalDec=dict(
          description="Amount by which permanences of synapses are "
                      "decremented during learning.",
          accessMode="Read",
          dataType="Real32",
          count=1),
        initialDistalPermanence=dict(
          description="Initial permanence of a new synapse.",
          accessMode="Read",
          dataType="Real32",
          count=1,
          constraints=""),
        sampleSizeDistal=dict(
          description="The desired number of active synapses for an active "
                      "segment.",
          accessMode="Read",
          dataType="Int32",
          count=1),
        activationThresholdDistal=dict(
          description="If the number of synapses active on a distal segment is "
                      "at least this threshold, the segment is considered "
                      "active",
          accessMode="Read",
          dataType="UInt32",
          count=1,
          constraints=""),
        connectedPermanenceDistal=dict(
          description="If the permanence value for a synapse is greater "
                      "than this value, it is said to be connected.",
          accessMode="Read",
          dataType="Real32",
          count=1,
          constraints=""),
        inertiaFactor=dict(
          description="Controls the proportion of previously active cells that "
                      "remain active through inertia in the next timestep (in  "
                      "the absence of inhibition).",
          accessMode="Read",
          dataType="Real32",
          count=1,
          constraints=""),



        seed=dict(
          description="Seed for the random number generator.",
          accessMode="Read",
          dataType="UInt32",
          count=1),
        defaultOutputType=dict(
          description="Controls what type of cell output is placed into"
                      " the default output 'feedForwardOutput'",
          accessMode="ReadWrite",
          dataType="Byte",
          count=0,
          constraints="enum: active,predicted,predictedActiveCells",
          defaultValue="active"),
      ),
      commands=dict(
        reset=dict(description="Explicitly reset TM states now."),
      )
    )

    return spec
255530
def lookup_function(val):
	""
	
	type = val.type
	
	if type.code == gdb.TYPE_CODE_REF:
		type = type.target()
	
	type = type.unqualified().strip_typedefs()
	
	typename = type.tag
	if typename == None:
		return None
	
	for function in pretty_printers_dict:
		if function.search(typename):
			return pretty_printers_dict[function](val)
	
	return None
813894
def db_type(python_type_representation):
    
    for type_name in _candidate_type_names(python_type_representation):
        db_type_name = _lookup_type_name(type_name)
        if db_type_name:
            return db_type_name
    raise ValueError("Failed to find sqlite3 column type for %s" % (
        python_type_representation))
1116495
def read_ncbi_gene2go(fin_gene2go, taxids=None, **kws):
    """"""
    obj = Gene2GoReader(fin_gene2go, taxids=taxids)
    # By default, return id2gos. User can cause go2geneids to be returned by:
    #   >>> read_ncbi_gene2go(..., go2geneids=True
    if 'taxid2asscs' not in kws:
        if len(obj.taxid2asscs) == 1:
            taxid = next(iter(obj.taxid2asscs))
            kws_ncbi = {k:v for k, v in kws.items() if k in AnnoOptions.keys_exp}
            kws_ncbi['taxid'] = taxid
            return obj.get_id2gos(**kws_ncbi)
    # Optional detailed associations split by taxid and having both ID2GOs & GO2IDs
    # e.g., taxid2asscs = defaultdict(lambda: defaultdict(lambda: defaultdict(set))
    t2asscs_ret = obj.get_taxid2asscs(taxids, **kws)
    t2asscs_usr = kws.get('taxid2asscs', defaultdict(lambda: defaultdict(lambda: defaultdict(set))))
    if 'taxid2asscs' in kws:
        obj.fill_taxid2asscs(t2asscs_usr, t2asscs_ret)
    return obj.get_id2gos_all(t2asscs_ret)
218593
def get_column(self, chrom, position,
                 missing_seqs=MissingSequenceHandler.TREAT_AS_ALL_GAPS,
                 species=None):
    """"""
    blocks = self.get_blocks(chrom, position, position + 1)
    if len(blocks) == 0:
      raise NoSuchAlignmentColumnError("Request for column on chrom " +
                                       chrom + " at position " +
                                       str(position) + " not possible; " +
                                       "genome alignment not defined at " +
                                       "that locus.")
    if len(blocks) > 1:
      raise NoUniqueColumnError("Request for column on chrom " + chrom +
                                " at position " + str(position) + "not " +
                                "possible; ambiguous alignment of that locus.")

    return blocks[0].get_column_absolute(position, missing_seqs, species)