Return Interacting taxon ID | optional | 0 or 1 | gaf column 13.
492729
def _get_taxon(taxon):
        """"""
        if not taxon:
            return None
        ## assert taxon[:6] == 'taxon:', 'UNRECOGNIZED Taxon({Taxon})'.format(Taxon=taxon)
        ## taxid = taxon[6:]
        ## assert taxon[:10] == 'NCBITaxon:', 'UNRECOGNIZED Taxon({Taxon})'.format(Taxon=taxon)
        ## taxid = taxon[10:]
        # Get tzxon number: taxon:9606 NCBITaxon:9606
        sep = taxon.find(':')
        taxid = taxon[sep + 1:]
        assert taxid.isdigit(), "UNEXPECTED TAXON({T})".format(T=taxid)
        return int(taxid)
304717
def tblNomenclator
      @headers = %w{NomenclatorID GenusNameID SubgenusNameID SpeciesNameID SubspeciesNameID LastUpdate ModifiedBy SuitableForGenus SuitableForSpecies InfrasubspeciesNameID InfrasubKind}
      sql = []   
      i = 1

      # Ugh, move build from here 
      @name_collection.nomenclators.keys.each do |i|
        name =  @name_collection.nomenclators[i]
        genus_id = @genus_names[name[0]]
        genus_id ||= 0
        subgenus_id = @genus_names[name[1]]
        subgenus_id ||= 0
        species_id = @species_names[name[2]]
        species_id ||= 0
        subspecies_id = @species_names[name[3]]
        subspecies_id ||= 0
        variety_id = @species_names[name[4]]
        variety_id ||= 0

        cols = {
          NomenclatorID: i,
          GenusNameID: genus_id, 
          SubgenusNameID: subgenus_id, 
          SpeciesNameID: species_id, 
          SubspeciesNameID: subspecies_id,
          InfrasubspeciesNameID: variety_id,
          InfrasubKind: (variety_id == 0 ? 0 : 2), 
          LastUpdate: @time,  
          ModifiedBy: @authorized_user_id, 
          SuitableForGenus: 0,                      # Set in SF w test
          SuitableForSpecies: 0                     # Set in SF w test
        }
        i += 1
        sql << sql_insert_statement('tblNomenclator', cols) 
      end

      sql.join("\n")
    end
1231470
def cli(ctx, organism_id, common_name, directory, blatdb="", species="", genus="", public=False):
    
    return ctx.gi.organisms.update_organism(organism_id, common_name, directory, blatdb=blatdb, species=species, genus=genus, public=public)
930151
def idsKEGG(organism):
    
    ORG=urlopen("http://rest.kegg.jp/list/"+organism).read()
    ORG=ORG.split("\n")
    final=[]
    for k in ORG:
        final.append(k.split("\t"))
    df=pd.DataFrame(final[0:len(final)-1])[[0,1]]
    df.columns=['KEGGid','description']
    field = pd.DataFrame(df['description'].str.split(';',1).tolist())[0]
    field = pd.DataFrame(field)
    df = pd.concat([df[['KEGGid']],field],axis=1)
    df.columns=['KEGGid','gene_name']
    df=df[['gene_name','KEGGid']]
    return df
518746
def get_paired_phenotype(data):
    
    allowed_names = set(["tumor", "normal"])
    p = tz.get_in(["metadata", "phenotype"], data)
    return p if p in allowed_names else None
587470
def chk(self, annotations, fout_err):
        """"""
        for idx, ntd in enumerate(annotations):
            self._chk_fld(ntd, "Qualifier")        # optional 0 or greater
            self._chk_fld(ntd, "DB_Reference", 1)  # required 1 or greater
            self._chk_fld(ntd, "With_From")        # optional 0 or greater
            self._chk_fld(ntd, "DB_Name", 0, 1)    # optional 0 or 1
            self._chk_fld(ntd, "DB_Synonym")       # optional 0 or greater
            self._chk_fld(ntd, "Taxon", 1, 2)
            flds = list(ntd)
            self._chk_qty_eq_1(flds)
            # self._chk_qualifier(ntd.Qualifier, flds, idx)
            if not ntd.Taxon or len(ntd.Taxon) not in {1, 2}:
                self.illegal_lines['BAD TAXON'].append((idx, '**{I}) TAXON: {NT}'.format(I=idx, NT=ntd)))
        if self.illegal_lines:
            self.prt_error_summary(fout_err)
        return not self.illegal_lines
353872
def write_assoc(self, assoc):
        
        # Handle comment 'associations'
        if assoc.get("header", False):

            # Skip incoming gaf-version headers, as we created the version above already
            if re.match("![\s]*gaf.?version", assoc["line"]):
                return

            self._write(assoc["line"] + "\n")
            return

        subj = assoc['subject']

        db, db_object_id = self._split_prefix(subj)

        qualifier = "|".join(assoc["qualifiers"])
        # qualifier is | seperated string, filter on None removes empty strings in case qualifiers is empty
        if assoc['negated']:
            qualifier = "|".join(list(filter(None, ["NOT", qualifier])))

        goid = assoc['object']['id']

        ev = assoc['evidence']
        evidence = ev['type']
        withfrom = "|".join(ev['with_support_from'])
        reference = "|".join(ev['has_supporting_reference'])

        date = assoc['date']
        assigned_by = assoc['provided_by']

        annotation_properties = '' # TODO
        # if we have any subject extensions, list each one that has a "property" equal to "isoform", take the first one, and grab the "filler"
        gene_product_isoform = [e for e in assoc["subject_extensions"] if e["property"] == "isoform"][0]["filler"] if len(assoc["subject_extensions"]) > 0 else ""

        aspect = assoc['aspect']
        interacting_taxon_id = assoc["interacting_taxon"]
        taxon = self._full_taxon_field(self.normalize_taxon(subj['taxon']['id']), self.normalize_taxon(interacting_taxon_id))

        extension_expression = self._extension_expression(assoc['object_extensions'])

        vals = [db,
                db_object_id,
                subj.get('label'),
                qualifier,
                goid,
                reference,
                evidence,
                withfrom,
                aspect,
                subj["fullname"],
                "|".join(subj.get('synonyms',[])),
                subj.get('type'),
                taxon,
                date,
                assigned_by,
                extension_expression,
                gene_product_isoform]

        self._write_row(vals)
683988
def gffatributes2ids(s):
    
    Name,gene_id,transcript_id,protein_id,exon_id=np.nan,np.nan,np.nan,np.nan,np.nan
    if '=' in s:
        d=dict([i.split('=') for i in s.split(';')])
        if 'Parent' in d:
            d[d['Parent'].split(':')[0]+'_id']=d['Parent'].split(':')[1]
        Name,gene_id,transcript_id,protein_id,exon_id=np.nan,np.nan,np.nan,np.nan,np.nan
        if 'Name' in d:    
            Name=d['Name']
        if 'gene_id' in d:    
            gene_id=d['gene_id']
        if 'transcript_id' in d:    
            transcript_id=d['transcript_id']
        if 'protein_id' in d:    
            protein_id=d['protein_id']
        if 'exon_id' in d:    
            exon_id=d['exon_id']
    return Name,gene_id,transcript_id,protein_id,exon_id
1088047
def get_assoc_ncbi_taxids(taxids, force_dnld=False, loading_bar=True, **kws):
    """"""
    fin = kws['gene2go'] if 'gene2go' in kws else os.path.join(os.getcwd(), "gene2go")
    dnld_ncbi_gene_file(fin, force_dnld, loading_bar=loading_bar)
    return read_ncbi_gene2go(fin, taxids, **kws)
979570
def _id_handler(self, f):
        

        # If id_spec is a string, convert to iterable for later
        if isinstance(self.id_spec, six.string_types):
            id_key = [self.id_spec]

        elif hasattr(self.id_spec, '__call__'):
            id_key = [self.id_spec]

        # If dict, then assume it's a feature -> attribute mapping, e.g.,
        # {'gene': 'gene_id'} for GTF
        elif isinstance(self.id_spec, dict):
            try:
                id_key = self.id_spec[f.featuretype]
                if isinstance(id_key, six.string_types):
                    id_key = [id_key]

            # Otherwise, use default auto-increment.
            except KeyError:
                return self._increment_featuretype_autoid(f.featuretype)

        # Otherwise assume it's an iterable.
        else:
            id_key = self.id_spec

        # Then try them in order, returning the first one that works:
        for k in id_key:

            if hasattr(k, '__call__'):
                _id = k(f)
                if _id:
                    if _id.startswith('autoincrement:'):
                        return self._increment_featuretype_autoid(_id[14:])
                    return _id
            else:
                # use GFF fields rather than attributes for cases like :seqid:
                # or :strand:
                if (len(k) > 3) and (k[0] == ':') and (k[-1] == ':'):
                    # No [0] here -- only attributes key/vals are forced into
                    # lists, not standard GFF fields.
                    return getattr(f, k[1:-1])
                else:
                    try:
                        return f.attributes[k][0]
                    except (KeyError, IndexError):
                        pass
        # If we get here, then default autoincrement
        return self._increment_featuretype_autoid(f.featuretype)
1248209
def _tegra_id(self):
        """"""
        board_value = self.detector.get_device_model()
        if 'tx1' in board_value:
            return JETSON_TX1
        elif 'quill' in board_value:
            return JETSON_TX2
        elif 'xavier' in board_value:
            return JETSON_XAVIER
        elif 'nano' in board_value:
            return JETSON_NANO
        return None
316366
def get_assc_pruned(assc_geneid2gos, min_genecnt=None, max_genecnt=None, prt=sys.stdout):
    """"""
    # DEFN WAS: get_assc_pruned(assc_geneid2gos, max_genecnt=None, prt=sys.stdout):
    #      ADDED min_genecnt argument and functionality
    if max_genecnt is None and min_genecnt is None:
        return assc_geneid2gos, set()
    go2genes_orig = get_b2aset(assc_geneid2gos)
    # go2genes_prun = {go:gs for go, gs in go2genes_orig.items() if len(gs) <= max_genecnt}
    go2genes_prun = {}
    for goid, genes in go2genes_orig.items():
        num_genes = len(genes)
        if (min_genecnt is None or num_genes >= min_genecnt) and \
           (max_genecnt is None or num_genes <= max_genecnt):
            go2genes_prun[goid] = genes
    num_was = len(go2genes_orig)
    num_now = len(go2genes_prun)
    gos_rm = set(go2genes_orig.keys()).difference(set(go2genes_prun.keys()))
    assert num_was-num_now == len(gos_rm)
    if prt is not None:
        if min_genecnt is None:
            min_genecnt = 1
        if max_genecnt is None:
            max_genecnt = "Max"
        prt.write("{N:4} GO IDs pruned. Kept {NOW} GOs assc w/({m} to {M} genes)\n".format(
            m=min_genecnt, M=max_genecnt, N=num_was-num_now, NOW=num_now))
    return get_b2aset(go2genes_prun), gos_rm
950081
def get_gene_id(gene_name):
    '''

    '''
    from intermine.webservice import Service

    service = Service('http://yeastmine.yeastgenome.org/yeastmine/service')

    # Get a new query on the class (table) you will be querying:
    query = service.new_query('Gene')

    # The view specifies the output columns
    query.add_view('primaryIdentifier', 'secondaryIdentifier', 'symbol',
                   'name', 'sgdAlias', 'crossReferences.identifier',
                   'crossReferences.source.name')

    # Uncomment and edit the line below (the default) to select a custom sort
    # order:
    # query.add_sort_order('Gene.primaryIdentifier', 'ASC')

    # You can edit the constraint values below
    query.add_constraint('organism.shortName', '=', 'S. cerevisiae', code='B')
    query.add_constraint('Gene', 'LOOKUP', gene_name, code='A')

    # Uncomment and edit the code below to specify your own custom logic:
    # query.set_logic('A and B')

    for row in query.rows():
        gid = row['secondaryIdentifier']
    return gid
348334
def getid(self, idtype):
        '''
        
        '''
        memorable_id = None
        while memorable_id in self._ids:
            l=[]
            for _ in range(4):
                l.append(str(randint(0, 19)))
            memorable_id = ''.join(l)
        self._ids.append(memorable_id)
        return idtype + '-' + memorable_id
512104
def nextRefAnalysesGroupID(self, reference):
        
        prefix = reference.id + "-"
        if not IReferenceSample.providedBy(reference):
            # Not a ReferenceSample, so this is a duplicate
            prefix = reference.id + "-D"
        bac = getToolByName(reference, 'bika_analysis_catalog')
        ids = bac.Indexes['getReferenceAnalysesGroupID'].uniqueValues()
        rr = re.compile("^" + prefix + "[\d+]+$")
        ids = [int(i.split(prefix)[1]) for i in ids if i and rr.match(i)]
        ids.sort()
        _id = ids[-1] if ids else 0
        suffix = str(_id + 1).zfill(int(3))
        if not IReferenceSample.providedBy(reference):
            # Not a ReferenceSample, so this is a duplicate
            suffix = str(_id + 1).zfill(2)
        return '%s%s' % (prefix, suffix)
437854
def unique_id(self):
        
        chain = self.ampal_parent.ampal_parent.id
        residue = self.ampal_parent.id
        return chain, residue, self.id
364255
def getUI(prog_name, args):
  """"""
  longDescription = "Given a set of BED intervals, compute a profile of " +\
                    "conservation by averaging over all intervals using a " +\
                    "whole genome alignment to a set of relevent species." +\
                    "\n\n" +\
                    "Usage: " + prog_name + " [options] regions.bed " +\
                    "genome-alig species" +\
                    "\n\n" +\
                    "genome-alig can be either a single MAF file, or a " +\
                    "directory of MAF files. In the latter case, the " +\
                    "directory may also optionally contain index files for " +\
                    "the alignment files."
  shortDescription = longDescription

  ui = CLI(prog_name, shortDescription, longDescription)
  # gotta have two args -- MAF dir/file and BED regions.
  # Input by stdin not allowed
  ui.minArgs = 3
  ui.maxArgs = 4
  ui.addOption(Option(short="o", long="output", argName="filename",
                      description="output to given file, else stdout",
                      required=False, type=str))
  ui.addOption(Option(short="w", long="window", argName="size",
                      description="size of window to compute around each " +
                                  "interval; " +
                                  str(DEFAULT_WINDOW_SIZE) +
                                  " to use whole interval. " +
                                  "Default " + str(DEFAULT_WINDOW_SIZE),
                      required=False, type=int))
  ui.addOption(Option(short="e", long="extensions", argName="extension",
                      description="if genome-alig specifies a directory, " +
                                  "treat files with this extension as " +
                                  "alignment files.", required=False,
                                  type=str))
  ui.addOption(Option(short="i", long="index-extensions", argName="extension",
                      description="if genome-alig specifies a directory, " +
                                  "treat files with this extension as " +
                                  "index files for alignments.",
                                  required=False, type=str))
  ui.addOption(Option(short="f", long="fail-no-index",
                      description="fail if an alignment file without an " +
                                  "index is found; otherwise index-less " +
                                  "alignment files are loaded whole (which " +
                                  "might be slow if they're large, and " +
                                  "might require a lot of memory)",
                      default=False, required=False))
  ui.addOption(Option(short="m", long="missing", argName="strategy",
                      description="how to treat missing sequences in " +
                                  "blocks. Options are " +
                                  ", ".join([str(x.name) for x in
                                             MissingSequenceHandler]),
                                  required=False, type=str))
  ui.addOption(Option(short="s", long="species", argName="species",
                      description="consider only these species. Default is " +
                                  "all.", required=False, type=str))
  ui.addOption(Option(short="v", long="verbose",
                      description="output additional messages to stderr " +
                                  "about run (default: " +
                                  str(DEFAULT_VERBOSITY) + ")",
                      default=DEFAULT_VERBOSITY, required=False))
  ui.addOption(Option(short="h", long="help",
                      description="show this help message ", special=True))
  ui.addOption(Option(short="u", long="test",
                      description="run unit tests ", special=True))

  ui.parseCommandLine(args)
  return ui