id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
242,400 | tanghaibao/goatools | goatools/godag_obosm.py | OboToGoDagSmall._init_go2obj | def _init_go2obj(self, **kws):
"""Initialize go2obj in small dag for source gos."""
if 'goids' in kws and 'obodag' in kws:
self.godag.go_sources = kws['goids']
obo = kws['obodag']
for goid in self.godag.go_sources:
self.godag.go2obj[goid] = obo[goid]
elif 'goid2goobj' in kws:
goid2goobj = kws['goid2goobj']
self.godag.go_sources = goid2goobj.keys()
for goid, goobj in goid2goobj.items():
self.godag.go2obj[goid] = goobj
elif 'goea_results' in kws:
goea_results = kws['goea_results']
self.godag.go_sources = [rec.GO for rec in goea_results]
self.godag.go2obj = {rec.GO:rec.goterm for rec in goea_results} | python | def _init_go2obj(self, **kws):
if 'goids' in kws and 'obodag' in kws:
self.godag.go_sources = kws['goids']
obo = kws['obodag']
for goid in self.godag.go_sources:
self.godag.go2obj[goid] = obo[goid]
elif 'goid2goobj' in kws:
goid2goobj = kws['goid2goobj']
self.godag.go_sources = goid2goobj.keys()
for goid, goobj in goid2goobj.items():
self.godag.go2obj[goid] = goobj
elif 'goea_results' in kws:
goea_results = kws['goea_results']
self.godag.go_sources = [rec.GO for rec in goea_results]
self.godag.go2obj = {rec.GO:rec.goterm for rec in goea_results} | [
"def",
"_init_go2obj",
"(",
"self",
",",
"*",
"*",
"kws",
")",
":",
"if",
"'goids'",
"in",
"kws",
"and",
"'obodag'",
"in",
"kws",
":",
"self",
".",
"godag",
".",
"go_sources",
"=",
"kws",
"[",
"'goids'",
"]",
"obo",
"=",
"kws",
"[",
"'obodag'",
"]"... | Initialize go2obj in small dag for source gos. | [
"Initialize",
"go2obj",
"in",
"small",
"dag",
"for",
"source",
"gos",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag_obosm.py#L28-L43 |
242,401 | tanghaibao/goatools | goatools/godag_obosm.py | OboToGoDagSmall._init | def _init(self):
"""Given GO ids and GOTerm objects, create mini GO dag."""
for goid in self.godag.go_sources:
goobj = self.godag.go2obj[goid]
self.godag.go2obj[goid] = goobj
# Traverse up parents
if self.traverse_parent and goid not in self.seen_cids:
self._traverse_parent_objs(goobj)
# Traverse down children
if self.traverse_child and goid not in self.seen_pids:
self._traverse_child_objs(goobj) | python | def _init(self):
for goid in self.godag.go_sources:
goobj = self.godag.go2obj[goid]
self.godag.go2obj[goid] = goobj
# Traverse up parents
if self.traverse_parent and goid not in self.seen_cids:
self._traverse_parent_objs(goobj)
# Traverse down children
if self.traverse_child and goid not in self.seen_pids:
self._traverse_child_objs(goobj) | [
"def",
"_init",
"(",
"self",
")",
":",
"for",
"goid",
"in",
"self",
".",
"godag",
".",
"go_sources",
":",
"goobj",
"=",
"self",
".",
"godag",
".",
"go2obj",
"[",
"goid",
"]",
"self",
".",
"godag",
".",
"go2obj",
"[",
"goid",
"]",
"=",
"goobj",
"#... | Given GO ids and GOTerm objects, create mini GO dag. | [
"Given",
"GO",
"ids",
"and",
"GOTerm",
"objects",
"create",
"mini",
"GO",
"dag",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag_obosm.py#L45-L55 |
242,402 | tanghaibao/goatools | goatools/rpt/write_hierarchy_base.py | WrHierPrt.prt_hier_rec | def prt_hier_rec(self, item_id, depth=1):
"""Write hierarchy for a GO Term record and all GO IDs down to the leaf level."""
# Shortens hierarchy report by only printing the hierarchy
# for the sub-set of user-specified GO terms which are connected.
if self.include_only and item_id not in self.include_only:
return
obj = self.id2obj[item_id]
# Optionally space the branches for readability
if self.space_branches:
if depth == 1 and obj.children:
self.prt.write("\n")
# Print marks if provided
if self.item_marks:
self.prt.write('{MARK} '.format(
MARK=self.item_marks.get(item_id, self.mark_dflt)))
no_repeat = self.concise_prt and item_id in self.items_printed
# Print content
dashes = self._str_dash(depth, no_repeat, obj)
if self.do_prtfmt:
self._prtfmt(item_id, dashes)
else:
self._prtstr(obj, dashes)
self.items_printed.add(item_id)
self.items_list.append(item_id)
# Do not print hierarchy below this turn if it has already been printed
if no_repeat:
return
depth += 1
if self.max_indent is not None and depth > self.max_indent:
return
children = obj.children if self.sortby is None else sorted(obj.children, key=self.sortby)
for child in children:
self.prt_hier_rec(child.item_id, depth) | python | def prt_hier_rec(self, item_id, depth=1):
# Shortens hierarchy report by only printing the hierarchy
# for the sub-set of user-specified GO terms which are connected.
if self.include_only and item_id not in self.include_only:
return
obj = self.id2obj[item_id]
# Optionally space the branches for readability
if self.space_branches:
if depth == 1 and obj.children:
self.prt.write("\n")
# Print marks if provided
if self.item_marks:
self.prt.write('{MARK} '.format(
MARK=self.item_marks.get(item_id, self.mark_dflt)))
no_repeat = self.concise_prt and item_id in self.items_printed
# Print content
dashes = self._str_dash(depth, no_repeat, obj)
if self.do_prtfmt:
self._prtfmt(item_id, dashes)
else:
self._prtstr(obj, dashes)
self.items_printed.add(item_id)
self.items_list.append(item_id)
# Do not print hierarchy below this turn if it has already been printed
if no_repeat:
return
depth += 1
if self.max_indent is not None and depth > self.max_indent:
return
children = obj.children if self.sortby is None else sorted(obj.children, key=self.sortby)
for child in children:
self.prt_hier_rec(child.item_id, depth) | [
"def",
"prt_hier_rec",
"(",
"self",
",",
"item_id",
",",
"depth",
"=",
"1",
")",
":",
"# Shortens hierarchy report by only printing the hierarchy",
"# for the sub-set of user-specified GO terms which are connected.",
"if",
"self",
".",
"include_only",
"and",
"item_id",
"not",... | Write hierarchy for a GO Term record and all GO IDs down to the leaf level. | [
"Write",
"hierarchy",
"for",
"a",
"GO",
"Term",
"record",
"and",
"all",
"GO",
"IDs",
"down",
"to",
"the",
"leaf",
"level",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/rpt/write_hierarchy_base.py#L34-L68 |
242,403 | tanghaibao/goatools | goatools/rpt/write_hierarchy_base.py | WrHierPrt._init_item_marks | def _init_item_marks(item_marks):
"""Initialize the makred item dict."""
if isinstance(item_marks, dict):
return item_marks
if item_marks:
return {item_id:'>' for item_id in item_marks} | python | def _init_item_marks(item_marks):
if isinstance(item_marks, dict):
return item_marks
if item_marks:
return {item_id:'>' for item_id in item_marks} | [
"def",
"_init_item_marks",
"(",
"item_marks",
")",
":",
"if",
"isinstance",
"(",
"item_marks",
",",
"dict",
")",
":",
"return",
"item_marks",
"if",
"item_marks",
":",
"return",
"{",
"item_id",
":",
"'>'",
"for",
"item_id",
"in",
"item_marks",
"}"
] | Initialize the makred item dict. | [
"Initialize",
"the",
"makred",
"item",
"dict",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/rpt/write_hierarchy_base.py#L97-L102 |
242,404 | tanghaibao/goatools | goatools/obo_parser.py | OBOReader._add_to_obj | def _add_to_obj(self, rec_curr, typedef_curr, line):
"""Add information on line to GOTerm or Typedef."""
if rec_curr is not None:
self._add_to_ref(rec_curr, line)
else:
add_to_typedef(typedef_curr, line) | python | def _add_to_obj(self, rec_curr, typedef_curr, line):
if rec_curr is not None:
self._add_to_ref(rec_curr, line)
else:
add_to_typedef(typedef_curr, line) | [
"def",
"_add_to_obj",
"(",
"self",
",",
"rec_curr",
",",
"typedef_curr",
",",
"line",
")",
":",
"if",
"rec_curr",
"is",
"not",
"None",
":",
"self",
".",
"_add_to_ref",
"(",
"rec_curr",
",",
"line",
")",
"else",
":",
"add_to_typedef",
"(",
"typedef_curr",
... | Add information on line to GOTerm or Typedef. | [
"Add",
"information",
"on",
"line",
"to",
"GOTerm",
"or",
"Typedef",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L87-L92 |
242,405 | tanghaibao/goatools | goatools/obo_parser.py | OBOReader._init_obo_version | def _init_obo_version(self, line):
"""Save obo version and release."""
if line[0:14] == "format-version":
self.format_version = line[16:-1]
if line[0:12] == "data-version":
self.data_version = line[14:-1] | python | def _init_obo_version(self, line):
if line[0:14] == "format-version":
self.format_version = line[16:-1]
if line[0:12] == "data-version":
self.data_version = line[14:-1] | [
"def",
"_init_obo_version",
"(",
"self",
",",
"line",
")",
":",
"if",
"line",
"[",
"0",
":",
"14",
"]",
"==",
"\"format-version\"",
":",
"self",
".",
"format_version",
"=",
"line",
"[",
"16",
":",
"-",
"1",
"]",
"if",
"line",
"[",
"0",
":",
"12",
... | Save obo version and release. | [
"Save",
"obo",
"version",
"and",
"release",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L94-L99 |
242,406 | tanghaibao/goatools | goatools/obo_parser.py | OBOReader._init_optional_attrs | def _init_optional_attrs(optional_attrs):
"""Create OboOptionalAttrs or return None."""
if optional_attrs is None:
return None
opts = OboOptionalAttrs.get_optional_attrs(optional_attrs)
if opts:
return OboOptionalAttrs(opts) | python | def _init_optional_attrs(optional_attrs):
if optional_attrs is None:
return None
opts = OboOptionalAttrs.get_optional_attrs(optional_attrs)
if opts:
return OboOptionalAttrs(opts) | [
"def",
"_init_optional_attrs",
"(",
"optional_attrs",
")",
":",
"if",
"optional_attrs",
"is",
"None",
":",
"return",
"None",
"opts",
"=",
"OboOptionalAttrs",
".",
"get_optional_attrs",
"(",
"optional_attrs",
")",
"if",
"opts",
":",
"return",
"OboOptionalAttrs",
"(... | Create OboOptionalAttrs or return None. | [
"Create",
"OboOptionalAttrs",
"or",
"return",
"None",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L130-L136 |
242,407 | tanghaibao/goatools | goatools/obo_parser.py | GOTerm.has_parent | def has_parent(self, term):
"""Return True if this GO object has a parent GO ID."""
for parent in self.parents:
if parent.item_id == term or parent.has_parent(term):
return True
return False | python | def has_parent(self, term):
for parent in self.parents:
if parent.item_id == term or parent.has_parent(term):
return True
return False | [
"def",
"has_parent",
"(",
"self",
",",
"term",
")",
":",
"for",
"parent",
"in",
"self",
".",
"parents",
":",
"if",
"parent",
".",
"item_id",
"==",
"term",
"or",
"parent",
".",
"has_parent",
"(",
"term",
")",
":",
"return",
"True",
"return",
"False"
] | Return True if this GO object has a parent GO ID. | [
"Return",
"True",
"if",
"this",
"GO",
"object",
"has",
"a",
"parent",
"GO",
"ID",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L191-L196 |
242,408 | tanghaibao/goatools | goatools/obo_parser.py | GOTerm.has_child | def has_child(self, term):
"""Return True if this GO object has a child GO ID."""
for parent in self.children:
if parent.item_id == term or parent.has_child(term):
return True
return False | python | def has_child(self, term):
for parent in self.children:
if parent.item_id == term or parent.has_child(term):
return True
return False | [
"def",
"has_child",
"(",
"self",
",",
"term",
")",
":",
"for",
"parent",
"in",
"self",
".",
"children",
":",
"if",
"parent",
".",
"item_id",
"==",
"term",
"or",
"parent",
".",
"has_child",
"(",
"term",
")",
":",
"return",
"True",
"return",
"False"
] | Return True if this GO object has a child GO ID. | [
"Return",
"True",
"if",
"this",
"GO",
"object",
"has",
"a",
"child",
"GO",
"ID",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L198-L203 |
242,409 | tanghaibao/goatools | goatools/obo_parser.py | GOTerm.get_all_parents | def get_all_parents(self):
"""Return all parent GO IDs."""
all_parents = set()
for parent in self.parents:
all_parents.add(parent.item_id)
all_parents |= parent.get_all_parents()
return all_parents | python | def get_all_parents(self):
all_parents = set()
for parent in self.parents:
all_parents.add(parent.item_id)
all_parents |= parent.get_all_parents()
return all_parents | [
"def",
"get_all_parents",
"(",
"self",
")",
":",
"all_parents",
"=",
"set",
"(",
")",
"for",
"parent",
"in",
"self",
".",
"parents",
":",
"all_parents",
".",
"add",
"(",
"parent",
".",
"item_id",
")",
"all_parents",
"|=",
"parent",
".",
"get_all_parents",
... | Return all parent GO IDs. | [
"Return",
"all",
"parent",
"GO",
"IDs",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L205-L211 |
242,410 | tanghaibao/goatools | goatools/obo_parser.py | GOTerm.get_all_upper | def get_all_upper(self):
"""Return all parent GO IDs through both 'is_a' and all relationships."""
all_upper = set()
for upper in self.get_goterms_upper():
all_upper.add(upper.item_id)
all_upper |= upper.get_all_upper()
return all_upper | python | def get_all_upper(self):
all_upper = set()
for upper in self.get_goterms_upper():
all_upper.add(upper.item_id)
all_upper |= upper.get_all_upper()
return all_upper | [
"def",
"get_all_upper",
"(",
"self",
")",
":",
"all_upper",
"=",
"set",
"(",
")",
"for",
"upper",
"in",
"self",
".",
"get_goterms_upper",
"(",
")",
":",
"all_upper",
".",
"add",
"(",
"upper",
".",
"item_id",
")",
"all_upper",
"|=",
"upper",
".",
"get_a... | Return all parent GO IDs through both 'is_a' and all relationships. | [
"Return",
"all",
"parent",
"GO",
"IDs",
"through",
"both",
"is_a",
"and",
"all",
"relationships",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L213-L219 |
242,411 | tanghaibao/goatools | goatools/obo_parser.py | GOTerm.get_all_children | def get_all_children(self):
"""Return all children GO IDs."""
all_children = set()
for parent in self.children:
all_children.add(parent.item_id)
all_children |= parent.get_all_children()
return all_children | python | def get_all_children(self):
all_children = set()
for parent in self.children:
all_children.add(parent.item_id)
all_children |= parent.get_all_children()
return all_children | [
"def",
"get_all_children",
"(",
"self",
")",
":",
"all_children",
"=",
"set",
"(",
")",
"for",
"parent",
"in",
"self",
".",
"children",
":",
"all_children",
".",
"add",
"(",
"parent",
".",
"item_id",
")",
"all_children",
"|=",
"parent",
".",
"get_all_child... | Return all children GO IDs. | [
"Return",
"all",
"children",
"GO",
"IDs",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L221-L227 |
242,412 | tanghaibao/goatools | goatools/obo_parser.py | GOTerm.get_all_lower | def get_all_lower(self):
"""Return all parent GO IDs through both reverse 'is_a' and all relationships."""
all_lower = set()
for lower in self.get_goterms_lower():
all_lower.add(lower.item_id)
all_lower |= lower.get_all_lower()
return all_lower | python | def get_all_lower(self):
all_lower = set()
for lower in self.get_goterms_lower():
all_lower.add(lower.item_id)
all_lower |= lower.get_all_lower()
return all_lower | [
"def",
"get_all_lower",
"(",
"self",
")",
":",
"all_lower",
"=",
"set",
"(",
")",
"for",
"lower",
"in",
"self",
".",
"get_goterms_lower",
"(",
")",
":",
"all_lower",
".",
"add",
"(",
"lower",
".",
"item_id",
")",
"all_lower",
"|=",
"lower",
".",
"get_a... | Return all parent GO IDs through both reverse 'is_a' and all relationships. | [
"Return",
"all",
"parent",
"GO",
"IDs",
"through",
"both",
"reverse",
"is_a",
"and",
"all",
"relationships",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L229-L235 |
242,413 | tanghaibao/goatools | goatools/obo_parser.py | GOTerm.get_all_parent_edges | def get_all_parent_edges(self):
"""Return tuples for all parent GO IDs, containing current GO ID and parent GO ID."""
all_parent_edges = set()
for parent in self.parents:
all_parent_edges.add((self.item_id, parent.item_id))
all_parent_edges |= parent.get_all_parent_edges()
return all_parent_edges | python | def get_all_parent_edges(self):
all_parent_edges = set()
for parent in self.parents:
all_parent_edges.add((self.item_id, parent.item_id))
all_parent_edges |= parent.get_all_parent_edges()
return all_parent_edges | [
"def",
"get_all_parent_edges",
"(",
"self",
")",
":",
"all_parent_edges",
"=",
"set",
"(",
")",
"for",
"parent",
"in",
"self",
".",
"parents",
":",
"all_parent_edges",
".",
"add",
"(",
"(",
"self",
".",
"item_id",
",",
"parent",
".",
"item_id",
")",
")",... | Return tuples for all parent GO IDs, containing current GO ID and parent GO ID. | [
"Return",
"tuples",
"for",
"all",
"parent",
"GO",
"IDs",
"containing",
"current",
"GO",
"ID",
"and",
"parent",
"GO",
"ID",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L237-L243 |
242,414 | tanghaibao/goatools | goatools/obo_parser.py | GOTerm.get_all_child_edges | def get_all_child_edges(self):
"""Return tuples for all child GO IDs, containing current GO ID and child GO ID."""
all_child_edges = set()
for parent in self.children:
all_child_edges.add((parent.item_id, self.item_id))
all_child_edges |= parent.get_all_child_edges()
return all_child_edges | python | def get_all_child_edges(self):
all_child_edges = set()
for parent in self.children:
all_child_edges.add((parent.item_id, self.item_id))
all_child_edges |= parent.get_all_child_edges()
return all_child_edges | [
"def",
"get_all_child_edges",
"(",
"self",
")",
":",
"all_child_edges",
"=",
"set",
"(",
")",
"for",
"parent",
"in",
"self",
".",
"children",
":",
"all_child_edges",
".",
"add",
"(",
"(",
"parent",
".",
"item_id",
",",
"self",
".",
"item_id",
")",
")",
... | Return tuples for all child GO IDs, containing current GO ID and child GO ID. | [
"Return",
"tuples",
"for",
"all",
"child",
"GO",
"IDs",
"containing",
"current",
"GO",
"ID",
"and",
"child",
"GO",
"ID",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L245-L251 |
242,415 | tanghaibao/goatools | goatools/obo_parser.py | GODag.load_obo_file | def load_obo_file(self, obo_file, optional_attrs, load_obsolete, prt):
"""Read obo file. Store results."""
reader = OBOReader(obo_file, optional_attrs)
# Save alt_ids and their corresponding main GO ID. Add to GODag after populating GO Terms
alt2rec = {}
for rec in reader:
# Save record if:
# 1) Argument load_obsolete is True OR
# 2) Argument load_obsolete is False and the GO term is "live" (not obsolete)
if load_obsolete or not rec.is_obsolete:
self[rec.item_id] = rec
for alt in rec.alt_ids:
alt2rec[alt] = rec
# Save the typedefs and parsed optional_attrs
# self.optobj = reader.optobj
self.typedefs = reader.typedefs
self._populate_terms(reader.optobj)
self._set_level_depth(reader.optobj)
# Add alt_ids to go2obj
for goid_alt, rec in alt2rec.items():
self[goid_alt] = rec
desc = self._str_desc(reader)
if prt is not None:
prt.write("{DESC}\n".format(DESC=desc))
return desc | python | def load_obo_file(self, obo_file, optional_attrs, load_obsolete, prt):
reader = OBOReader(obo_file, optional_attrs)
# Save alt_ids and their corresponding main GO ID. Add to GODag after populating GO Terms
alt2rec = {}
for rec in reader:
# Save record if:
# 1) Argument load_obsolete is True OR
# 2) Argument load_obsolete is False and the GO term is "live" (not obsolete)
if load_obsolete or not rec.is_obsolete:
self[rec.item_id] = rec
for alt in rec.alt_ids:
alt2rec[alt] = rec
# Save the typedefs and parsed optional_attrs
# self.optobj = reader.optobj
self.typedefs = reader.typedefs
self._populate_terms(reader.optobj)
self._set_level_depth(reader.optobj)
# Add alt_ids to go2obj
for goid_alt, rec in alt2rec.items():
self[goid_alt] = rec
desc = self._str_desc(reader)
if prt is not None:
prt.write("{DESC}\n".format(DESC=desc))
return desc | [
"def",
"load_obo_file",
"(",
"self",
",",
"obo_file",
",",
"optional_attrs",
",",
"load_obsolete",
",",
"prt",
")",
":",
"reader",
"=",
"OBOReader",
"(",
"obo_file",
",",
"optional_attrs",
")",
"# Save alt_ids and their corresponding main GO ID. Add to GODag after populat... | Read obo file. Store results. | [
"Read",
"obo",
"file",
".",
"Store",
"results",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L312-L340 |
242,416 | tanghaibao/goatools | goatools/obo_parser.py | GODag._str_desc | def _str_desc(self, reader):
"""String containing information about the current GO DAG."""
data_version = reader.data_version
if data_version is not None:
data_version = data_version.replace("releases/", "")
desc = "{OBO}: fmt({FMT}) rel({REL}) {N:,} GO Terms".format(
OBO=reader.obo_file, FMT=reader.format_version,
REL=data_version, N=len(self))
if reader.optobj:
desc = "{D}; optional_attrs({A})".format(D=desc, A=" ".join(sorted(reader.optobj.optional_attrs)))
return desc | python | def _str_desc(self, reader):
data_version = reader.data_version
if data_version is not None:
data_version = data_version.replace("releases/", "")
desc = "{OBO}: fmt({FMT}) rel({REL}) {N:,} GO Terms".format(
OBO=reader.obo_file, FMT=reader.format_version,
REL=data_version, N=len(self))
if reader.optobj:
desc = "{D}; optional_attrs({A})".format(D=desc, A=" ".join(sorted(reader.optobj.optional_attrs)))
return desc | [
"def",
"_str_desc",
"(",
"self",
",",
"reader",
")",
":",
"data_version",
"=",
"reader",
".",
"data_version",
"if",
"data_version",
"is",
"not",
"None",
":",
"data_version",
"=",
"data_version",
".",
"replace",
"(",
"\"releases/\"",
",",
"\"\"",
")",
"desc",... | String containing information about the current GO DAG. | [
"String",
"containing",
"information",
"about",
"the",
"current",
"GO",
"DAG",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L342-L352 |
242,417 | tanghaibao/goatools | goatools/obo_parser.py | GODag._populate_terms | def _populate_terms(self, optobj):
"""Convert GO IDs to GO Term record objects. Populate children."""
has_relationship = optobj is not None and 'relationship' in optobj.optional_attrs
# Make parents and relationships references to the actual GO terms.
for rec in self.values():
# Given parent GO IDs, set parent GO Term objects
rec.parents = set([self[goid] for goid in rec._parents])
# For each parent GO Term object, add it's child GO Term to the children data member
for parent_rec in rec.parents:
parent_rec.children.add(rec)
if has_relationship:
self._populate_relationships(rec) | python | def _populate_terms(self, optobj):
has_relationship = optobj is not None and 'relationship' in optobj.optional_attrs
# Make parents and relationships references to the actual GO terms.
for rec in self.values():
# Given parent GO IDs, set parent GO Term objects
rec.parents = set([self[goid] for goid in rec._parents])
# For each parent GO Term object, add it's child GO Term to the children data member
for parent_rec in rec.parents:
parent_rec.children.add(rec)
if has_relationship:
self._populate_relationships(rec) | [
"def",
"_populate_terms",
"(",
"self",
",",
"optobj",
")",
":",
"has_relationship",
"=",
"optobj",
"is",
"not",
"None",
"and",
"'relationship'",
"in",
"optobj",
".",
"optional_attrs",
"# Make parents and relationships references to the actual GO terms.",
"for",
"rec",
"... | Convert GO IDs to GO Term record objects. Populate children. | [
"Convert",
"GO",
"IDs",
"to",
"GO",
"Term",
"record",
"objects",
".",
"Populate",
"children",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L355-L368 |
242,418 | tanghaibao/goatools | goatools/obo_parser.py | GODag._populate_relationships | def _populate_relationships(self, rec_curr):
"""Convert GO IDs in relationships to GO Term record objects. Populate children."""
for relationship_type, goids in rec_curr.relationship.items():
parent_recs = set([self[goid] for goid in goids])
rec_curr.relationship[relationship_type] = parent_recs
for parent_rec in parent_recs:
if relationship_type not in parent_rec.relationship_rev:
parent_rec.relationship_rev[relationship_type] = set([rec_curr])
else:
parent_rec.relationship_rev[relationship_type].add(rec_curr) | python | def _populate_relationships(self, rec_curr):
for relationship_type, goids in rec_curr.relationship.items():
parent_recs = set([self[goid] for goid in goids])
rec_curr.relationship[relationship_type] = parent_recs
for parent_rec in parent_recs:
if relationship_type not in parent_rec.relationship_rev:
parent_rec.relationship_rev[relationship_type] = set([rec_curr])
else:
parent_rec.relationship_rev[relationship_type].add(rec_curr) | [
"def",
"_populate_relationships",
"(",
"self",
",",
"rec_curr",
")",
":",
"for",
"relationship_type",
",",
"goids",
"in",
"rec_curr",
".",
"relationship",
".",
"items",
"(",
")",
":",
"parent_recs",
"=",
"set",
"(",
"[",
"self",
"[",
"goid",
"]",
"for",
... | Convert GO IDs in relationships to GO Term record objects. Populate children. | [
"Convert",
"GO",
"IDs",
"in",
"relationships",
"to",
"GO",
"Term",
"record",
"objects",
".",
"Populate",
"children",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L370-L379 |
242,419 | tanghaibao/goatools | goatools/obo_parser.py | GODag._set_level_depth | def _set_level_depth(self, optobj):
"""Set level, depth and add inverted relationships."""
has_relationship = optobj is not None and 'relationship' in optobj.optional_attrs
def _init_level(rec):
if rec.level is None:
if rec.parents:
rec.level = min(_init_level(rec) for rec in rec.parents) + 1
else:
rec.level = 0
return rec.level
def _init_depth(rec):
if rec.depth is None:
if rec.parents:
rec.depth = max(_init_depth(rec) for rec in rec.parents) + 1
else:
rec.depth = 0
return rec.depth
def _init_reldepth(rec):
if not hasattr(rec, 'reldepth'):
up_terms = rec.get_goterms_upper()
if up_terms:
rec.reldepth = max(_init_reldepth(rec) for rec in up_terms) + 1
else:
rec.reldepth = 0
return rec.reldepth
for rec in self.values():
# Add invert relationships
if has_relationship:
if rec.depth is None:
_init_reldepth(rec)
# print("BBBBBBBBBBB1", rec.item_id, rec.relationship)
#for (typedef, terms) in rec.relationship.items():
# invert_typedef = self.typedefs[typedef].inverse_of
# # print("BBBBBBBBBBB2 {} ({}) ({}) ({})".format(
# # rec.item_id, rec.relationship, typedef, invert_typedef))
# if invert_typedef:
# # Add inverted relationship
# for term in terms:
# if not hasattr(term, 'relationship'):
# term.relationship = defaultdict(set)
# term.relationship[invert_typedef].add(rec)
# print("BBBBBBBBBBB3", rec.item_id, rec.relationship)
if rec.level is None:
_init_level(rec)
if rec.depth is None:
_init_depth(rec) | python | def _set_level_depth(self, optobj):
has_relationship = optobj is not None and 'relationship' in optobj.optional_attrs
def _init_level(rec):
if rec.level is None:
if rec.parents:
rec.level = min(_init_level(rec) for rec in rec.parents) + 1
else:
rec.level = 0
return rec.level
def _init_depth(rec):
if rec.depth is None:
if rec.parents:
rec.depth = max(_init_depth(rec) for rec in rec.parents) + 1
else:
rec.depth = 0
return rec.depth
def _init_reldepth(rec):
if not hasattr(rec, 'reldepth'):
up_terms = rec.get_goterms_upper()
if up_terms:
rec.reldepth = max(_init_reldepth(rec) for rec in up_terms) + 1
else:
rec.reldepth = 0
return rec.reldepth
for rec in self.values():
# Add invert relationships
if has_relationship:
if rec.depth is None:
_init_reldepth(rec)
# print("BBBBBBBBBBB1", rec.item_id, rec.relationship)
#for (typedef, terms) in rec.relationship.items():
# invert_typedef = self.typedefs[typedef].inverse_of
# # print("BBBBBBBBBBB2 {} ({}) ({}) ({})".format(
# # rec.item_id, rec.relationship, typedef, invert_typedef))
# if invert_typedef:
# # Add inverted relationship
# for term in terms:
# if not hasattr(term, 'relationship'):
# term.relationship = defaultdict(set)
# term.relationship[invert_typedef].add(rec)
# print("BBBBBBBBBBB3", rec.item_id, rec.relationship)
if rec.level is None:
_init_level(rec)
if rec.depth is None:
_init_depth(rec) | [
"def",
"_set_level_depth",
"(",
"self",
",",
"optobj",
")",
":",
"has_relationship",
"=",
"optobj",
"is",
"not",
"None",
"and",
"'relationship'",
"in",
"optobj",
".",
"optional_attrs",
"def",
"_init_level",
"(",
"rec",
")",
":",
"if",
"rec",
".",
"level",
... | Set level, depth and add inverted relationships. | [
"Set",
"level",
"depth",
"and",
"add",
"inverted",
"relationships",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L381-L434 |
242,420 | tanghaibao/goatools | goatools/obo_parser.py | GODag.write_dag | def write_dag(self, out=sys.stdout):
"""Write info for all GO Terms in obo file, sorted numerically."""
for rec in sorted(self.values()):
print(rec, file=out) | python | def write_dag(self, out=sys.stdout):
for rec in sorted(self.values()):
print(rec, file=out) | [
"def",
"write_dag",
"(",
"self",
",",
"out",
"=",
"sys",
".",
"stdout",
")",
":",
"for",
"rec",
"in",
"sorted",
"(",
"self",
".",
"values",
"(",
")",
")",
":",
"print",
"(",
"rec",
",",
"file",
"=",
"out",
")"
] | Write info for all GO Terms in obo file, sorted numerically. | [
"Write",
"info",
"for",
"all",
"GO",
"Terms",
"in",
"obo",
"file",
"sorted",
"numerically",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L436-L439 |
242,421 | tanghaibao/goatools | goatools/obo_parser.py | GODag.query_term | def query_term(self, term, verbose=False):
"""Given a GO ID, return GO object."""
if term not in self:
sys.stderr.write("Term %s not found!\n" % term)
return
rec = self[term]
if verbose:
print(rec)
sys.stderr.write("all parents: {}\n".format(
repr(rec.get_all_parents())))
sys.stderr.write("all children: {}\n".format(
repr(rec.get_all_children())))
return rec | python | def query_term(self, term, verbose=False):
if term not in self:
sys.stderr.write("Term %s not found!\n" % term)
return
rec = self[term]
if verbose:
print(rec)
sys.stderr.write("all parents: {}\n".format(
repr(rec.get_all_parents())))
sys.stderr.write("all children: {}\n".format(
repr(rec.get_all_children())))
return rec | [
"def",
"query_term",
"(",
"self",
",",
"term",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"term",
"not",
"in",
"self",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Term %s not found!\\n\"",
"%",
"term",
")",
"return",
"rec",
"=",
"self",
"[",
... | Given a GO ID, return GO object. | [
"Given",
"a",
"GO",
"ID",
"return",
"GO",
"object",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L461-L474 |
242,422 | tanghaibao/goatools | goatools/obo_parser.py | GODag.label_wrap | def label_wrap(self, label):
"""Label text for plot."""
wrapped_label = r"%s\n%s" % (label,
self[label].name.replace(",", r"\n"))
return wrapped_label | python | def label_wrap(self, label):
wrapped_label = r"%s\n%s" % (label,
self[label].name.replace(",", r"\n"))
return wrapped_label | [
"def",
"label_wrap",
"(",
"self",
",",
"label",
")",
":",
"wrapped_label",
"=",
"r\"%s\\n%s\"",
"%",
"(",
"label",
",",
"self",
"[",
"label",
"]",
".",
"name",
".",
"replace",
"(",
"\",\"",
",",
"r\"\\n\"",
")",
")",
"return",
"wrapped_label"
] | Label text for plot. | [
"Label",
"text",
"for",
"plot",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L512-L516 |
242,423 | tanghaibao/goatools | goatools/obo_parser.py | GODag.make_graph_pygraphviz | def make_graph_pygraphviz(self, recs, nodecolor,
edgecolor, dpi,
draw_parents=True, draw_children=True):
"""Draw AMIGO style network, lineage containing one query record."""
import pygraphviz as pgv
grph = pgv.AGraph(name="GO tree")
edgeset = set()
for rec in recs:
if draw_parents:
edgeset.update(rec.get_all_parent_edges())
if draw_children:
edgeset.update(rec.get_all_child_edges())
edgeset = [(self.label_wrap(a), self.label_wrap(b))
for (a, b) in edgeset]
# add nodes explicitly via add_node
# adding nodes implicitly via add_edge misses nodes
# without at least one edge
for rec in recs:
grph.add_node(self.label_wrap(rec.item_id))
for src, target in edgeset:
# default layout in graphviz is top->bottom, so we invert
# the direction and plot using dir="back"
grph.add_edge(target, src)
grph.graph_attr.update(dpi="%d" % dpi)
grph.node_attr.update(shape="box", style="rounded,filled",
fillcolor="beige", color=nodecolor)
grph.edge_attr.update(shape="normal", color=edgecolor,
dir="back", label="is_a")
# highlight the query terms
for rec in recs:
try:
node = grph.get_node(self.label_wrap(rec.item_id))
node.attr.update(fillcolor="plum")
except:
continue
return grph | python | def make_graph_pygraphviz(self, recs, nodecolor,
edgecolor, dpi,
draw_parents=True, draw_children=True):
import pygraphviz as pgv
grph = pgv.AGraph(name="GO tree")
edgeset = set()
for rec in recs:
if draw_parents:
edgeset.update(rec.get_all_parent_edges())
if draw_children:
edgeset.update(rec.get_all_child_edges())
edgeset = [(self.label_wrap(a), self.label_wrap(b))
for (a, b) in edgeset]
# add nodes explicitly via add_node
# adding nodes implicitly via add_edge misses nodes
# without at least one edge
for rec in recs:
grph.add_node(self.label_wrap(rec.item_id))
for src, target in edgeset:
# default layout in graphviz is top->bottom, so we invert
# the direction and plot using dir="back"
grph.add_edge(target, src)
grph.graph_attr.update(dpi="%d" % dpi)
grph.node_attr.update(shape="box", style="rounded,filled",
fillcolor="beige", color=nodecolor)
grph.edge_attr.update(shape="normal", color=edgecolor,
dir="back", label="is_a")
# highlight the query terms
for rec in recs:
try:
node = grph.get_node(self.label_wrap(rec.item_id))
node.attr.update(fillcolor="plum")
except:
continue
return grph | [
"def",
"make_graph_pygraphviz",
"(",
"self",
",",
"recs",
",",
"nodecolor",
",",
"edgecolor",
",",
"dpi",
",",
"draw_parents",
"=",
"True",
",",
"draw_children",
"=",
"True",
")",
":",
"import",
"pygraphviz",
"as",
"pgv",
"grph",
"=",
"pgv",
".",
"AGraph",... | Draw AMIGO style network, lineage containing one query record. | [
"Draw",
"AMIGO",
"style",
"network",
"lineage",
"containing",
"one",
"query",
"record",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L557-L599 |
242,424 | tanghaibao/goatools | goatools/obo_parser.py | GODag.draw_lineage | def draw_lineage(self, recs, nodecolor="mediumseagreen",
edgecolor="lightslateblue", dpi=96,
lineage_img="GO_lineage.png", engine="pygraphviz",
gml=False, draw_parents=True, draw_children=True):
"""Draw GO DAG subplot."""
assert engine in GraphEngines
grph = None
if engine == "pygraphviz":
grph = self.make_graph_pygraphviz(recs, nodecolor, edgecolor, dpi,
draw_parents=draw_parents,
draw_children=draw_children)
else:
grph = self.make_graph_pydot(recs, nodecolor, edgecolor, dpi,
draw_parents=draw_parents, draw_children=draw_children)
if gml:
import networkx as nx # use networkx to do the conversion
gmlbase = lineage_img.rsplit(".", 1)[0]
obj = nx.from_agraph(grph) if engine == "pygraphviz" else nx.from_pydot(grph)
del obj.graph['node']
del obj.graph['edge']
gmlfile = gmlbase + ".gml"
nx.write_gml(self.label_wrap, gmlfile)
sys.stderr.write("GML graph written to {0}\n".format(gmlfile))
sys.stderr.write(("lineage info for terms %s written to %s\n" %
([rec.item_id for rec in recs], lineage_img)))
if engine == "pygraphviz":
grph.draw(lineage_img, prog="dot")
else:
grph.write_png(lineage_img) | python | def draw_lineage(self, recs, nodecolor="mediumseagreen",
edgecolor="lightslateblue", dpi=96,
lineage_img="GO_lineage.png", engine="pygraphviz",
gml=False, draw_parents=True, draw_children=True):
assert engine in GraphEngines
grph = None
if engine == "pygraphviz":
grph = self.make_graph_pygraphviz(recs, nodecolor, edgecolor, dpi,
draw_parents=draw_parents,
draw_children=draw_children)
else:
grph = self.make_graph_pydot(recs, nodecolor, edgecolor, dpi,
draw_parents=draw_parents, draw_children=draw_children)
if gml:
import networkx as nx # use networkx to do the conversion
gmlbase = lineage_img.rsplit(".", 1)[0]
obj = nx.from_agraph(grph) if engine == "pygraphviz" else nx.from_pydot(grph)
del obj.graph['node']
del obj.graph['edge']
gmlfile = gmlbase + ".gml"
nx.write_gml(self.label_wrap, gmlfile)
sys.stderr.write("GML graph written to {0}\n".format(gmlfile))
sys.stderr.write(("lineage info for terms %s written to %s\n" %
([rec.item_id for rec in recs], lineage_img)))
if engine == "pygraphviz":
grph.draw(lineage_img, prog="dot")
else:
grph.write_png(lineage_img) | [
"def",
"draw_lineage",
"(",
"self",
",",
"recs",
",",
"nodecolor",
"=",
"\"mediumseagreen\"",
",",
"edgecolor",
"=",
"\"lightslateblue\"",
",",
"dpi",
"=",
"96",
",",
"lineage_img",
"=",
"\"GO_lineage.png\"",
",",
"engine",
"=",
"\"pygraphviz\"",
",",
"gml",
"... | Draw GO DAG subplot. | [
"Draw",
"GO",
"DAG",
"subplot",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L601-L633 |
242,425 | tanghaibao/goatools | goatools/anno/init/reader_gpad.py | InitAssc._get_ntgpadvals | def _get_ntgpadvals(self, flds, add_ns):
"""Convert fields from string to preferred format for GPAD ver 2.1 and 2.0."""
is_set = False
qualifiers = self._get_qualifier(flds[2])
assert flds[3][:3] == 'GO:', 'UNRECOGNIZED GO({GO})'.format(GO=flds[3])
db_reference = self._rd_fld_vals("DB_Reference", flds[4], is_set, 1)
assert flds[5][:4] == 'ECO:', 'UNRECOGNIZED ECO({ECO})'.format(ECO=flds[3])
with_from = self._rd_fld_vals("With_From", flds[6], is_set)
taxons = self._get_taxon(flds[7])
assert flds[8].isdigit(), 'UNRECOGNIZED DATE({D})'.format(D=flds[8])
assert flds[9], '"Assigned By" VALUE WAS NOT FOUND'
props = self._get_properties(flds[11])
self._chk_qty_eq_1(flds, [0, 1, 3, 5, 8, 9])
# Additional Formatting
self._chk_qualifier(qualifiers)
# Create list of values
eco = flds[5]
goid = flds[3]
gpadvals = [
flds[0], # 0 DB
flds[1], # 1 DB_ID
qualifiers, # 3 Qualifier
flds[3], # 4 GO_ID
db_reference, # 5 DB_Reference
eco, # 6 ECO
ECO2GRP[eco],
with_from, # 7 With_From
taxons, # 12 Taxon
GET_DATE_YYYYMMDD(flds[8]), # 13 Date
flds[9], # 14 Assigned_By
get_extensions(flds[10]), # 12 Extension
props] # 12 Annotation_Properties
if add_ns:
goobj = self.godag.get(goid, '')
gpadvals.append(NAMESPACE2NS[goobj.namespace] if goobj else '')
return gpadvals | python | def _get_ntgpadvals(self, flds, add_ns):
is_set = False
qualifiers = self._get_qualifier(flds[2])
assert flds[3][:3] == 'GO:', 'UNRECOGNIZED GO({GO})'.format(GO=flds[3])
db_reference = self._rd_fld_vals("DB_Reference", flds[4], is_set, 1)
assert flds[5][:4] == 'ECO:', 'UNRECOGNIZED ECO({ECO})'.format(ECO=flds[3])
with_from = self._rd_fld_vals("With_From", flds[6], is_set)
taxons = self._get_taxon(flds[7])
assert flds[8].isdigit(), 'UNRECOGNIZED DATE({D})'.format(D=flds[8])
assert flds[9], '"Assigned By" VALUE WAS NOT FOUND'
props = self._get_properties(flds[11])
self._chk_qty_eq_1(flds, [0, 1, 3, 5, 8, 9])
# Additional Formatting
self._chk_qualifier(qualifiers)
# Create list of values
eco = flds[5]
goid = flds[3]
gpadvals = [
flds[0], # 0 DB
flds[1], # 1 DB_ID
qualifiers, # 3 Qualifier
flds[3], # 4 GO_ID
db_reference, # 5 DB_Reference
eco, # 6 ECO
ECO2GRP[eco],
with_from, # 7 With_From
taxons, # 12 Taxon
GET_DATE_YYYYMMDD(flds[8]), # 13 Date
flds[9], # 14 Assigned_By
get_extensions(flds[10]), # 12 Extension
props] # 12 Annotation_Properties
if add_ns:
goobj = self.godag.get(goid, '')
gpadvals.append(NAMESPACE2NS[goobj.namespace] if goobj else '')
return gpadvals | [
"def",
"_get_ntgpadvals",
"(",
"self",
",",
"flds",
",",
"add_ns",
")",
":",
"is_set",
"=",
"False",
"qualifiers",
"=",
"self",
".",
"_get_qualifier",
"(",
"flds",
"[",
"2",
"]",
")",
"assert",
"flds",
"[",
"3",
"]",
"[",
":",
"3",
"]",
"==",
"'GO:... | Convert fields from string to preferred format for GPAD ver 2.1 and 2.0. | [
"Convert",
"fields",
"from",
"string",
"to",
"preferred",
"format",
"for",
"GPAD",
"ver",
"2",
".",
"1",
"and",
"2",
".",
"0",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/init/reader_gpad.py#L74-L109 |
242,426 | tanghaibao/goatools | goatools/anno/init/reader_gpad.py | InitAssc._rd_fld_vals | def _rd_fld_vals(name, val, set_list_ft=True, qty_min=0, qty_max=None):
"""Further split a GPAD value within a single field."""
if not val and qty_min == 0:
return [] if set_list_ft else set()
vals = val.split('|') # Use a pipe to separate entries
num_vals = len(vals)
assert num_vals >= qty_min, \
"FLD({F}): MIN QUANTITY({Q}) WASN'T MET: {V}".format(
F=name, Q=qty_min, V=vals)
if qty_max is not None:
assert num_vals <= qty_max, \
"FLD({F}): MAX QUANTITY({Q}) EXCEEDED: {V}".format(
F=name, Q=qty_max, V=vals)
return vals if set_list_ft else set(vals) | python | def _rd_fld_vals(name, val, set_list_ft=True, qty_min=0, qty_max=None):
if not val and qty_min == 0:
return [] if set_list_ft else set()
vals = val.split('|') # Use a pipe to separate entries
num_vals = len(vals)
assert num_vals >= qty_min, \
"FLD({F}): MIN QUANTITY({Q}) WASN'T MET: {V}".format(
F=name, Q=qty_min, V=vals)
if qty_max is not None:
assert num_vals <= qty_max, \
"FLD({F}): MAX QUANTITY({Q}) EXCEEDED: {V}".format(
F=name, Q=qty_max, V=vals)
return vals if set_list_ft else set(vals) | [
"def",
"_rd_fld_vals",
"(",
"name",
",",
"val",
",",
"set_list_ft",
"=",
"True",
",",
"qty_min",
"=",
"0",
",",
"qty_max",
"=",
"None",
")",
":",
"if",
"not",
"val",
"and",
"qty_min",
"==",
"0",
":",
"return",
"[",
"]",
"if",
"set_list_ft",
"else",
... | Further split a GPAD value within a single field. | [
"Further",
"split",
"a",
"GPAD",
"value",
"within",
"a",
"single",
"field",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/init/reader_gpad.py#L123-L136 |
242,427 | tanghaibao/goatools | goatools/anno/init/reader_gpad.py | InitAssc._get_taxon | def _get_taxon(taxon):
"""Return Interacting taxon ID | optional | 0 or 1 | gaf column 13."""
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) | python | 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) | [
"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)... | Return Interacting taxon ID | optional | 0 or 1 | gaf column 13. | [
"Return",
"Interacting",
"taxon",
"ID",
"|",
"optional",
"|",
"0",
"or",
"1",
"|",
"gaf",
"column",
"13",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/init/reader_gpad.py#L139-L151 |
242,428 | tanghaibao/goatools | goatools/anno/init/reader_gpad.py | InitAssc._get_ntgpadnt | def _get_ntgpadnt(self, ver, add_ns):
"""Create a namedtuple object for each annotation"""
hdrs = self.gpad_columns[ver]
if add_ns:
hdrs = hdrs + ['NS']
return cx.namedtuple("ntgpadobj", hdrs) | python | def _get_ntgpadnt(self, ver, add_ns):
hdrs = self.gpad_columns[ver]
if add_ns:
hdrs = hdrs + ['NS']
return cx.namedtuple("ntgpadobj", hdrs) | [
"def",
"_get_ntgpadnt",
"(",
"self",
",",
"ver",
",",
"add_ns",
")",
":",
"hdrs",
"=",
"self",
".",
"gpad_columns",
"[",
"ver",
"]",
"if",
"add_ns",
":",
"hdrs",
"=",
"hdrs",
"+",
"[",
"'NS'",
"]",
"return",
"cx",
".",
"namedtuple",
"(",
"\"ntgpadobj... | Create a namedtuple object for each annotation | [
"Create",
"a",
"namedtuple",
"object",
"for",
"each",
"annotation"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/init/reader_gpad.py#L226-L231 |
242,429 | tanghaibao/goatools | goatools/anno/init/reader_gpad.py | InitAssc._split_line | def _split_line(self, line):
"""Split line into field values."""
line = line.rstrip('\r\n')
flds = re.split('\t', line)
assert len(flds) == self.exp_numcol, "EXPECTED({E}) COLUMNS, ACTUAL({A}): {L}".format(
E=self.exp_numcol, A=len(flds), L=line)
return flds | python | def _split_line(self, line):
line = line.rstrip('\r\n')
flds = re.split('\t', line)
assert len(flds) == self.exp_numcol, "EXPECTED({E}) COLUMNS, ACTUAL({A}): {L}".format(
E=self.exp_numcol, A=len(flds), L=line)
return flds | [
"def",
"_split_line",
"(",
"self",
",",
"line",
")",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
"'\\r\\n'",
")",
"flds",
"=",
"re",
".",
"split",
"(",
"'\\t'",
",",
"line",
")",
"assert",
"len",
"(",
"flds",
")",
"==",
"self",
".",
"exp_numcol",... | Split line into field values. | [
"Split",
"line",
"into",
"field",
"values",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/init/reader_gpad.py#L233-L239 |
242,430 | tanghaibao/goatools | goatools/anno/init/reader_gpad.py | GpadHdr.chkaddhdr | def chkaddhdr(self, line):
"""If this line contains desired header info, save it."""
mtch = self.cmpline.search(line)
if mtch:
self.gpadhdr.append(mtch.group(1)) | python | def chkaddhdr(self, line):
mtch = self.cmpline.search(line)
if mtch:
self.gpadhdr.append(mtch.group(1)) | [
"def",
"chkaddhdr",
"(",
"self",
",",
"line",
")",
":",
"mtch",
"=",
"self",
".",
"cmpline",
".",
"search",
"(",
"line",
")",
"if",
"mtch",
":",
"self",
".",
"gpadhdr",
".",
"append",
"(",
"mtch",
".",
"group",
"(",
"1",
")",
")"
] | If this line contains desired header info, save it. | [
"If",
"this",
"line",
"contains",
"desired",
"header",
"info",
"save",
"it",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/init/reader_gpad.py#L268-L272 |
242,431 | tanghaibao/goatools | goatools/nt_utils.py | get_dict_w_id2nts | def get_dict_w_id2nts(ids, id2nts, flds, dflt_null=""):
"""Return a new dict of namedtuples by combining "dicts" of namedtuples or objects."""
assert len(ids) == len(set(ids)), "NOT ALL IDs ARE UNIQUE: {IDs}".format(IDs=ids)
assert len(flds) == len(set(flds)), "DUPLICATE FIELDS: {IDs}".format(
IDs=cx.Counter(flds).most_common())
usr_id_nt = []
# 1. Instantiate namedtuple object
ntobj = cx.namedtuple("Nt", " ".join(flds))
# 2. Fill dict with namedtuple objects for desired ids
for item_id in ids:
# 2a. Combine various namedtuples into a single namedtuple
nts = [id2nt.get(item_id) for id2nt in id2nts]
vals = _combine_nt_vals(nts, flds, dflt_null)
usr_id_nt.append((item_id, ntobj._make(vals)))
return cx.OrderedDict(usr_id_nt) | python | def get_dict_w_id2nts(ids, id2nts, flds, dflt_null=""):
assert len(ids) == len(set(ids)), "NOT ALL IDs ARE UNIQUE: {IDs}".format(IDs=ids)
assert len(flds) == len(set(flds)), "DUPLICATE FIELDS: {IDs}".format(
IDs=cx.Counter(flds).most_common())
usr_id_nt = []
# 1. Instantiate namedtuple object
ntobj = cx.namedtuple("Nt", " ".join(flds))
# 2. Fill dict with namedtuple objects for desired ids
for item_id in ids:
# 2a. Combine various namedtuples into a single namedtuple
nts = [id2nt.get(item_id) for id2nt in id2nts]
vals = _combine_nt_vals(nts, flds, dflt_null)
usr_id_nt.append((item_id, ntobj._make(vals)))
return cx.OrderedDict(usr_id_nt) | [
"def",
"get_dict_w_id2nts",
"(",
"ids",
",",
"id2nts",
",",
"flds",
",",
"dflt_null",
"=",
"\"\"",
")",
":",
"assert",
"len",
"(",
"ids",
")",
"==",
"len",
"(",
"set",
"(",
"ids",
")",
")",
",",
"\"NOT ALL IDs ARE UNIQUE: {IDs}\"",
".",
"format",
"(",
... | Return a new dict of namedtuples by combining "dicts" of namedtuples or objects. | [
"Return",
"a",
"new",
"dict",
"of",
"namedtuples",
"by",
"combining",
"dicts",
"of",
"namedtuples",
"or",
"objects",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/nt_utils.py#L10-L24 |
242,432 | tanghaibao/goatools | goatools/nt_utils.py | get_list_w_id2nts | def get_list_w_id2nts(ids, id2nts, flds, dflt_null=""):
"""Return a new list of namedtuples by combining "dicts" of namedtuples or objects."""
combined_nt_list = []
# 1. Instantiate namedtuple object
ntobj = cx.namedtuple("Nt", " ".join(flds))
# 2. Fill dict with namedtuple objects for desired ids
for item_id in ids:
# 2a. Combine various namedtuples into a single namedtuple
nts = [id2nt.get(item_id) for id2nt in id2nts]
vals = _combine_nt_vals(nts, flds, dflt_null)
combined_nt_list.append(ntobj._make(vals))
return combined_nt_list | python | def get_list_w_id2nts(ids, id2nts, flds, dflt_null=""):
combined_nt_list = []
# 1. Instantiate namedtuple object
ntobj = cx.namedtuple("Nt", " ".join(flds))
# 2. Fill dict with namedtuple objects for desired ids
for item_id in ids:
# 2a. Combine various namedtuples into a single namedtuple
nts = [id2nt.get(item_id) for id2nt in id2nts]
vals = _combine_nt_vals(nts, flds, dflt_null)
combined_nt_list.append(ntobj._make(vals))
return combined_nt_list | [
"def",
"get_list_w_id2nts",
"(",
"ids",
",",
"id2nts",
",",
"flds",
",",
"dflt_null",
"=",
"\"\"",
")",
":",
"combined_nt_list",
"=",
"[",
"]",
"# 1. Instantiate namedtuple object",
"ntobj",
"=",
"cx",
".",
"namedtuple",
"(",
"\"Nt\"",
",",
"\" \"",
".",
"jo... | Return a new list of namedtuples by combining "dicts" of namedtuples or objects. | [
"Return",
"a",
"new",
"list",
"of",
"namedtuples",
"by",
"combining",
"dicts",
"of",
"namedtuples",
"or",
"objects",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/nt_utils.py#L26-L37 |
242,433 | tanghaibao/goatools | goatools/nt_utils.py | combine_nt_lists | def combine_nt_lists(lists, flds, dflt_null=""):
"""Return a new list of namedtuples by zipping "lists" of namedtuples or objects."""
combined_nt_list = []
# Check that all lists are the same length
lens = [len(lst) for lst in lists]
assert len(set(lens)) == 1, \
"LIST LENGTHS MUST BE EQUAL: {Ls}".format(Ls=" ".join(str(l) for l in lens))
# 1. Instantiate namedtuple object
ntobj = cx.namedtuple("Nt", " ".join(flds))
# 2. Loop through zipped list
for lst0_lstn in zip(*lists):
# 2a. Combine various namedtuples into a single namedtuple
combined_nt_list.append(ntobj._make(_combine_nt_vals(lst0_lstn, flds, dflt_null)))
return combined_nt_list | python | def combine_nt_lists(lists, flds, dflt_null=""):
combined_nt_list = []
# Check that all lists are the same length
lens = [len(lst) for lst in lists]
assert len(set(lens)) == 1, \
"LIST LENGTHS MUST BE EQUAL: {Ls}".format(Ls=" ".join(str(l) for l in lens))
# 1. Instantiate namedtuple object
ntobj = cx.namedtuple("Nt", " ".join(flds))
# 2. Loop through zipped list
for lst0_lstn in zip(*lists):
# 2a. Combine various namedtuples into a single namedtuple
combined_nt_list.append(ntobj._make(_combine_nt_vals(lst0_lstn, flds, dflt_null)))
return combined_nt_list | [
"def",
"combine_nt_lists",
"(",
"lists",
",",
"flds",
",",
"dflt_null",
"=",
"\"\"",
")",
":",
"combined_nt_list",
"=",
"[",
"]",
"# Check that all lists are the same length",
"lens",
"=",
"[",
"len",
"(",
"lst",
")",
"for",
"lst",
"in",
"lists",
"]",
"asser... | Return a new list of namedtuples by zipping "lists" of namedtuples or objects. | [
"Return",
"a",
"new",
"list",
"of",
"namedtuples",
"by",
"zipping",
"lists",
"of",
"namedtuples",
"or",
"objects",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/nt_utils.py#L39-L52 |
242,434 | tanghaibao/goatools | goatools/nt_utils.py | wr_py_nts | def wr_py_nts(fout_py, nts, docstring=None, varname="nts"):
"""Save namedtuples into a Python module."""
if nts:
with open(fout_py, 'w') as prt:
prt.write('"""{DOCSTRING}"""\n\n'.format(DOCSTRING=docstring))
prt.write("# Created: {DATE}\n".format(DATE=str(datetime.date.today())))
prt_nts(prt, nts, varname)
sys.stdout.write(" {N:7,} items WROTE: {PY}\n".format(N=len(nts), PY=fout_py)) | python | def wr_py_nts(fout_py, nts, docstring=None, varname="nts"):
if nts:
with open(fout_py, 'w') as prt:
prt.write('"""{DOCSTRING}"""\n\n'.format(DOCSTRING=docstring))
prt.write("# Created: {DATE}\n".format(DATE=str(datetime.date.today())))
prt_nts(prt, nts, varname)
sys.stdout.write(" {N:7,} items WROTE: {PY}\n".format(N=len(nts), PY=fout_py)) | [
"def",
"wr_py_nts",
"(",
"fout_py",
",",
"nts",
",",
"docstring",
"=",
"None",
",",
"varname",
"=",
"\"nts\"",
")",
":",
"if",
"nts",
":",
"with",
"open",
"(",
"fout_py",
",",
"'w'",
")",
"as",
"prt",
":",
"prt",
".",
"write",
"(",
"'\"\"\"{DOCSTRING... | Save namedtuples into a Python module. | [
"Save",
"namedtuples",
"into",
"a",
"Python",
"module",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/nt_utils.py#L54-L61 |
242,435 | tanghaibao/goatools | goatools/nt_utils.py | prt_nts | def prt_nts(prt, nts, varname, spc=' '):
"""Print namedtuples into a Python module."""
first_nt = nts[0]
nt_name = type(first_nt).__name__
prt.write("import collections as cx\n\n")
prt.write("NT_FIELDS = [\n")
for fld in first_nt._fields:
prt.write('{SPC}"{F}",\n'.format(SPC=spc, F=fld))
prt.write("]\n\n")
prt.write('{NtName} = cx.namedtuple("{NtName}", " ".join(NT_FIELDS))\n\n'.format(
NtName=nt_name))
prt.write("# {N:,} items\n".format(N=len(nts)))
prt.write("# pylint: disable=line-too-long\n")
prt.write("{VARNAME} = [\n".format(VARNAME=varname))
for ntup in nts:
prt.write("{SPC}{NT},\n".format(SPC=spc, NT=ntup))
prt.write("]\n") | python | def prt_nts(prt, nts, varname, spc=' '):
first_nt = nts[0]
nt_name = type(first_nt).__name__
prt.write("import collections as cx\n\n")
prt.write("NT_FIELDS = [\n")
for fld in first_nt._fields:
prt.write('{SPC}"{F}",\n'.format(SPC=spc, F=fld))
prt.write("]\n\n")
prt.write('{NtName} = cx.namedtuple("{NtName}", " ".join(NT_FIELDS))\n\n'.format(
NtName=nt_name))
prt.write("# {N:,} items\n".format(N=len(nts)))
prt.write("# pylint: disable=line-too-long\n")
prt.write("{VARNAME} = [\n".format(VARNAME=varname))
for ntup in nts:
prt.write("{SPC}{NT},\n".format(SPC=spc, NT=ntup))
prt.write("]\n") | [
"def",
"prt_nts",
"(",
"prt",
",",
"nts",
",",
"varname",
",",
"spc",
"=",
"' '",
")",
":",
"first_nt",
"=",
"nts",
"[",
"0",
"]",
"nt_name",
"=",
"type",
"(",
"first_nt",
")",
".",
"__name__",
"prt",
".",
"write",
"(",
"\"import collections as cx\\... | Print namedtuples into a Python module. | [
"Print",
"namedtuples",
"into",
"a",
"Python",
"module",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/nt_utils.py#L63-L79 |
242,436 | tanghaibao/goatools | goatools/nt_utils.py | get_unique_fields | def get_unique_fields(fld_lists):
"""Get unique namedtuple fields, despite potential duplicates in lists of fields."""
flds = []
fld_set = set([f for flst in fld_lists for f in flst])
fld_seen = set()
# Add unique fields to list of fields in order that they appear
for fld_list in fld_lists:
for fld in fld_list:
# Add fields if the field has not yet been seen
if fld not in fld_seen:
flds.append(fld)
fld_seen.add(fld)
assert len(flds) == len(fld_set)
return flds | python | def get_unique_fields(fld_lists):
flds = []
fld_set = set([f for flst in fld_lists for f in flst])
fld_seen = set()
# Add unique fields to list of fields in order that they appear
for fld_list in fld_lists:
for fld in fld_list:
# Add fields if the field has not yet been seen
if fld not in fld_seen:
flds.append(fld)
fld_seen.add(fld)
assert len(flds) == len(fld_set)
return flds | [
"def",
"get_unique_fields",
"(",
"fld_lists",
")",
":",
"flds",
"=",
"[",
"]",
"fld_set",
"=",
"set",
"(",
"[",
"f",
"for",
"flst",
"in",
"fld_lists",
"for",
"f",
"in",
"flst",
"]",
")",
"fld_seen",
"=",
"set",
"(",
")",
"# Add unique fields to list of f... | Get unique namedtuple fields, despite potential duplicates in lists of fields. | [
"Get",
"unique",
"namedtuple",
"fields",
"despite",
"potential",
"duplicates",
"in",
"lists",
"of",
"fields",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/nt_utils.py#L81-L94 |
242,437 | tanghaibao/goatools | goatools/nt_utils.py | _combine_nt_vals | def _combine_nt_vals(lst0_lstn, flds, dflt_null):
"""Given a list of lists of nts, return a single namedtuple."""
vals = []
for fld in flds:
fld_seen = False
# Set field value using the **first** value seen in list of nt lists(lst0_lstn)
for nt_curr in lst0_lstn:
if hasattr(nt_curr, fld):
vals.append(getattr(nt_curr, fld))
fld_seen = True
break
# Set default value if GO ID or nt value is not present
if fld_seen is False:
vals.append(dflt_null)
return vals | python | def _combine_nt_vals(lst0_lstn, flds, dflt_null):
vals = []
for fld in flds:
fld_seen = False
# Set field value using the **first** value seen in list of nt lists(lst0_lstn)
for nt_curr in lst0_lstn:
if hasattr(nt_curr, fld):
vals.append(getattr(nt_curr, fld))
fld_seen = True
break
# Set default value if GO ID or nt value is not present
if fld_seen is False:
vals.append(dflt_null)
return vals | [
"def",
"_combine_nt_vals",
"(",
"lst0_lstn",
",",
"flds",
",",
"dflt_null",
")",
":",
"vals",
"=",
"[",
"]",
"for",
"fld",
"in",
"flds",
":",
"fld_seen",
"=",
"False",
"# Set field value using the **first** value seen in list of nt lists(lst0_lstn)",
"for",
"nt_curr",... | Given a list of lists of nts, return a single namedtuple. | [
"Given",
"a",
"list",
"of",
"lists",
"of",
"nts",
"return",
"a",
"single",
"namedtuple",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/nt_utils.py#L97-L111 |
242,438 | tanghaibao/goatools | goatools/cli/gos_get.py | GetGOs.get_go2obj | def get_go2obj(self, goids):
"""Return GO Terms for each user-specified GO ID. Note missing GO IDs."""
goids = goids.intersection(self.go2obj.keys())
if len(goids) != len(goids):
goids_missing = goids.difference(goids)
print(" {N} MISSING GO IDs: {GOs}".format(N=len(goids_missing), GOs=goids_missing))
return {go:self.go2obj[go] for go in goids} | python | def get_go2obj(self, goids):
goids = goids.intersection(self.go2obj.keys())
if len(goids) != len(goids):
goids_missing = goids.difference(goids)
print(" {N} MISSING GO IDs: {GOs}".format(N=len(goids_missing), GOs=goids_missing))
return {go:self.go2obj[go] for go in goids} | [
"def",
"get_go2obj",
"(",
"self",
",",
"goids",
")",
":",
"goids",
"=",
"goids",
".",
"intersection",
"(",
"self",
".",
"go2obj",
".",
"keys",
"(",
")",
")",
"if",
"len",
"(",
"goids",
")",
"!=",
"len",
"(",
"goids",
")",
":",
"goids_missing",
"=",... | Return GO Terms for each user-specified GO ID. Note missing GO IDs. | [
"Return",
"GO",
"Terms",
"for",
"each",
"user",
"-",
"specified",
"GO",
"ID",
".",
"Note",
"missing",
"GO",
"IDs",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/gos_get.py#L46-L52 |
242,439 | tanghaibao/goatools | goatools/grouper/utils.py | no_duplicates_sections2d | def no_duplicates_sections2d(sections2d, prt=None):
"""Check for duplicate header GO IDs in the 2-D sections variable."""
no_dups = True
ctr = cx.Counter()
for _, hdrgos in sections2d:
for goid in hdrgos:
ctr[goid] += 1
for goid, cnt in ctr.most_common():
if cnt == 1:
break
no_dups = False
if prt is not None:
prt.write("**SECTIONS WARNING FOUND: {N:3} {GO}\n".format(N=cnt, GO=goid))
return no_dups | python | def no_duplicates_sections2d(sections2d, prt=None):
no_dups = True
ctr = cx.Counter()
for _, hdrgos in sections2d:
for goid in hdrgos:
ctr[goid] += 1
for goid, cnt in ctr.most_common():
if cnt == 1:
break
no_dups = False
if prt is not None:
prt.write("**SECTIONS WARNING FOUND: {N:3} {GO}\n".format(N=cnt, GO=goid))
return no_dups | [
"def",
"no_duplicates_sections2d",
"(",
"sections2d",
",",
"prt",
"=",
"None",
")",
":",
"no_dups",
"=",
"True",
"ctr",
"=",
"cx",
".",
"Counter",
"(",
")",
"for",
"_",
",",
"hdrgos",
"in",
"sections2d",
":",
"for",
"goid",
"in",
"hdrgos",
":",
"ctr",
... | Check for duplicate header GO IDs in the 2-D sections variable. | [
"Check",
"for",
"duplicate",
"header",
"GO",
"IDs",
"in",
"the",
"2",
"-",
"D",
"sections",
"variable",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/utils.py#L13-L26 |
242,440 | tanghaibao/goatools | goatools/evidence_codes.py | EvidenceCodes.get_evcodes | def get_evcodes(self, inc_set=None, exc_set=None):
"""Get evidence code for all but NOT 'No biological data'"""
codes = self.get_evcodes_all(inc_set, exc_set)
codes.discard('ND')
return codes | python | def get_evcodes(self, inc_set=None, exc_set=None):
"""Get evidence code for all but NOT 'No biological data'"""
codes = self.get_evcodes_all(inc_set, exc_set)
codes.discard('ND')
return codes | [
"def",
"get_evcodes",
"(",
"self",
",",
"inc_set",
"=",
"None",
",",
"exc_set",
"=",
"None",
")",
":",
"codes",
"=",
"self",
".",
"get_evcodes_all",
"(",
"inc_set",
",",
"exc_set",
")",
"codes",
".",
"discard",
"(",
"'ND'",
")",
"return",
"codes"
] | Get evidence code for all but NOT 'No biological data | [
"Get",
"evidence",
"code",
"for",
"all",
"but",
"NOT",
"No",
"biological",
"data"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/evidence_codes.py#L90-L94 |
242,441 | tanghaibao/goatools | goatools/evidence_codes.py | EvidenceCodes.get_evcodes_all | def get_evcodes_all(self, inc_set=None, exc_set=None):
"""Get set of evidence codes given include set and exclude set"""
codes = self._get_grps_n_codes(inc_set) if inc_set else set(self.code2nt)
if exc_set:
codes.difference_update(self._get_grps_n_codes(exc_set))
return codes | python | def get_evcodes_all(self, inc_set=None, exc_set=None):
codes = self._get_grps_n_codes(inc_set) if inc_set else set(self.code2nt)
if exc_set:
codes.difference_update(self._get_grps_n_codes(exc_set))
return codes | [
"def",
"get_evcodes_all",
"(",
"self",
",",
"inc_set",
"=",
"None",
",",
"exc_set",
"=",
"None",
")",
":",
"codes",
"=",
"self",
".",
"_get_grps_n_codes",
"(",
"inc_set",
")",
"if",
"inc_set",
"else",
"set",
"(",
"self",
".",
"code2nt",
")",
"if",
"exc... | Get set of evidence codes given include set and exclude set | [
"Get",
"set",
"of",
"evidence",
"codes",
"given",
"include",
"set",
"and",
"exclude",
"set"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/evidence_codes.py#L96-L101 |
242,442 | tanghaibao/goatools | goatools/evidence_codes.py | EvidenceCodes._get_grps_n_codes | def _get_grps_n_codes(self, usr_set):
"""Get codes, given codes or groups."""
codes = usr_set.intersection(self.code2nt)
for grp in usr_set.intersection(self.grp2codes):
codes.update(self.grp2codes[grp])
return codes | python | def _get_grps_n_codes(self, usr_set):
codes = usr_set.intersection(self.code2nt)
for grp in usr_set.intersection(self.grp2codes):
codes.update(self.grp2codes[grp])
return codes | [
"def",
"_get_grps_n_codes",
"(",
"self",
",",
"usr_set",
")",
":",
"codes",
"=",
"usr_set",
".",
"intersection",
"(",
"self",
".",
"code2nt",
")",
"for",
"grp",
"in",
"usr_set",
".",
"intersection",
"(",
"self",
".",
"grp2codes",
")",
":",
"codes",
".",
... | Get codes, given codes or groups. | [
"Get",
"codes",
"given",
"codes",
"or",
"groups",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/evidence_codes.py#L103-L108 |
242,443 | tanghaibao/goatools | goatools/evidence_codes.py | EvidenceCodes.sort_nts | def sort_nts(self, nt_list, codekey):
"""Sort list of namedtuples such so evidence codes in same order as code2nt."""
# Problem is that some members in the nt_list do NOT have
# codekey=EvidenceCode, then it returns None, which breaks py34 and 35
# The fix here is that for these members, default to -1 (is this valid?)
sortby = lambda nt: self.ev2idx.get(getattr(nt, codekey), -1)
return sorted(nt_list, key=sortby) | python | def sort_nts(self, nt_list, codekey):
# Problem is that some members in the nt_list do NOT have
# codekey=EvidenceCode, then it returns None, which breaks py34 and 35
# The fix here is that for these members, default to -1 (is this valid?)
sortby = lambda nt: self.ev2idx.get(getattr(nt, codekey), -1)
return sorted(nt_list, key=sortby) | [
"def",
"sort_nts",
"(",
"self",
",",
"nt_list",
",",
"codekey",
")",
":",
"# Problem is that some members in the nt_list do NOT have",
"# codekey=EvidenceCode, then it returns None, which breaks py34 and 35",
"# The fix here is that for these members, default to -1 (is this valid?)",
"sort... | Sort list of namedtuples such so evidence codes in same order as code2nt. | [
"Sort",
"list",
"of",
"namedtuples",
"such",
"so",
"evidence",
"codes",
"in",
"same",
"order",
"as",
"code2nt",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/evidence_codes.py#L110-L116 |
242,444 | tanghaibao/goatools | goatools/evidence_codes.py | EvidenceCodes.get_grp_name | def get_grp_name(self, code):
"""Return group and name for an evidence code."""
nt_code = self.code2nt.get(code.strip(), None)
if nt_code is not None:
return nt_code.group, nt_code.name
return "", "" | python | def get_grp_name(self, code):
nt_code = self.code2nt.get(code.strip(), None)
if nt_code is not None:
return nt_code.group, nt_code.name
return "", "" | [
"def",
"get_grp_name",
"(",
"self",
",",
"code",
")",
":",
"nt_code",
"=",
"self",
".",
"code2nt",
".",
"get",
"(",
"code",
".",
"strip",
"(",
")",
",",
"None",
")",
"if",
"nt_code",
"is",
"not",
"None",
":",
"return",
"nt_code",
".",
"group",
",",... | Return group and name for an evidence code. | [
"Return",
"group",
"and",
"name",
"for",
"an",
"evidence",
"code",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/evidence_codes.py#L118-L123 |
242,445 | tanghaibao/goatools | goatools/evidence_codes.py | EvidenceCodes.prt_ev_cnts | def prt_ev_cnts(self, ctr, prt=sys.stdout):
"""Prints evidence code counts stored in a collections Counter."""
for key, cnt in ctr.most_common():
grp, name = self.get_grp_name(key.replace("NOT ", ""))
prt.write("{CNT:7,} {EV:>7} {GROUP:<15} {NAME}\n".format(
CNT=cnt, EV=key, GROUP=grp, NAME=name)) | python | def prt_ev_cnts(self, ctr, prt=sys.stdout):
for key, cnt in ctr.most_common():
grp, name = self.get_grp_name(key.replace("NOT ", ""))
prt.write("{CNT:7,} {EV:>7} {GROUP:<15} {NAME}\n".format(
CNT=cnt, EV=key, GROUP=grp, NAME=name)) | [
"def",
"prt_ev_cnts",
"(",
"self",
",",
"ctr",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"for",
"key",
",",
"cnt",
"in",
"ctr",
".",
"most_common",
"(",
")",
":",
"grp",
",",
"name",
"=",
"self",
".",
"get_grp_name",
"(",
"key",
".",
"repl... | Prints evidence code counts stored in a collections Counter. | [
"Prints",
"evidence",
"code",
"counts",
"stored",
"in",
"a",
"collections",
"Counter",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/evidence_codes.py#L125-L130 |
242,446 | tanghaibao/goatools | goatools/evidence_codes.py | EvidenceCodes.get_order | def get_order(self, codes):
"""Return evidence codes in order shown in code2name."""
return sorted(codes, key=lambda e: [self.ev2idx.get(e)]) | python | def get_order(self, codes):
return sorted(codes, key=lambda e: [self.ev2idx.get(e)]) | [
"def",
"get_order",
"(",
"self",
",",
"codes",
")",
":",
"return",
"sorted",
"(",
"codes",
",",
"key",
"=",
"lambda",
"e",
":",
"[",
"self",
".",
"ev2idx",
".",
"get",
"(",
"e",
")",
"]",
")"
] | Return evidence codes in order shown in code2name. | [
"Return",
"evidence",
"codes",
"in",
"order",
"shown",
"in",
"code2name",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/evidence_codes.py#L132-L134 |
242,447 | tanghaibao/goatools | goatools/evidence_codes.py | _Init.get_grp2code2nt | def get_grp2code2nt(self):
"""Return ordered dict for group to namedtuple"""
grp2code2nt = cx.OrderedDict([(g, []) for g in self.grps])
for code, ntd in self.code2nt.items():
grp2code2nt[ntd.group].append((code, ntd))
for grp, nts in grp2code2nt.items():
grp2code2nt[grp] = cx.OrderedDict(nts)
return grp2code2nt | python | def get_grp2code2nt(self):
grp2code2nt = cx.OrderedDict([(g, []) for g in self.grps])
for code, ntd in self.code2nt.items():
grp2code2nt[ntd.group].append((code, ntd))
for grp, nts in grp2code2nt.items():
grp2code2nt[grp] = cx.OrderedDict(nts)
return grp2code2nt | [
"def",
"get_grp2code2nt",
"(",
"self",
")",
":",
"grp2code2nt",
"=",
"cx",
".",
"OrderedDict",
"(",
"[",
"(",
"g",
",",
"[",
"]",
")",
"for",
"g",
"in",
"self",
".",
"grps",
"]",
")",
"for",
"code",
",",
"ntd",
"in",
"self",
".",
"code2nt",
".",
... | Return ordered dict for group to namedtuple | [
"Return",
"ordered",
"dict",
"for",
"group",
"to",
"namedtuple"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/evidence_codes.py#L156-L163 |
242,448 | tanghaibao/goatools | goatools/evidence_codes.py | _Init._init_grps | def _init_grps(code2nt):
"""Return list of groups in same order as in code2nt"""
seen = set()
seen_add = seen.add
groups = [nt.group for nt in code2nt.values()]
return [g for g in groups if not (g in seen or seen_add(g))] | python | def _init_grps(code2nt):
seen = set()
seen_add = seen.add
groups = [nt.group for nt in code2nt.values()]
return [g for g in groups if not (g in seen or seen_add(g))] | [
"def",
"_init_grps",
"(",
"code2nt",
")",
":",
"seen",
"=",
"set",
"(",
")",
"seen_add",
"=",
"seen",
".",
"add",
"groups",
"=",
"[",
"nt",
".",
"group",
"for",
"nt",
"in",
"code2nt",
".",
"values",
"(",
")",
"]",
"return",
"[",
"g",
"for",
"g",
... | Return list of groups in same order as in code2nt | [
"Return",
"list",
"of",
"groups",
"in",
"same",
"order",
"as",
"in",
"code2nt"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/evidence_codes.py#L166-L171 |
242,449 | tanghaibao/goatools | goatools/evidence_codes.py | _Init.get_grp2codes | def get_grp2codes(self):
"""Get dict of group name to namedtuples."""
grp2codes = cx.defaultdict(set)
for code, ntd in self.code2nt.items():
grp2codes[ntd.group].add(code)
return dict(grp2codes) | python | def get_grp2codes(self):
grp2codes = cx.defaultdict(set)
for code, ntd in self.code2nt.items():
grp2codes[ntd.group].add(code)
return dict(grp2codes) | [
"def",
"get_grp2codes",
"(",
"self",
")",
":",
"grp2codes",
"=",
"cx",
".",
"defaultdict",
"(",
"set",
")",
"for",
"code",
",",
"ntd",
"in",
"self",
".",
"code2nt",
".",
"items",
"(",
")",
":",
"grp2codes",
"[",
"ntd",
".",
"group",
"]",
".",
"add"... | Get dict of group name to namedtuples. | [
"Get",
"dict",
"of",
"group",
"name",
"to",
"namedtuples",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/evidence_codes.py#L173-L178 |
242,450 | tanghaibao/goatools | goatools/grouper/grprplt.py | GrouperPlot.plot_sections | def plot_sections(self, fout_dir=".", **kws_usr):
"""Plot groups of GOs which have been placed in sections."""
kws_plt, _ = self._get_kws_plt(None, **kws_usr)
PltGroupedGos(self).plot_sections(fout_dir, **kws_plt) | python | def plot_sections(self, fout_dir=".", **kws_usr):
kws_plt, _ = self._get_kws_plt(None, **kws_usr)
PltGroupedGos(self).plot_sections(fout_dir, **kws_plt) | [
"def",
"plot_sections",
"(",
"self",
",",
"fout_dir",
"=",
"\".\"",
",",
"*",
"*",
"kws_usr",
")",
":",
"kws_plt",
",",
"_",
"=",
"self",
".",
"_get_kws_plt",
"(",
"None",
",",
"*",
"*",
"kws_usr",
")",
"PltGroupedGos",
"(",
"self",
")",
".",
"plot_s... | Plot groups of GOs which have been placed in sections. | [
"Plot",
"groups",
"of",
"GOs",
"which",
"have",
"been",
"placed",
"in",
"sections",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprplt.py#L31-L34 |
242,451 | tanghaibao/goatools | goatools/grouper/grprplt.py | GrouperPlot.get_pltdotstr | def get_pltdotstr(self, **kws_usr):
"""Plot one GO header group in Grouper."""
dotstrs = self.get_pltdotstrs(**kws_usr)
assert len(dotstrs) == 1
return dotstrs[0] | python | def get_pltdotstr(self, **kws_usr):
dotstrs = self.get_pltdotstrs(**kws_usr)
assert len(dotstrs) == 1
return dotstrs[0] | [
"def",
"get_pltdotstr",
"(",
"self",
",",
"*",
"*",
"kws_usr",
")",
":",
"dotstrs",
"=",
"self",
".",
"get_pltdotstrs",
"(",
"*",
"*",
"kws_usr",
")",
"assert",
"len",
"(",
"dotstrs",
")",
"==",
"1",
"return",
"dotstrs",
"[",
"0",
"]"
] | Plot one GO header group in Grouper. | [
"Plot",
"one",
"GO",
"header",
"group",
"in",
"Grouper",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprplt.py#L46-L50 |
242,452 | tanghaibao/goatools | goatools/grouper/grprplt.py | GrouperPlot.plot_groups_unplaced | def plot_groups_unplaced(self, fout_dir=".", **kws_usr):
"""Plot each GO group."""
# kws: go2color max_gos upper_trigger max_upper
plotobj = PltGroupedGos(self)
return plotobj.plot_groups_unplaced(fout_dir, **kws_usr) | python | def plot_groups_unplaced(self, fout_dir=".", **kws_usr):
# kws: go2color max_gos upper_trigger max_upper
plotobj = PltGroupedGos(self)
return plotobj.plot_groups_unplaced(fout_dir, **kws_usr) | [
"def",
"plot_groups_unplaced",
"(",
"self",
",",
"fout_dir",
"=",
"\".\"",
",",
"*",
"*",
"kws_usr",
")",
":",
"# kws: go2color max_gos upper_trigger max_upper",
"plotobj",
"=",
"PltGroupedGos",
"(",
"self",
")",
"return",
"plotobj",
".",
"plot_groups_unplaced",
"("... | Plot each GO group. | [
"Plot",
"each",
"GO",
"group",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprplt.py#L52-L56 |
242,453 | tanghaibao/goatools | goatools/grouper/grprplt.py | GrouperPlot._get_kws_plt | def _get_kws_plt(self, usrgos, **kws_usr):
"""Add go2color and go2bordercolor relevant to this grouping into plot."""
kws_plt = kws_usr.copy()
kws_dag = {}
hdrgo = kws_plt.get('hdrgo', None)
objcolor = GrouperColors(self.grprobj)
# GO term colors
if 'go2color' not in kws_usr:
kws_plt['go2color'] = objcolor.get_go2color_users()
elif hdrgo is not None:
go2color = kws_plt.get('go2color').copy()
go2color[hdrgo] = PltGroupedGosArgs.hdrgo_dflt_color
kws_plt['go2color'] = go2color
# GO term border colors
if 'go2bordercolor' not in kws_usr:
kws_plt['go2bordercolor'] = objcolor.get_bordercolor()
prune = kws_usr.get('prune', None)
if prune is True and hdrgo is not None:
kws_dag['dst_srcs_list'] = [(hdrgo, usrgos), (None, set([hdrgo]))]
kws_plt['parentcnt'] = True
elif prune:
kws_dag['dst_srcs_list'] = prune
kws_plt['parentcnt'] = True
# Group text
kws_plt['go2txt'] = self.get_go2txt(self.grprobj,
kws_plt.get('go2color'), kws_plt.get('go2bordercolor'))
return kws_plt, kws_dag | python | def _get_kws_plt(self, usrgos, **kws_usr):
kws_plt = kws_usr.copy()
kws_dag = {}
hdrgo = kws_plt.get('hdrgo', None)
objcolor = GrouperColors(self.grprobj)
# GO term colors
if 'go2color' not in kws_usr:
kws_plt['go2color'] = objcolor.get_go2color_users()
elif hdrgo is not None:
go2color = kws_plt.get('go2color').copy()
go2color[hdrgo] = PltGroupedGosArgs.hdrgo_dflt_color
kws_plt['go2color'] = go2color
# GO term border colors
if 'go2bordercolor' not in kws_usr:
kws_plt['go2bordercolor'] = objcolor.get_bordercolor()
prune = kws_usr.get('prune', None)
if prune is True and hdrgo is not None:
kws_dag['dst_srcs_list'] = [(hdrgo, usrgos), (None, set([hdrgo]))]
kws_plt['parentcnt'] = True
elif prune:
kws_dag['dst_srcs_list'] = prune
kws_plt['parentcnt'] = True
# Group text
kws_plt['go2txt'] = self.get_go2txt(self.grprobj,
kws_plt.get('go2color'), kws_plt.get('go2bordercolor'))
return kws_plt, kws_dag | [
"def",
"_get_kws_plt",
"(",
"self",
",",
"usrgos",
",",
"*",
"*",
"kws_usr",
")",
":",
"kws_plt",
"=",
"kws_usr",
".",
"copy",
"(",
")",
"kws_dag",
"=",
"{",
"}",
"hdrgo",
"=",
"kws_plt",
".",
"get",
"(",
"'hdrgo'",
",",
"None",
")",
"objcolor",
"=... | Add go2color and go2bordercolor relevant to this grouping into plot. | [
"Add",
"go2color",
"and",
"go2bordercolor",
"relevant",
"to",
"this",
"grouping",
"into",
"plot",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprplt.py#L77-L103 |
242,454 | tanghaibao/goatools | goatools/grouper/grprplt.py | GrouperPlot.get_go2txt | def get_go2txt(grprobj_cur, grp_go2color, grp_go2bordercolor):
"""Adds section text in all GO terms if not Misc. Adds Misc in terms of interest."""
goids_main = set(o.id for o in grprobj_cur.gosubdag.go2obj.values())
hdrobj = grprobj_cur.hdrobj
grprobj_all = Grouper("all",
grprobj_cur.usrgos.union(goids_main), hdrobj, grprobj_cur.gosubdag)
# Adds section text to all GO terms in plot (misses middle GO terms)
_secdflt = hdrobj.secdflt
_hilight = set(grp_go2color.keys()).union(grp_go2bordercolor)
ret_go2txt = {}
# Keep sections text only if GO header, GO user, or not Misc.
if hdrobj.sections:
for goid, txt in grprobj_all.get_go2sectiontxt().items():
if txt == 'broad':
continue
if txt != _secdflt or goid in _hilight:
ret_go2txt[goid] = txt
return ret_go2txt | python | def get_go2txt(grprobj_cur, grp_go2color, grp_go2bordercolor):
goids_main = set(o.id for o in grprobj_cur.gosubdag.go2obj.values())
hdrobj = grprobj_cur.hdrobj
grprobj_all = Grouper("all",
grprobj_cur.usrgos.union(goids_main), hdrobj, grprobj_cur.gosubdag)
# Adds section text to all GO terms in plot (misses middle GO terms)
_secdflt = hdrobj.secdflt
_hilight = set(grp_go2color.keys()).union(grp_go2bordercolor)
ret_go2txt = {}
# Keep sections text only if GO header, GO user, or not Misc.
if hdrobj.sections:
for goid, txt in grprobj_all.get_go2sectiontxt().items():
if txt == 'broad':
continue
if txt != _secdflt or goid in _hilight:
ret_go2txt[goid] = txt
return ret_go2txt | [
"def",
"get_go2txt",
"(",
"grprobj_cur",
",",
"grp_go2color",
",",
"grp_go2bordercolor",
")",
":",
"goids_main",
"=",
"set",
"(",
"o",
".",
"id",
"for",
"o",
"in",
"grprobj_cur",
".",
"gosubdag",
".",
"go2obj",
".",
"values",
"(",
")",
")",
"hdrobj",
"="... | Adds section text in all GO terms if not Misc. Adds Misc in terms of interest. | [
"Adds",
"section",
"text",
"in",
"all",
"GO",
"terms",
"if",
"not",
"Misc",
".",
"Adds",
"Misc",
"in",
"terms",
"of",
"interest",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprplt.py#L106-L123 |
242,455 | tanghaibao/goatools | goatools/base.py | download_go_basic_obo | def download_go_basic_obo(obo="go-basic.obo", prt=sys.stdout, loading_bar=True):
"""Download Ontologies, if necessary."""
if not os.path.isfile(obo):
http = "http://purl.obolibrary.org/obo/go"
if "slim" in obo:
http = "http://www.geneontology.org/ontology/subsets"
# http = 'http://current.geneontology.org/ontology/subsets'
obo_remote = "{HTTP}/{OBO}".format(HTTP=http, OBO=os.path.basename(obo))
dnld_file(obo_remote, obo, prt, loading_bar)
else:
if prt is not None:
prt.write(" EXISTS: {FILE}\n".format(FILE=obo))
return obo | python | def download_go_basic_obo(obo="go-basic.obo", prt=sys.stdout, loading_bar=True):
if not os.path.isfile(obo):
http = "http://purl.obolibrary.org/obo/go"
if "slim" in obo:
http = "http://www.geneontology.org/ontology/subsets"
# http = 'http://current.geneontology.org/ontology/subsets'
obo_remote = "{HTTP}/{OBO}".format(HTTP=http, OBO=os.path.basename(obo))
dnld_file(obo_remote, obo, prt, loading_bar)
else:
if prt is not None:
prt.write(" EXISTS: {FILE}\n".format(FILE=obo))
return obo | [
"def",
"download_go_basic_obo",
"(",
"obo",
"=",
"\"go-basic.obo\"",
",",
"prt",
"=",
"sys",
".",
"stdout",
",",
"loading_bar",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"obo",
")",
":",
"http",
"=",
"\"http://purl.obolib... | Download Ontologies, if necessary. | [
"Download",
"Ontologies",
"if",
"necessary",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/base.py#L113-L125 |
242,456 | tanghaibao/goatools | goatools/base.py | download_ncbi_associations | def download_ncbi_associations(gene2go="gene2go", prt=sys.stdout, loading_bar=True):
"""Download associations from NCBI, if necessary"""
# Download: ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/gene2go.gz
gzip_file = "{GENE2GO}.gz".format(GENE2GO=gene2go)
if not os.path.isfile(gene2go):
file_remote = "ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/{GZ}".format(
GZ=os.path.basename(gzip_file))
dnld_file(file_remote, gene2go, prt, loading_bar)
else:
if prt is not None:
prt.write(" EXISTS: {FILE}\n".format(FILE=gene2go))
return gene2go | python | def download_ncbi_associations(gene2go="gene2go", prt=sys.stdout, loading_bar=True):
# Download: ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/gene2go.gz
gzip_file = "{GENE2GO}.gz".format(GENE2GO=gene2go)
if not os.path.isfile(gene2go):
file_remote = "ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/{GZ}".format(
GZ=os.path.basename(gzip_file))
dnld_file(file_remote, gene2go, prt, loading_bar)
else:
if prt is not None:
prt.write(" EXISTS: {FILE}\n".format(FILE=gene2go))
return gene2go | [
"def",
"download_ncbi_associations",
"(",
"gene2go",
"=",
"\"gene2go\"",
",",
"prt",
"=",
"sys",
".",
"stdout",
",",
"loading_bar",
"=",
"True",
")",
":",
"# Download: ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/gene2go.gz",
"gzip_file",
"=",
"\"{GENE2GO}.gz\"",
".",
"format",... | Download associations from NCBI, if necessary | [
"Download",
"associations",
"from",
"NCBI",
"if",
"necessary"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/base.py#L127-L138 |
242,457 | tanghaibao/goatools | goatools/base.py | gunzip | def gunzip(gzip_file, file_gunzip=None):
"""Unzip .gz file. Return filename of unzipped file."""
if file_gunzip is None:
file_gunzip = os.path.splitext(gzip_file)[0]
gzip_open_to(gzip_file, file_gunzip)
return file_gunzip | python | def gunzip(gzip_file, file_gunzip=None):
if file_gunzip is None:
file_gunzip = os.path.splitext(gzip_file)[0]
gzip_open_to(gzip_file, file_gunzip)
return file_gunzip | [
"def",
"gunzip",
"(",
"gzip_file",
",",
"file_gunzip",
"=",
"None",
")",
":",
"if",
"file_gunzip",
"is",
"None",
":",
"file_gunzip",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"gzip_file",
")",
"[",
"0",
"]",
"gzip_open_to",
"(",
"gzip_file",
",",
"... | Unzip .gz file. Return filename of unzipped file. | [
"Unzip",
".",
"gz",
"file",
".",
"Return",
"filename",
"of",
"unzipped",
"file",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/base.py#L140-L145 |
242,458 | tanghaibao/goatools | goatools/base.py | get_godag | def get_godag(fin_obo="go-basic.obo", prt=sys.stdout, loading_bar=True, optional_attrs=None):
"""Return GODag object. Initialize, if necessary."""
from goatools.obo_parser import GODag
download_go_basic_obo(fin_obo, prt, loading_bar)
return GODag(fin_obo, optional_attrs, load_obsolete=False, prt=prt) | python | def get_godag(fin_obo="go-basic.obo", prt=sys.stdout, loading_bar=True, optional_attrs=None):
from goatools.obo_parser import GODag
download_go_basic_obo(fin_obo, prt, loading_bar)
return GODag(fin_obo, optional_attrs, load_obsolete=False, prt=prt) | [
"def",
"get_godag",
"(",
"fin_obo",
"=",
"\"go-basic.obo\"",
",",
"prt",
"=",
"sys",
".",
"stdout",
",",
"loading_bar",
"=",
"True",
",",
"optional_attrs",
"=",
"None",
")",
":",
"from",
"goatools",
".",
"obo_parser",
"import",
"GODag",
"download_go_basic_obo"... | Return GODag object. Initialize, if necessary. | [
"Return",
"GODag",
"object",
".",
"Initialize",
"if",
"necessary",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/base.py#L147-L151 |
242,459 | tanghaibao/goatools | goatools/base.py | dnld_gaf | def dnld_gaf(species_txt, prt=sys.stdout, loading_bar=True):
"""Download GAF file if necessary."""
return dnld_gafs([species_txt], prt, loading_bar)[0] | python | def dnld_gaf(species_txt, prt=sys.stdout, loading_bar=True):
return dnld_gafs([species_txt], prt, loading_bar)[0] | [
"def",
"dnld_gaf",
"(",
"species_txt",
",",
"prt",
"=",
"sys",
".",
"stdout",
",",
"loading_bar",
"=",
"True",
")",
":",
"return",
"dnld_gafs",
"(",
"[",
"species_txt",
"]",
",",
"prt",
",",
"loading_bar",
")",
"[",
"0",
"]"
] | Download GAF file if necessary. | [
"Download",
"GAF",
"file",
"if",
"necessary",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/base.py#L153-L155 |
242,460 | tanghaibao/goatools | goatools/base.py | dnld_gafs | def dnld_gafs(species_list, prt=sys.stdout, loading_bar=True):
"""Download GAF files if necessary."""
# Example GAF files in http://current.geneontology.org/annotations/:
# http://current.geneontology.org/annotations/mgi.gaf.gz
# http://current.geneontology.org/annotations/fb.gaf.gz
# http://current.geneontology.org/annotations/goa_human.gaf.gz
http = "http://current.geneontology.org/annotations"
# There are two filename patterns for gene associations on geneontology.org
fin_gafs = []
cwd = os.getcwd()
for species_txt in species_list: # e.g., goa_human mgi fb
gaf_base = '{ABC}.gaf'.format(ABC=species_txt) # goa_human.gaf
gaf_cwd = os.path.join(cwd, gaf_base) # {CWD}/goa_human.gaf
wget_cmd = "{HTTP}/{GAF}.gz".format(HTTP=http, GAF=gaf_base)
dnld_file(wget_cmd, gaf_cwd, prt, loading_bar)
fin_gafs.append(gaf_cwd)
return fin_gafs | python | def dnld_gafs(species_list, prt=sys.stdout, loading_bar=True):
# Example GAF files in http://current.geneontology.org/annotations/:
# http://current.geneontology.org/annotations/mgi.gaf.gz
# http://current.geneontology.org/annotations/fb.gaf.gz
# http://current.geneontology.org/annotations/goa_human.gaf.gz
http = "http://current.geneontology.org/annotations"
# There are two filename patterns for gene associations on geneontology.org
fin_gafs = []
cwd = os.getcwd()
for species_txt in species_list: # e.g., goa_human mgi fb
gaf_base = '{ABC}.gaf'.format(ABC=species_txt) # goa_human.gaf
gaf_cwd = os.path.join(cwd, gaf_base) # {CWD}/goa_human.gaf
wget_cmd = "{HTTP}/{GAF}.gz".format(HTTP=http, GAF=gaf_base)
dnld_file(wget_cmd, gaf_cwd, prt, loading_bar)
fin_gafs.append(gaf_cwd)
return fin_gafs | [
"def",
"dnld_gafs",
"(",
"species_list",
",",
"prt",
"=",
"sys",
".",
"stdout",
",",
"loading_bar",
"=",
"True",
")",
":",
"# Example GAF files in http://current.geneontology.org/annotations/:",
"# http://current.geneontology.org/annotations/mgi.gaf.gz",
"# http://current.ge... | Download GAF files if necessary. | [
"Download",
"GAF",
"files",
"if",
"necessary",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/base.py#L157-L173 |
242,461 | tanghaibao/goatools | goatools/base.py | http_get | def http_get(url, fout=None):
"""Download a file from http. Save it in a file named by fout"""
print('requests.get({URL}, stream=True)'.format(URL=url))
rsp = requests.get(url, stream=True)
if rsp.status_code == 200 and fout is not None:
with open(fout, 'wb') as prt:
for chunk in rsp: # .iter_content(chunk_size=128):
prt.write(chunk)
print(' WROTE: {F}\n'.format(F=fout))
else:
print(rsp.status_code, rsp.reason, url)
print(rsp.content)
return rsp | python | def http_get(url, fout=None):
print('requests.get({URL}, stream=True)'.format(URL=url))
rsp = requests.get(url, stream=True)
if rsp.status_code == 200 and fout is not None:
with open(fout, 'wb') as prt:
for chunk in rsp: # .iter_content(chunk_size=128):
prt.write(chunk)
print(' WROTE: {F}\n'.format(F=fout))
else:
print(rsp.status_code, rsp.reason, url)
print(rsp.content)
return rsp | [
"def",
"http_get",
"(",
"url",
",",
"fout",
"=",
"None",
")",
":",
"print",
"(",
"'requests.get({URL}, stream=True)'",
".",
"format",
"(",
"URL",
"=",
"url",
")",
")",
"rsp",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"... | Download a file from http. Save it in a file named by fout | [
"Download",
"a",
"file",
"from",
"http",
".",
"Save",
"it",
"in",
"a",
"file",
"named",
"by",
"fout"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/base.py#L175-L187 |
242,462 | tanghaibao/goatools | goatools/base.py | ftp_get | def ftp_get(fin_src, fout):
"""Download a file from an ftp server"""
assert fin_src[:6] == 'ftp://', fin_src
dir_full, fin_ftp = os.path.split(fin_src[6:])
pt0 = dir_full.find('/')
assert pt0 != -1, pt0
ftphost = dir_full[:pt0]
chg_dir = dir_full[pt0+1:]
print('FTP RETR {HOST} {DIR} {SRC} -> {DST}'.format(
HOST=ftphost, DIR=chg_dir, SRC=fin_ftp, DST=fout))
ftp = FTP(ftphost) # connect to host, default port ftp.ncbi.nlm.nih.gov
ftp.login() # user anonymous, passwd anonymous@
ftp.cwd(chg_dir) # change into "debian" directory gene/DATA
cmd = 'RETR {F}'.format(F=fin_ftp) # gene2go.gz
ftp.retrbinary(cmd, open(fout, 'wb').write) # /usr/home/gene2go.gz
ftp.quit() | python | def ftp_get(fin_src, fout):
assert fin_src[:6] == 'ftp://', fin_src
dir_full, fin_ftp = os.path.split(fin_src[6:])
pt0 = dir_full.find('/')
assert pt0 != -1, pt0
ftphost = dir_full[:pt0]
chg_dir = dir_full[pt0+1:]
print('FTP RETR {HOST} {DIR} {SRC} -> {DST}'.format(
HOST=ftphost, DIR=chg_dir, SRC=fin_ftp, DST=fout))
ftp = FTP(ftphost) # connect to host, default port ftp.ncbi.nlm.nih.gov
ftp.login() # user anonymous, passwd anonymous@
ftp.cwd(chg_dir) # change into "debian" directory gene/DATA
cmd = 'RETR {F}'.format(F=fin_ftp) # gene2go.gz
ftp.retrbinary(cmd, open(fout, 'wb').write) # /usr/home/gene2go.gz
ftp.quit() | [
"def",
"ftp_get",
"(",
"fin_src",
",",
"fout",
")",
":",
"assert",
"fin_src",
"[",
":",
"6",
"]",
"==",
"'ftp://'",
",",
"fin_src",
"dir_full",
",",
"fin_ftp",
"=",
"os",
".",
"path",
".",
"split",
"(",
"fin_src",
"[",
"6",
":",
"]",
")",
"pt0",
... | Download a file from an ftp server | [
"Download",
"a",
"file",
"from",
"an",
"ftp",
"server"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/base.py#L189-L204 |
242,463 | tanghaibao/goatools | goatools/base.py | dnld_file | def dnld_file(src_ftp, dst_file, prt=sys.stdout, loading_bar=True):
"""Download specified file if necessary."""
if os.path.isfile(dst_file):
return
do_gunzip = src_ftp[-3:] == '.gz' and dst_file[-3:] != '.gz'
dst_wget = "{DST}.gz".format(DST=dst_file) if do_gunzip else dst_file
# Write to stderr, not stdout so this message will be seen when running nosetests
wget_msg = "wget({SRC} out={DST})\n".format(SRC=src_ftp, DST=dst_wget)
#### sys.stderr.write(" {WGET}".format(WGET=wget_msg))
#### if loading_bar:
#### loading_bar = wget.bar_adaptive
try:
#### wget.download(src_ftp, out=dst_wget, bar=loading_bar)
rsp = http_get(src_ftp, dst_wget) if src_ftp[:4] == 'http' else ftp_get(src_ftp, dst_wget)
if do_gunzip:
if prt is not None:
prt.write(" gunzip {FILE}\n".format(FILE=dst_wget))
gzip_open_to(dst_wget, dst_file)
except IOError as errmsg:
import traceback
traceback.print_exc()
sys.stderr.write("**FATAL cmd: {WGET}".format(WGET=wget_msg))
sys.stderr.write("**FATAL msg: {ERR}".format(ERR=str(errmsg)))
sys.exit(1) | python | def dnld_file(src_ftp, dst_file, prt=sys.stdout, loading_bar=True):
if os.path.isfile(dst_file):
return
do_gunzip = src_ftp[-3:] == '.gz' and dst_file[-3:] != '.gz'
dst_wget = "{DST}.gz".format(DST=dst_file) if do_gunzip else dst_file
# Write to stderr, not stdout so this message will be seen when running nosetests
wget_msg = "wget({SRC} out={DST})\n".format(SRC=src_ftp, DST=dst_wget)
#### sys.stderr.write(" {WGET}".format(WGET=wget_msg))
#### if loading_bar:
#### loading_bar = wget.bar_adaptive
try:
#### wget.download(src_ftp, out=dst_wget, bar=loading_bar)
rsp = http_get(src_ftp, dst_wget) if src_ftp[:4] == 'http' else ftp_get(src_ftp, dst_wget)
if do_gunzip:
if prt is not None:
prt.write(" gunzip {FILE}\n".format(FILE=dst_wget))
gzip_open_to(dst_wget, dst_file)
except IOError as errmsg:
import traceback
traceback.print_exc()
sys.stderr.write("**FATAL cmd: {WGET}".format(WGET=wget_msg))
sys.stderr.write("**FATAL msg: {ERR}".format(ERR=str(errmsg)))
sys.exit(1) | [
"def",
"dnld_file",
"(",
"src_ftp",
",",
"dst_file",
",",
"prt",
"=",
"sys",
".",
"stdout",
",",
"loading_bar",
"=",
"True",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"dst_file",
")",
":",
"return",
"do_gunzip",
"=",
"src_ftp",
"[",
"-",... | Download specified file if necessary. | [
"Download",
"specified",
"file",
"if",
"necessary",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/base.py#L207-L230 |
242,464 | tanghaibao/goatools | goatools/godag/obo_optional_attributes.py | OboOptionalAttrs.init_datamembers | def init_datamembers(self, rec):
"""Initialize current GOTerm with data members for storing optional attributes."""
# pylint: disable=multiple-statements
if 'synonym' in self.optional_attrs: rec.synonym = []
if 'xref' in self.optional_attrs: rec.xref = set()
if 'subset' in self.optional_attrs: rec.subset = set()
if 'comment' in self.optional_attrs: rec.comment = ""
if 'relationship' in self.optional_attrs:
rec.relationship = {}
rec.relationship_rev = {} | python | def init_datamembers(self, rec):
# pylint: disable=multiple-statements
if 'synonym' in self.optional_attrs: rec.synonym = []
if 'xref' in self.optional_attrs: rec.xref = set()
if 'subset' in self.optional_attrs: rec.subset = set()
if 'comment' in self.optional_attrs: rec.comment = ""
if 'relationship' in self.optional_attrs:
rec.relationship = {}
rec.relationship_rev = {} | [
"def",
"init_datamembers",
"(",
"self",
",",
"rec",
")",
":",
"# pylint: disable=multiple-statements",
"if",
"'synonym'",
"in",
"self",
".",
"optional_attrs",
":",
"rec",
".",
"synonym",
"=",
"[",
"]",
"if",
"'xref'",
"in",
"self",
".",
"optional_attrs",
":",
... | Initialize current GOTerm with data members for storing optional attributes. | [
"Initialize",
"current",
"GOTerm",
"with",
"data",
"members",
"for",
"storing",
"optional",
"attributes",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag/obo_optional_attributes.py#L51-L60 |
242,465 | tanghaibao/goatools | goatools/godag/obo_optional_attributes.py | OboOptionalAttrs._get_synonym | def _get_synonym(self, line):
"""Given line, return optional attribute synonym value in a namedtuple.
Example synonym and its storage in a namedtuple:
synonym: "The other white meat" EXACT MARKETING_SLOGAN [MEAT:00324, BACONBASE:03021]
text: "The other white meat"
scope: EXACT
typename: MARKETING_SLOGAN
dbxrefs: set(["MEAT:00324", "BACONBASE:03021"])
Example synonyms:
"peptidase inhibitor complex" EXACT [GOC:bf, GOC:pr]
"regulation of postsynaptic cytosolic calcium levels" EXACT syngo_official_label []
"tocopherol 13-hydroxylase activity" EXACT systematic_synonym []
"""
mtch = self.attr2cmp['synonym'].match(line)
text, scope, typename, dbxrefs, _ = mtch.groups()
typename = typename.strip()
dbxrefs = set(dbxrefs.split(', ')) if dbxrefs else set()
return self.attr2cmp['synonym nt']._make([text, scope, typename, dbxrefs]) | python | def _get_synonym(self, line):
mtch = self.attr2cmp['synonym'].match(line)
text, scope, typename, dbxrefs, _ = mtch.groups()
typename = typename.strip()
dbxrefs = set(dbxrefs.split(', ')) if dbxrefs else set()
return self.attr2cmp['synonym nt']._make([text, scope, typename, dbxrefs]) | [
"def",
"_get_synonym",
"(",
"self",
",",
"line",
")",
":",
"mtch",
"=",
"self",
".",
"attr2cmp",
"[",
"'synonym'",
"]",
".",
"match",
"(",
"line",
")",
"text",
",",
"scope",
",",
"typename",
",",
"dbxrefs",
",",
"_",
"=",
"mtch",
".",
"groups",
"("... | Given line, return optional attribute synonym value in a namedtuple.
Example synonym and its storage in a namedtuple:
synonym: "The other white meat" EXACT MARKETING_SLOGAN [MEAT:00324, BACONBASE:03021]
text: "The other white meat"
scope: EXACT
typename: MARKETING_SLOGAN
dbxrefs: set(["MEAT:00324", "BACONBASE:03021"])
Example synonyms:
"peptidase inhibitor complex" EXACT [GOC:bf, GOC:pr]
"regulation of postsynaptic cytosolic calcium levels" EXACT syngo_official_label []
"tocopherol 13-hydroxylase activity" EXACT systematic_synonym [] | [
"Given",
"line",
"return",
"optional",
"attribute",
"synonym",
"value",
"in",
"a",
"namedtuple",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag/obo_optional_attributes.py#L62-L81 |
242,466 | tanghaibao/goatools | goatools/godag/obo_optional_attributes.py | OboOptionalAttrs._get_xref | def _get_xref(self, line):
"""Given line, return optional attribute xref value in a dict of sets."""
# Ex: Wikipedia:Zygotene
# Ex: Reactome:REACT_22295 "Addition of a third mannose to ..."
mtch = self.attr2cmp['xref'].match(line)
return mtch.group(1).replace(' ', '') | python | def _get_xref(self, line):
# Ex: Wikipedia:Zygotene
# Ex: Reactome:REACT_22295 "Addition of a third mannose to ..."
mtch = self.attr2cmp['xref'].match(line)
return mtch.group(1).replace(' ', '') | [
"def",
"_get_xref",
"(",
"self",
",",
"line",
")",
":",
"# Ex: Wikipedia:Zygotene",
"# Ex: Reactome:REACT_22295 \"Addition of a third mannose to ...\"",
"mtch",
"=",
"self",
".",
"attr2cmp",
"[",
"'xref'",
"]",
".",
"match",
"(",
"line",
")",
"return",
"mtch",
".",
... | Given line, return optional attribute xref value in a dict of sets. | [
"Given",
"line",
"return",
"optional",
"attribute",
"xref",
"value",
"in",
"a",
"dict",
"of",
"sets",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag/obo_optional_attributes.py#L83-L88 |
242,467 | tanghaibao/goatools | goatools/godag/obo_optional_attributes.py | OboOptionalAttrs._init_compile_patterns | def _init_compile_patterns(optional_attrs):
"""Compile search patterns for optional attributes if needed."""
attr2cmp = {}
if optional_attrs is None:
return attr2cmp
# "peptidase inhibitor complex" EXACT [GOC:bf, GOC:pr]
# "blood vessel formation from pre-existing blood vessels" EXACT systematic_synonym []
# "mitochondrial inheritance" EXACT []
# "tricarboxylate transport protein" RELATED [] {comment="WIkipedia:Mitochondrial_carrier"}
if 'synonym' in optional_attrs:
attr2cmp['synonym'] = re.compile(r'"(\S.*\S)" ([A-Z]+) (.*)\[(.*)\](.*)$')
attr2cmp['synonym nt'] = cx.namedtuple("synonym", "text scope typename dbxrefs")
# Wikipedia:Zygotene
# Reactome:REACT_27267 "DHAP from Ery4P and PEP, Mycobacterium tuberculosis"
if 'xref' in optional_attrs:
attr2cmp['xref'] = re.compile(r'^(\S+:\s*\S+)\b(.*)$')
return attr2cmp | python | def _init_compile_patterns(optional_attrs):
attr2cmp = {}
if optional_attrs is None:
return attr2cmp
# "peptidase inhibitor complex" EXACT [GOC:bf, GOC:pr]
# "blood vessel formation from pre-existing blood vessels" EXACT systematic_synonym []
# "mitochondrial inheritance" EXACT []
# "tricarboxylate transport protein" RELATED [] {comment="WIkipedia:Mitochondrial_carrier"}
if 'synonym' in optional_attrs:
attr2cmp['synonym'] = re.compile(r'"(\S.*\S)" ([A-Z]+) (.*)\[(.*)\](.*)$')
attr2cmp['synonym nt'] = cx.namedtuple("synonym", "text scope typename dbxrefs")
# Wikipedia:Zygotene
# Reactome:REACT_27267 "DHAP from Ery4P and PEP, Mycobacterium tuberculosis"
if 'xref' in optional_attrs:
attr2cmp['xref'] = re.compile(r'^(\S+:\s*\S+)\b(.*)$')
return attr2cmp | [
"def",
"_init_compile_patterns",
"(",
"optional_attrs",
")",
":",
"attr2cmp",
"=",
"{",
"}",
"if",
"optional_attrs",
"is",
"None",
":",
"return",
"attr2cmp",
"# \"peptidase inhibitor complex\" EXACT [GOC:bf, GOC:pr]",
"# \"blood vessel formation from pre-existing blood vessels\" ... | Compile search patterns for optional attributes if needed. | [
"Compile",
"search",
"patterns",
"for",
"optional",
"attributes",
"if",
"needed",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag/obo_optional_attributes.py#L91-L107 |
242,468 | tanghaibao/goatools | goatools/cli/wr_hierarchy.py | cli | def cli():
"""Command-line script to print a GO term's lower-level hierarchy."""
objcli = WrHierCli(sys.argv[1:])
fouts_txt = objcli.get_fouts()
if fouts_txt:
for fout_txt in fouts_txt:
objcli.wrtxt_hier(fout_txt)
else:
objcli.prt_hier(sys.stdout) | python | def cli():
objcli = WrHierCli(sys.argv[1:])
fouts_txt = objcli.get_fouts()
if fouts_txt:
for fout_txt in fouts_txt:
objcli.wrtxt_hier(fout_txt)
else:
objcli.prt_hier(sys.stdout) | [
"def",
"cli",
"(",
")",
":",
"objcli",
"=",
"WrHierCli",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"fouts_txt",
"=",
"objcli",
".",
"get_fouts",
"(",
")",
"if",
"fouts_txt",
":",
"for",
"fout_txt",
"in",
"fouts_txt",
":",
"objcli",
".",
"wr... | Command-line script to print a GO term's lower-level hierarchy. | [
"Command",
"-",
"line",
"script",
"to",
"print",
"a",
"GO",
"term",
"s",
"lower",
"-",
"level",
"hierarchy",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/wr_hierarchy.py#L50-L58 |
242,469 | tanghaibao/goatools | goatools/cli/wr_hierarchy.py | WrHierCli.get_fouts | def get_fouts(self):
"""Get output filename."""
fouts_txt = []
if 'o' in self.kws:
fouts_txt.append(self.kws['o'])
if 'f' in self.kws:
fouts_txt.append(self._get_fout_go())
return fouts_txt | python | def get_fouts(self):
fouts_txt = []
if 'o' in self.kws:
fouts_txt.append(self.kws['o'])
if 'f' in self.kws:
fouts_txt.append(self._get_fout_go())
return fouts_txt | [
"def",
"get_fouts",
"(",
"self",
")",
":",
"fouts_txt",
"=",
"[",
"]",
"if",
"'o'",
"in",
"self",
".",
"kws",
":",
"fouts_txt",
".",
"append",
"(",
"self",
".",
"kws",
"[",
"'o'",
"]",
")",
"if",
"'f'",
"in",
"self",
".",
"kws",
":",
"fouts_txt",... | Get output filename. | [
"Get",
"output",
"filename",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/wr_hierarchy.py#L107-L114 |
242,470 | tanghaibao/goatools | goatools/cli/wr_hierarchy.py | WrHierCli._get_fout_go | def _get_fout_go(self):
"""Get the name of an output file based on the top GO term."""
assert self.goids, "NO VALID GO IDs WERE PROVIDED AS STARTING POINTS FOR HIERARCHY REPORT"
base = next(iter(self.goids)).replace(':', '')
upstr = '_up' if 'up' in self.kws else ''
return "hier_{BASE}{UP}.{EXT}".format(BASE=base, UP=upstr, EXT='txt') | python | def _get_fout_go(self):
assert self.goids, "NO VALID GO IDs WERE PROVIDED AS STARTING POINTS FOR HIERARCHY REPORT"
base = next(iter(self.goids)).replace(':', '')
upstr = '_up' if 'up' in self.kws else ''
return "hier_{BASE}{UP}.{EXT}".format(BASE=base, UP=upstr, EXT='txt') | [
"def",
"_get_fout_go",
"(",
"self",
")",
":",
"assert",
"self",
".",
"goids",
",",
"\"NO VALID GO IDs WERE PROVIDED AS STARTING POINTS FOR HIERARCHY REPORT\"",
"base",
"=",
"next",
"(",
"iter",
"(",
"self",
".",
"goids",
")",
")",
".",
"replace",
"(",
"':'",
","... | Get the name of an output file based on the top GO term. | [
"Get",
"the",
"name",
"of",
"an",
"output",
"file",
"based",
"on",
"the",
"top",
"GO",
"term",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/wr_hierarchy.py#L116-L121 |
242,471 | tanghaibao/goatools | goatools/cli/wr_hierarchy.py | WrHierCli.wrtxt_hier | def wrtxt_hier(self, fout_txt):
"""Write hierarchy below specfied GO IDs to an ASCII file."""
with open(fout_txt, 'wb') as prt:
self.prt_hier(prt)
print(" WROTE: {TXT}".format(TXT=fout_txt)) | python | def wrtxt_hier(self, fout_txt):
with open(fout_txt, 'wb') as prt:
self.prt_hier(prt)
print(" WROTE: {TXT}".format(TXT=fout_txt)) | [
"def",
"wrtxt_hier",
"(",
"self",
",",
"fout_txt",
")",
":",
"with",
"open",
"(",
"fout_txt",
",",
"'wb'",
")",
"as",
"prt",
":",
"self",
".",
"prt_hier",
"(",
"prt",
")",
"print",
"(",
"\" WROTE: {TXT}\"",
".",
"format",
"(",
"TXT",
"=",
"fout_txt",
... | Write hierarchy below specfied GO IDs to an ASCII file. | [
"Write",
"hierarchy",
"below",
"specfied",
"GO",
"IDs",
"to",
"an",
"ASCII",
"file",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/wr_hierarchy.py#L123-L127 |
242,472 | tanghaibao/goatools | goatools/cli/wr_hierarchy.py | WrHierCli.prt_hier | def prt_hier(self, prt=sys.stdout):
"""Write hierarchy below specfied GO IDs."""
objwr = WrHierGO(self.gosubdag, **self.kws)
assert self.goids, "NO VALID GO IDs WERE PROVIDED"
if 'up' not in objwr.usrset:
for goid in self.goids:
objwr.prt_hier_down(goid, prt)
else:
objwr.prt_hier_up(self.goids, prt) | python | def prt_hier(self, prt=sys.stdout):
objwr = WrHierGO(self.gosubdag, **self.kws)
assert self.goids, "NO VALID GO IDs WERE PROVIDED"
if 'up' not in objwr.usrset:
for goid in self.goids:
objwr.prt_hier_down(goid, prt)
else:
objwr.prt_hier_up(self.goids, prt) | [
"def",
"prt_hier",
"(",
"self",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"objwr",
"=",
"WrHierGO",
"(",
"self",
".",
"gosubdag",
",",
"*",
"*",
"self",
".",
"kws",
")",
"assert",
"self",
".",
"goids",
",",
"\"NO VALID GO IDs WERE PROVIDED\"",
"... | Write hierarchy below specfied GO IDs. | [
"Write",
"hierarchy",
"below",
"specfied",
"GO",
"IDs",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/wr_hierarchy.py#L129-L137 |
242,473 | tanghaibao/goatools | goatools/cli/wr_hierarchy.py | WrHierCli._adj_for_assc | def _adj_for_assc(self):
"""Print only GO IDs from associations and their ancestors."""
if self.gene2gos:
gos_assoc = set(get_b2aset(self.gene2gos).keys())
if 'item_marks' not in self.kws:
self.kws['item_marks'] = {go:'>' for go in gos_assoc}
if 'include_only' not in self.kws:
gosubdag = GoSubDag(gos_assoc, self.gosubdag.go2obj,
self.gosubdag.relationships)
self.kws['include_only'] = gosubdag.go2obj | python | def _adj_for_assc(self):
if self.gene2gos:
gos_assoc = set(get_b2aset(self.gene2gos).keys())
if 'item_marks' not in self.kws:
self.kws['item_marks'] = {go:'>' for go in gos_assoc}
if 'include_only' not in self.kws:
gosubdag = GoSubDag(gos_assoc, self.gosubdag.go2obj,
self.gosubdag.relationships)
self.kws['include_only'] = gosubdag.go2obj | [
"def",
"_adj_for_assc",
"(",
"self",
")",
":",
"if",
"self",
".",
"gene2gos",
":",
"gos_assoc",
"=",
"set",
"(",
"get_b2aset",
"(",
"self",
".",
"gene2gos",
")",
".",
"keys",
"(",
")",
")",
"if",
"'item_marks'",
"not",
"in",
"self",
".",
"kws",
":",
... | Print only GO IDs from associations and their ancestors. | [
"Print",
"only",
"GO",
"IDs",
"from",
"associations",
"and",
"their",
"ancestors",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/wr_hierarchy.py#L165-L174 |
242,474 | tanghaibao/goatools | goatools/pvalcalc.py | PvalCalcBase.calc_pvalue | def calc_pvalue(self, study_count, study_n, pop_count, pop_n):
"""pvalues are calculated in derived classes."""
fnc_call = "calc_pvalue({SCNT}, {STOT}, {PCNT} {PTOT})".format(
SCNT=study_count, STOT=study_n, PCNT=pop_count, PTOT=pop_n)
raise Exception("NOT IMPLEMENTED: {FNC_CALL} using {FNC}.".format(
FNC_CALL=fnc_call, FNC=self.pval_fnc)) | python | def calc_pvalue(self, study_count, study_n, pop_count, pop_n):
fnc_call = "calc_pvalue({SCNT}, {STOT}, {PCNT} {PTOT})".format(
SCNT=study_count, STOT=study_n, PCNT=pop_count, PTOT=pop_n)
raise Exception("NOT IMPLEMENTED: {FNC_CALL} using {FNC}.".format(
FNC_CALL=fnc_call, FNC=self.pval_fnc)) | [
"def",
"calc_pvalue",
"(",
"self",
",",
"study_count",
",",
"study_n",
",",
"pop_count",
",",
"pop_n",
")",
":",
"fnc_call",
"=",
"\"calc_pvalue({SCNT}, {STOT}, {PCNT} {PTOT})\"",
".",
"format",
"(",
"SCNT",
"=",
"study_count",
",",
"STOT",
"=",
"study_n",
",",
... | pvalues are calculated in derived classes. | [
"pvalues",
"are",
"calculated",
"in",
"derived",
"classes",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/pvalcalc.py#L19-L24 |
242,475 | tanghaibao/goatools | goatools/pvalcalc.py | FisherFactory._init_pval_obj | def _init_pval_obj(self):
"""Returns a Fisher object based on user-input."""
if self.pval_fnc_name in self.options.keys():
try:
fisher_obj = self.options[self.pval_fnc_name](self.pval_fnc_name, self.log)
except ImportError:
print("fisher module not installed. Falling back on scipy.stats.fisher_exact")
fisher_obj = self.options['fisher_scipy_stats']('fisher_scipy_stats', self.log)
return fisher_obj
raise Exception("PVALUE FUNCTION({FNC}) NOT FOUND".format(FNC=self.pval_fnc_name)) | python | def _init_pval_obj(self):
if self.pval_fnc_name in self.options.keys():
try:
fisher_obj = self.options[self.pval_fnc_name](self.pval_fnc_name, self.log)
except ImportError:
print("fisher module not installed. Falling back on scipy.stats.fisher_exact")
fisher_obj = self.options['fisher_scipy_stats']('fisher_scipy_stats', self.log)
return fisher_obj
raise Exception("PVALUE FUNCTION({FNC}) NOT FOUND".format(FNC=self.pval_fnc_name)) | [
"def",
"_init_pval_obj",
"(",
"self",
")",
":",
"if",
"self",
".",
"pval_fnc_name",
"in",
"self",
".",
"options",
".",
"keys",
"(",
")",
":",
"try",
":",
"fisher_obj",
"=",
"self",
".",
"options",
"[",
"self",
".",
"pval_fnc_name",
"]",
"(",
"self",
... | Returns a Fisher object based on user-input. | [
"Returns",
"a",
"Fisher",
"object",
"based",
"on",
"user",
"-",
"input",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/pvalcalc.py#L90-L101 |
242,476 | tanghaibao/goatools | setup_helper.py | SetupHelper.check_version | def check_version(self, name, majorv=2, minorv=7):
""" Make sure the package runs on the supported Python version
"""
if sys.version_info.major == majorv and sys.version_info.minor != minorv:
sys.stderr.write("ERROR: %s is only for >= Python %d.%d but you are running %d.%d\n" %\
(name, majorv, minorv, sys.version_info.major, sys.version_info.minor))
sys.exit(1) | python | def check_version(self, name, majorv=2, minorv=7):
if sys.version_info.major == majorv and sys.version_info.minor != minorv:
sys.stderr.write("ERROR: %s is only for >= Python %d.%d but you are running %d.%d\n" %\
(name, majorv, minorv, sys.version_info.major, sys.version_info.minor))
sys.exit(1) | [
"def",
"check_version",
"(",
"self",
",",
"name",
",",
"majorv",
"=",
"2",
",",
"minorv",
"=",
"7",
")",
":",
"if",
"sys",
".",
"version_info",
".",
"major",
"==",
"majorv",
"and",
"sys",
".",
"version_info",
".",
"minor",
"!=",
"minorv",
":",
"sys",... | Make sure the package runs on the supported Python version | [
"Make",
"sure",
"the",
"package",
"runs",
"on",
"the",
"supported",
"Python",
"version"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/setup_helper.py#L21-L27 |
242,477 | tanghaibao/goatools | setup_helper.py | SetupHelper.get_init | def get_init(self, filename="__init__.py"):
""" Get various info from the package without importing them
"""
import ast
with open(filename) as init_file:
module = ast.parse(init_file.read())
itr = lambda x: (ast.literal_eval(node.value) for node in ast.walk(module) \
if isinstance(node, ast.Assign) and node.targets[0].id == x)
try:
return next(itr("__author__")), \
next(itr("__email__")), \
next(itr("__license__")), \
next(itr("__version__"))
except StopIteration:
raise ValueError("One of author, email, license, or version"
" cannot be found in {}".format(filename)) | python | def get_init(self, filename="__init__.py"):
import ast
with open(filename) as init_file:
module = ast.parse(init_file.read())
itr = lambda x: (ast.literal_eval(node.value) for node in ast.walk(module) \
if isinstance(node, ast.Assign) and node.targets[0].id == x)
try:
return next(itr("__author__")), \
next(itr("__email__")), \
next(itr("__license__")), \
next(itr("__version__"))
except StopIteration:
raise ValueError("One of author, email, license, or version"
" cannot be found in {}".format(filename)) | [
"def",
"get_init",
"(",
"self",
",",
"filename",
"=",
"\"__init__.py\"",
")",
":",
"import",
"ast",
"with",
"open",
"(",
"filename",
")",
"as",
"init_file",
":",
"module",
"=",
"ast",
".",
"parse",
"(",
"init_file",
".",
"read",
"(",
")",
")",
"itr",
... | Get various info from the package without importing them | [
"Get",
"various",
"info",
"from",
"the",
"package",
"without",
"importing",
"them"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/setup_helper.py#L29-L47 |
242,478 | tanghaibao/goatools | setup_helper.py | SetupHelper.missing_requirements | def missing_requirements(self, specifiers):
""" Find what's missing
"""
for specifier in specifiers:
try:
pkg_resources.require(specifier)
except pkg_resources.DistributionNotFound:
yield specifier | python | def missing_requirements(self, specifiers):
for specifier in specifiers:
try:
pkg_resources.require(specifier)
except pkg_resources.DistributionNotFound:
yield specifier | [
"def",
"missing_requirements",
"(",
"self",
",",
"specifiers",
")",
":",
"for",
"specifier",
"in",
"specifiers",
":",
"try",
":",
"pkg_resources",
".",
"require",
"(",
"specifier",
")",
"except",
"pkg_resources",
".",
"DistributionNotFound",
":",
"yield",
"speci... | Find what's missing | [
"Find",
"what",
"s",
"missing"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/setup_helper.py#L49-L56 |
242,479 | tanghaibao/goatools | setup_helper.py | SetupHelper.install_requirements | def install_requirements(self, requires):
""" Install the listed requirements
"""
# Temporarily install dependencies required by setup.py before trying to import them.
sys.path[0:0] = ['setup-requires']
pkg_resources.working_set.add_entry('setup-requires')
to_install = list(self.missing_requirements(requires))
if to_install:
cmd = [sys.executable, "-m", "pip", "install",
"-t", "setup-requires"] + to_install
subprocess.call(cmd) | python | def install_requirements(self, requires):
# Temporarily install dependencies required by setup.py before trying to import them.
sys.path[0:0] = ['setup-requires']
pkg_resources.working_set.add_entry('setup-requires')
to_install = list(self.missing_requirements(requires))
if to_install:
cmd = [sys.executable, "-m", "pip", "install",
"-t", "setup-requires"] + to_install
subprocess.call(cmd) | [
"def",
"install_requirements",
"(",
"self",
",",
"requires",
")",
":",
"# Temporarily install dependencies required by setup.py before trying to import them.",
"sys",
".",
"path",
"[",
"0",
":",
"0",
"]",
"=",
"[",
"'setup-requires'",
"]",
"pkg_resources",
".",
"working... | Install the listed requirements | [
"Install",
"the",
"listed",
"requirements"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/setup_helper.py#L58-L69 |
242,480 | tanghaibao/goatools | setup_helper.py | SetupHelper.get_long_description | def get_long_description(self, filename='README.md'):
""" I really prefer Markdown to reStructuredText. PyPi does not.
"""
try:
import pypandoc
description = pypandoc.convert_file('README.md', 'rst', 'md')
except (IOError, ImportError):
description = open("README.md").read()
return description | python | def get_long_description(self, filename='README.md'):
try:
import pypandoc
description = pypandoc.convert_file('README.md', 'rst', 'md')
except (IOError, ImportError):
description = open("README.md").read()
return description | [
"def",
"get_long_description",
"(",
"self",
",",
"filename",
"=",
"'README.md'",
")",
":",
"try",
":",
"import",
"pypandoc",
"description",
"=",
"pypandoc",
".",
"convert_file",
"(",
"'README.md'",
",",
"'rst'",
",",
"'md'",
")",
"except",
"(",
"IOError",
",... | I really prefer Markdown to reStructuredText. PyPi does not. | [
"I",
"really",
"prefer",
"Markdown",
"to",
"reStructuredText",
".",
"PyPi",
"does",
"not",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/setup_helper.py#L71-L79 |
242,481 | tanghaibao/goatools | goatools/grouper/sorter.py | Sorter.prt_gos | def prt_gos(self, prt=sys.stdout, **kws_usr):
"""Sort user GO ids, grouped under broader GO terms or sections. Print to screen."""
# deprecated
# Keyword arguments (control content): hdrgo_prt section_prt use_sections
# desc2nts contains: (sections hdrgo_prt sortobj) or (flat hdrgo_prt sortobj)
desc2nts = self.get_desc2nts(**kws_usr)
# Keyword arguments (control print format): prt prtfmt
self.prt_nts(desc2nts, prt, kws_usr.get('prtfmt'))
return desc2nts | python | def prt_gos(self, prt=sys.stdout, **kws_usr):
# deprecated
# Keyword arguments (control content): hdrgo_prt section_prt use_sections
# desc2nts contains: (sections hdrgo_prt sortobj) or (flat hdrgo_prt sortobj)
desc2nts = self.get_desc2nts(**kws_usr)
# Keyword arguments (control print format): prt prtfmt
self.prt_nts(desc2nts, prt, kws_usr.get('prtfmt'))
return desc2nts | [
"def",
"prt_gos",
"(",
"self",
",",
"prt",
"=",
"sys",
".",
"stdout",
",",
"*",
"*",
"kws_usr",
")",
":",
"# deprecated",
"# Keyword arguments (control content): hdrgo_prt section_prt use_sections",
"# desc2nts contains: (sections hdrgo_prt sortobj) or (flat hdrgo_prt sortobj)",
... | Sort user GO ids, grouped under broader GO terms or sections. Print to screen. | [
"Sort",
"user",
"GO",
"ids",
"grouped",
"under",
"broader",
"GO",
"terms",
"or",
"sections",
".",
"Print",
"to",
"screen",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/sorter.py#L64-L72 |
242,482 | tanghaibao/goatools | goatools/grouper/sorter.py | Sorter.get_nts_flat | def get_nts_flat(self, hdrgo_prt=True, use_sections=True):
"""Return a flat list of sorted nts."""
# Either there are no sections OR we are not using them
if self.sectobj is None or not use_sections:
return self.sortgos.get_nts_sorted(
hdrgo_prt,
hdrgos=self.grprobj.get_hdrgos(),
hdrgo_sort=True)
if not use_sections:
return self.sectobj.get_sorted_nts_omit_section(hdrgo_prt, hdrgo_sort=True)
return None | python | def get_nts_flat(self, hdrgo_prt=True, use_sections=True):
# Either there are no sections OR we are not using them
if self.sectobj is None or not use_sections:
return self.sortgos.get_nts_sorted(
hdrgo_prt,
hdrgos=self.grprobj.get_hdrgos(),
hdrgo_sort=True)
if not use_sections:
return self.sectobj.get_sorted_nts_omit_section(hdrgo_prt, hdrgo_sort=True)
return None | [
"def",
"get_nts_flat",
"(",
"self",
",",
"hdrgo_prt",
"=",
"True",
",",
"use_sections",
"=",
"True",
")",
":",
"# Either there are no sections OR we are not using them",
"if",
"self",
".",
"sectobj",
"is",
"None",
"or",
"not",
"use_sections",
":",
"return",
"self"... | Return a flat list of sorted nts. | [
"Return",
"a",
"flat",
"list",
"of",
"sorted",
"nts",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/sorter.py#L165-L175 |
242,483 | tanghaibao/goatools | goatools/grouper/grprobj.py | Grouper.get_sections_2d | def get_sections_2d(self):
"""Get 2-D list of sections and hdrgos sets actually used in grouping."""
sections_hdrgos_act = []
hdrgos_act_all = self.get_hdrgos() # Header GOs actually used to group
hdrgos_act_secs = set()
if self.hdrobj.sections:
for section_name, hdrgos_all_lst in self.hdrobj.sections:
# print("GGGGGGGGGGGGGGGGG {N:3} {NAME}".format(N=len(hdrgos_all_lst), NAME=section_name))
hdrgos_all_set = set(hdrgos_all_lst)
hdrgos_act_set = hdrgos_all_set.intersection(hdrgos_act_all)
if hdrgos_act_set:
hdrgos_act_secs |= hdrgos_act_set
# Use original order of header GOs found in sections
hdrgos_act_lst = []
hdrgos_act_ctr = cx.Counter()
for hdrgo_p in hdrgos_all_lst: # Header GO that may or may not be used.
if hdrgo_p in hdrgos_act_set and hdrgos_act_ctr[hdrgo_p] == 0:
hdrgos_act_lst.append(hdrgo_p)
hdrgos_act_ctr[hdrgo_p] += 1
sections_hdrgos_act.append((section_name, hdrgos_act_lst))
# print(">>>>>>>>>>>>>>> hdrgos_act_all {N:3}".format(N=len(hdrgos_act_all)))
# print(">>>>>>>>>>>>>>> hdrgos_act_secs {N:3}".format(N=len(hdrgos_act_secs)))
hdrgos_act_rem = hdrgos_act_all.difference(hdrgos_act_secs)
if hdrgos_act_rem:
# print("RRRRRRRRRRR {N:3}".format(N=len(hdrgos_act_rem)))
sections_hdrgos_act.append((self.hdrobj.secdflt, hdrgos_act_rem))
else:
sections_hdrgos_act.append((self.hdrobj.secdflt, hdrgos_act_all))
return sections_hdrgos_act | python | def get_sections_2d(self):
sections_hdrgos_act = []
hdrgos_act_all = self.get_hdrgos() # Header GOs actually used to group
hdrgos_act_secs = set()
if self.hdrobj.sections:
for section_name, hdrgos_all_lst in self.hdrobj.sections:
# print("GGGGGGGGGGGGGGGGG {N:3} {NAME}".format(N=len(hdrgos_all_lst), NAME=section_name))
hdrgos_all_set = set(hdrgos_all_lst)
hdrgos_act_set = hdrgos_all_set.intersection(hdrgos_act_all)
if hdrgos_act_set:
hdrgos_act_secs |= hdrgos_act_set
# Use original order of header GOs found in sections
hdrgos_act_lst = []
hdrgos_act_ctr = cx.Counter()
for hdrgo_p in hdrgos_all_lst: # Header GO that may or may not be used.
if hdrgo_p in hdrgos_act_set and hdrgos_act_ctr[hdrgo_p] == 0:
hdrgos_act_lst.append(hdrgo_p)
hdrgos_act_ctr[hdrgo_p] += 1
sections_hdrgos_act.append((section_name, hdrgos_act_lst))
# print(">>>>>>>>>>>>>>> hdrgos_act_all {N:3}".format(N=len(hdrgos_act_all)))
# print(">>>>>>>>>>>>>>> hdrgos_act_secs {N:3}".format(N=len(hdrgos_act_secs)))
hdrgos_act_rem = hdrgos_act_all.difference(hdrgos_act_secs)
if hdrgos_act_rem:
# print("RRRRRRRRRRR {N:3}".format(N=len(hdrgos_act_rem)))
sections_hdrgos_act.append((self.hdrobj.secdflt, hdrgos_act_rem))
else:
sections_hdrgos_act.append((self.hdrobj.secdflt, hdrgos_act_all))
return sections_hdrgos_act | [
"def",
"get_sections_2d",
"(",
"self",
")",
":",
"sections_hdrgos_act",
"=",
"[",
"]",
"hdrgos_act_all",
"=",
"self",
".",
"get_hdrgos",
"(",
")",
"# Header GOs actually used to group",
"hdrgos_act_secs",
"=",
"set",
"(",
")",
"if",
"self",
".",
"hdrobj",
".",
... | Get 2-D list of sections and hdrgos sets actually used in grouping. | [
"Get",
"2",
"-",
"D",
"list",
"of",
"sections",
"and",
"hdrgos",
"sets",
"actually",
"used",
"in",
"grouping",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L60-L88 |
242,484 | tanghaibao/goatools | goatools/grouper/grprobj.py | Grouper.get_usrgos_g_section | def get_usrgos_g_section(self, section=None):
"""Get usrgos in a requested section."""
if section is None:
section = self.hdrobj.secdflt
if section is True:
return self.usrgos
# Get dict of sections and hdrgos actually used in grouping
section2hdrgos = cx.OrderedDict(self.get_sections_2d())
hdrgos_lst = section2hdrgos.get(section, None)
if hdrgos_lst is not None:
hdrgos_set = set(hdrgos_lst)
hdrgos_u = hdrgos_set.intersection(self.hdrgo_is_usrgo)
hdrgos_h = hdrgos_set.intersection(self.hdrgo2usrgos.keys())
usrgos = set([u for h in hdrgos_h for u in self.hdrgo2usrgos.get(h)])
usrgos |= hdrgos_u
return usrgos
return set() | python | def get_usrgos_g_section(self, section=None):
if section is None:
section = self.hdrobj.secdflt
if section is True:
return self.usrgos
# Get dict of sections and hdrgos actually used in grouping
section2hdrgos = cx.OrderedDict(self.get_sections_2d())
hdrgos_lst = section2hdrgos.get(section, None)
if hdrgos_lst is not None:
hdrgos_set = set(hdrgos_lst)
hdrgos_u = hdrgos_set.intersection(self.hdrgo_is_usrgo)
hdrgos_h = hdrgos_set.intersection(self.hdrgo2usrgos.keys())
usrgos = set([u for h in hdrgos_h for u in self.hdrgo2usrgos.get(h)])
usrgos |= hdrgos_u
return usrgos
return set() | [
"def",
"get_usrgos_g_section",
"(",
"self",
",",
"section",
"=",
"None",
")",
":",
"if",
"section",
"is",
"None",
":",
"section",
"=",
"self",
".",
"hdrobj",
".",
"secdflt",
"if",
"section",
"is",
"True",
":",
"return",
"self",
".",
"usrgos",
"# Get dict... | Get usrgos in a requested section. | [
"Get",
"usrgos",
"in",
"a",
"requested",
"section",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L90-L106 |
242,485 | tanghaibao/goatools | goatools/grouper/grprobj.py | Grouper.get_section2usrnts | def get_section2usrnts(self):
"""Get dict section2usrnts."""
sec_nts = []
for section_name, _ in self.get_sections_2d():
usrgos = self.get_usrgos_g_section(section_name)
sec_nts.append((section_name, [self.go2nt.get(u) for u in usrgos]))
return cx.OrderedDict(sec_nts) | python | def get_section2usrnts(self):
sec_nts = []
for section_name, _ in self.get_sections_2d():
usrgos = self.get_usrgos_g_section(section_name)
sec_nts.append((section_name, [self.go2nt.get(u) for u in usrgos]))
return cx.OrderedDict(sec_nts) | [
"def",
"get_section2usrnts",
"(",
"self",
")",
":",
"sec_nts",
"=",
"[",
"]",
"for",
"section_name",
",",
"_",
"in",
"self",
".",
"get_sections_2d",
"(",
")",
":",
"usrgos",
"=",
"self",
".",
"get_usrgos_g_section",
"(",
"section_name",
")",
"sec_nts",
"."... | Get dict section2usrnts. | [
"Get",
"dict",
"section2usrnts",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L108-L114 |
242,486 | tanghaibao/goatools | goatools/grouper/grprobj.py | Grouper.get_section2items | def get_section2items(self, itemkey):
"""Collect all items into a single set per section."""
sec_items = []
section2usrnts = self.get_section2usrnts()
for section, usrnts in section2usrnts.items():
items = set([e for nt in usrnts for e in getattr(nt, itemkey, set())])
sec_items.append((section, items))
return cx.OrderedDict(sec_items) | python | def get_section2items(self, itemkey):
sec_items = []
section2usrnts = self.get_section2usrnts()
for section, usrnts in section2usrnts.items():
items = set([e for nt in usrnts for e in getattr(nt, itemkey, set())])
sec_items.append((section, items))
return cx.OrderedDict(sec_items) | [
"def",
"get_section2items",
"(",
"self",
",",
"itemkey",
")",
":",
"sec_items",
"=",
"[",
"]",
"section2usrnts",
"=",
"self",
".",
"get_section2usrnts",
"(",
")",
"for",
"section",
",",
"usrnts",
"in",
"section2usrnts",
".",
"items",
"(",
")",
":",
"items"... | Collect all items into a single set per section. | [
"Collect",
"all",
"items",
"into",
"a",
"single",
"set",
"per",
"section",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L116-L123 |
242,487 | tanghaibao/goatools | goatools/grouper/grprobj.py | Grouper.get_hdrgos_g_usrgos | def get_hdrgos_g_usrgos(self, usrgos):
"""Return hdrgos which contain the usrgos."""
hdrgos_for_usrgos = set()
hdrgos_all = self.get_hdrgos()
usrgo2hdrgo = self.get_usrgo2hdrgo()
for usrgo in usrgos:
if usrgo in hdrgos_all:
hdrgos_for_usrgos.add(usrgo)
continue
hdrgo_cur = usrgo2hdrgo.get(usrgo, None)
if hdrgo_cur is not None:
hdrgos_for_usrgos.add(hdrgo_cur)
return hdrgos_for_usrgos | python | def get_hdrgos_g_usrgos(self, usrgos):
hdrgos_for_usrgos = set()
hdrgos_all = self.get_hdrgos()
usrgo2hdrgo = self.get_usrgo2hdrgo()
for usrgo in usrgos:
if usrgo in hdrgos_all:
hdrgos_for_usrgos.add(usrgo)
continue
hdrgo_cur = usrgo2hdrgo.get(usrgo, None)
if hdrgo_cur is not None:
hdrgos_for_usrgos.add(hdrgo_cur)
return hdrgos_for_usrgos | [
"def",
"get_hdrgos_g_usrgos",
"(",
"self",
",",
"usrgos",
")",
":",
"hdrgos_for_usrgos",
"=",
"set",
"(",
")",
"hdrgos_all",
"=",
"self",
".",
"get_hdrgos",
"(",
")",
"usrgo2hdrgo",
"=",
"self",
".",
"get_usrgo2hdrgo",
"(",
")",
"for",
"usrgo",
"in",
"usrg... | Return hdrgos which contain the usrgos. | [
"Return",
"hdrgos",
"which",
"contain",
"the",
"usrgos",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L125-L137 |
242,488 | tanghaibao/goatools | goatools/grouper/grprobj.py | Grouper.get_section_hdrgos_nts | def get_section_hdrgos_nts(self, sortby=None):
"""Get a flat list of sections and hdrgos actually used in grouping."""
nts_all = []
section_hdrgos_actual = self.get_sections_2d()
flds_all = ['Section'] + self.gosubdag.prt_attr['flds']
ntobj = cx.namedtuple("NtGoSec", " ".join(flds_all))
flds_go = None
if sortby is None:
sortby = lambda nt: -1*nt.dcnt
for section_name, hdrgos_actual in section_hdrgos_actual:
nts_sec = []
for hdrgo_nt in self.gosubdag.get_go2nt(hdrgos_actual).values():
if flds_go is None:
flds_go = hdrgo_nt._fields
key2val = {key:val for key, val in zip(flds_go, list(hdrgo_nt))}
key2val['Section'] = section_name
nts_sec.append(ntobj(**key2val))
nts_all.extend(sorted(nts_sec, key=sortby))
return nts_all | python | def get_section_hdrgos_nts(self, sortby=None):
nts_all = []
section_hdrgos_actual = self.get_sections_2d()
flds_all = ['Section'] + self.gosubdag.prt_attr['flds']
ntobj = cx.namedtuple("NtGoSec", " ".join(flds_all))
flds_go = None
if sortby is None:
sortby = lambda nt: -1*nt.dcnt
for section_name, hdrgos_actual in section_hdrgos_actual:
nts_sec = []
for hdrgo_nt in self.gosubdag.get_go2nt(hdrgos_actual).values():
if flds_go is None:
flds_go = hdrgo_nt._fields
key2val = {key:val for key, val in zip(flds_go, list(hdrgo_nt))}
key2val['Section'] = section_name
nts_sec.append(ntobj(**key2val))
nts_all.extend(sorted(nts_sec, key=sortby))
return nts_all | [
"def",
"get_section_hdrgos_nts",
"(",
"self",
",",
"sortby",
"=",
"None",
")",
":",
"nts_all",
"=",
"[",
"]",
"section_hdrgos_actual",
"=",
"self",
".",
"get_sections_2d",
"(",
")",
"flds_all",
"=",
"[",
"'Section'",
"]",
"+",
"self",
".",
"gosubdag",
".",... | Get a flat list of sections and hdrgos actually used in grouping. | [
"Get",
"a",
"flat",
"list",
"of",
"sections",
"and",
"hdrgos",
"actually",
"used",
"in",
"grouping",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L139-L157 |
242,489 | tanghaibao/goatools | goatools/grouper/grprobj.py | Grouper.get_sections_2d_nts | def get_sections_2d_nts(self, sortby=None):
"""Get high GO IDs that are actually used to group current set of GO IDs."""
sections_2d_nts = []
for section_name, hdrgos_actual in self.get_sections_2d():
hdrgo_nts = self.gosubdag.get_nts(hdrgos_actual, sortby=sortby)
sections_2d_nts.append((section_name, hdrgo_nts))
return sections_2d_nts | python | def get_sections_2d_nts(self, sortby=None):
sections_2d_nts = []
for section_name, hdrgos_actual in self.get_sections_2d():
hdrgo_nts = self.gosubdag.get_nts(hdrgos_actual, sortby=sortby)
sections_2d_nts.append((section_name, hdrgo_nts))
return sections_2d_nts | [
"def",
"get_sections_2d_nts",
"(",
"self",
",",
"sortby",
"=",
"None",
")",
":",
"sections_2d_nts",
"=",
"[",
"]",
"for",
"section_name",
",",
"hdrgos_actual",
"in",
"self",
".",
"get_sections_2d",
"(",
")",
":",
"hdrgo_nts",
"=",
"self",
".",
"gosubdag",
... | Get high GO IDs that are actually used to group current set of GO IDs. | [
"Get",
"high",
"GO",
"IDs",
"that",
"are",
"actually",
"used",
"to",
"group",
"current",
"set",
"of",
"GO",
"IDs",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L159-L165 |
242,490 | tanghaibao/goatools | goatools/grouper/grprobj.py | Grouper.get_usrgos_g_hdrgos | def get_usrgos_g_hdrgos(self, hdrgos):
"""Return usrgos under provided hdrgos."""
usrgos_all = set()
if isinstance(hdrgos, str):
hdrgos = [hdrgos]
for hdrgo in hdrgos:
usrgos_cur = self.hdrgo2usrgos.get(hdrgo, None)
if usrgos_cur is not None:
usrgos_all |= usrgos_cur
if hdrgo in self.hdrgo_is_usrgo:
usrgos_all.add(hdrgo)
return usrgos_all | python | def get_usrgos_g_hdrgos(self, hdrgos):
usrgos_all = set()
if isinstance(hdrgos, str):
hdrgos = [hdrgos]
for hdrgo in hdrgos:
usrgos_cur = self.hdrgo2usrgos.get(hdrgo, None)
if usrgos_cur is not None:
usrgos_all |= usrgos_cur
if hdrgo in self.hdrgo_is_usrgo:
usrgos_all.add(hdrgo)
return usrgos_all | [
"def",
"get_usrgos_g_hdrgos",
"(",
"self",
",",
"hdrgos",
")",
":",
"usrgos_all",
"=",
"set",
"(",
")",
"if",
"isinstance",
"(",
"hdrgos",
",",
"str",
")",
":",
"hdrgos",
"=",
"[",
"hdrgos",
"]",
"for",
"hdrgo",
"in",
"hdrgos",
":",
"usrgos_cur",
"=",
... | Return usrgos under provided hdrgos. | [
"Return",
"usrgos",
"under",
"provided",
"hdrgos",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L171-L182 |
242,491 | tanghaibao/goatools | goatools/grouper/grprobj.py | Grouper.get_hdrgo2usrgos | def get_hdrgo2usrgos(self, hdrgos):
"""Return a subset of hdrgo2usrgos."""
get_usrgos = self.hdrgo2usrgos.get
hdrgos_actual = self.get_hdrgos().intersection(hdrgos)
return {h:get_usrgos(h) for h in hdrgos_actual} | python | def get_hdrgo2usrgos(self, hdrgos):
get_usrgos = self.hdrgo2usrgos.get
hdrgos_actual = self.get_hdrgos().intersection(hdrgos)
return {h:get_usrgos(h) for h in hdrgos_actual} | [
"def",
"get_hdrgo2usrgos",
"(",
"self",
",",
"hdrgos",
")",
":",
"get_usrgos",
"=",
"self",
".",
"hdrgo2usrgos",
".",
"get",
"hdrgos_actual",
"=",
"self",
".",
"get_hdrgos",
"(",
")",
".",
"intersection",
"(",
"hdrgos",
")",
"return",
"{",
"h",
":",
"get... | Return a subset of hdrgo2usrgos. | [
"Return",
"a",
"subset",
"of",
"hdrgo2usrgos",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L196-L200 |
242,492 | tanghaibao/goatools | goatools/grouper/grprobj.py | Grouper.get_usrgo2hdrgo | def get_usrgo2hdrgo(self):
"""Return a dict with all user GO IDs as keys and their respective header GOs as values."""
usrgo2hdrgo = {}
for hdrgo, usrgos in self.hdrgo2usrgos.items():
for usrgo in usrgos:
assert usrgo not in usrgo2hdrgo
usrgo2hdrgo[usrgo] = hdrgo
# Add usrgos which are also a hdrgo and the GO group contains no other GO IDs
for goid in self.hdrgo_is_usrgo:
usrgo2hdrgo[goid] = goid
assert len(self.usrgos) <= len(usrgo2hdrgo), \
"USRGOS({U}) != USRGO2HDRGO({H}): {GOs}".format(
U=len(self.usrgos),
H=len(usrgo2hdrgo),
GOs=self.usrgos.symmetric_difference(set(usrgo2hdrgo.keys())))
return usrgo2hdrgo | python | def get_usrgo2hdrgo(self):
usrgo2hdrgo = {}
for hdrgo, usrgos in self.hdrgo2usrgos.items():
for usrgo in usrgos:
assert usrgo not in usrgo2hdrgo
usrgo2hdrgo[usrgo] = hdrgo
# Add usrgos which are also a hdrgo and the GO group contains no other GO IDs
for goid in self.hdrgo_is_usrgo:
usrgo2hdrgo[goid] = goid
assert len(self.usrgos) <= len(usrgo2hdrgo), \
"USRGOS({U}) != USRGO2HDRGO({H}): {GOs}".format(
U=len(self.usrgos),
H=len(usrgo2hdrgo),
GOs=self.usrgos.symmetric_difference(set(usrgo2hdrgo.keys())))
return usrgo2hdrgo | [
"def",
"get_usrgo2hdrgo",
"(",
"self",
")",
":",
"usrgo2hdrgo",
"=",
"{",
"}",
"for",
"hdrgo",
",",
"usrgos",
"in",
"self",
".",
"hdrgo2usrgos",
".",
"items",
"(",
")",
":",
"for",
"usrgo",
"in",
"usrgos",
":",
"assert",
"usrgo",
"not",
"in",
"usrgo2hd... | Return a dict with all user GO IDs as keys and their respective header GOs as values. | [
"Return",
"a",
"dict",
"with",
"all",
"user",
"GO",
"IDs",
"as",
"keys",
"and",
"their",
"respective",
"header",
"GOs",
"as",
"values",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L202-L217 |
242,493 | tanghaibao/goatools | goatools/grouper/grprobj.py | Grouper.get_go2sectiontxt | def get_go2sectiontxt(self):
"""Return a dict with actual header and user GO IDs as keys and their sections as values."""
go2txt = {}
_get_secs = self.hdrobj.get_sections
hdrgo2sectxt = {h:" ".join(_get_secs(h)) for h in self.get_hdrgos()}
usrgo2hdrgo = self.get_usrgo2hdrgo()
for goid, ntgo in self.go2nt.items():
hdrgo = ntgo.GO if ntgo.is_hdrgo else usrgo2hdrgo[ntgo.GO]
go2txt[goid] = hdrgo2sectxt[hdrgo]
return go2txt | python | def get_go2sectiontxt(self):
go2txt = {}
_get_secs = self.hdrobj.get_sections
hdrgo2sectxt = {h:" ".join(_get_secs(h)) for h in self.get_hdrgos()}
usrgo2hdrgo = self.get_usrgo2hdrgo()
for goid, ntgo in self.go2nt.items():
hdrgo = ntgo.GO if ntgo.is_hdrgo else usrgo2hdrgo[ntgo.GO]
go2txt[goid] = hdrgo2sectxt[hdrgo]
return go2txt | [
"def",
"get_go2sectiontxt",
"(",
"self",
")",
":",
"go2txt",
"=",
"{",
"}",
"_get_secs",
"=",
"self",
".",
"hdrobj",
".",
"get_sections",
"hdrgo2sectxt",
"=",
"{",
"h",
":",
"\" \"",
".",
"join",
"(",
"_get_secs",
"(",
"h",
")",
")",
"for",
"h",
"in"... | Return a dict with actual header and user GO IDs as keys and their sections as values. | [
"Return",
"a",
"dict",
"with",
"actual",
"header",
"and",
"user",
"GO",
"IDs",
"as",
"keys",
"and",
"their",
"sections",
"as",
"values",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L219-L228 |
242,494 | tanghaibao/goatools | goatools/grouper/grprobj.py | Grouper.get_usrgo2sections | def get_usrgo2sections(self):
"""Return a dict with all user GO IDs as keys and their sections as values."""
usrgo2sections = cx.defaultdict(set)
usrgo2hdrgo = self.get_usrgo2hdrgo()
get_sections = self.hdrobj.get_sections
for usrgo, hdrgo in usrgo2hdrgo.items():
sections = set(get_sections(hdrgo))
usrgo2sections[usrgo] |= sections
assert len(usrgo2sections) >= len(self.usrgos), \
"uGOS({U}) != uGO2sections({H}): {GOs}".format(
U=len(self.usrgos),
H=len(usrgo2sections),
GOs=self.usrgos.symmetric_difference(set(usrgo2sections.keys())))
return usrgo2sections | python | def get_usrgo2sections(self):
usrgo2sections = cx.defaultdict(set)
usrgo2hdrgo = self.get_usrgo2hdrgo()
get_sections = self.hdrobj.get_sections
for usrgo, hdrgo in usrgo2hdrgo.items():
sections = set(get_sections(hdrgo))
usrgo2sections[usrgo] |= sections
assert len(usrgo2sections) >= len(self.usrgos), \
"uGOS({U}) != uGO2sections({H}): {GOs}".format(
U=len(self.usrgos),
H=len(usrgo2sections),
GOs=self.usrgos.symmetric_difference(set(usrgo2sections.keys())))
return usrgo2sections | [
"def",
"get_usrgo2sections",
"(",
"self",
")",
":",
"usrgo2sections",
"=",
"cx",
".",
"defaultdict",
"(",
"set",
")",
"usrgo2hdrgo",
"=",
"self",
".",
"get_usrgo2hdrgo",
"(",
")",
"get_sections",
"=",
"self",
".",
"hdrobj",
".",
"get_sections",
"for",
"usrgo... | Return a dict with all user GO IDs as keys and their sections as values. | [
"Return",
"a",
"dict",
"with",
"all",
"user",
"GO",
"IDs",
"as",
"keys",
"and",
"their",
"sections",
"as",
"values",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L230-L243 |
242,495 | tanghaibao/goatools | goatools/grouper/grprobj.py | Grouper.get_fout_base | def get_fout_base(self, goid, name=None, pre="gogrp"):
"""Get filename for a group of GO IDs under a single header GO ID."""
goobj = self.gosubdag.go2obj[goid]
if name is None:
name = self.grpname.replace(" ", "_")
sections = "_".join(self.hdrobj.get_sections(goid))
return "{PRE}_{BP}_{NAME}_{SEC}_{DSTR}_{D1s}_{GO}".format(
PRE=pre,
BP=Consts.NAMESPACE2NS[goobj.namespace],
NAME=self._str_replace(name),
SEC=self._str_replace(self._str_replace(sections)),
GO=goid.replace(":", ""),
DSTR=self._get_depthsr(goobj),
D1s=self.gosubdag.go2nt[goobj.id].D1) | python | def get_fout_base(self, goid, name=None, pre="gogrp"):
goobj = self.gosubdag.go2obj[goid]
if name is None:
name = self.grpname.replace(" ", "_")
sections = "_".join(self.hdrobj.get_sections(goid))
return "{PRE}_{BP}_{NAME}_{SEC}_{DSTR}_{D1s}_{GO}".format(
PRE=pre,
BP=Consts.NAMESPACE2NS[goobj.namespace],
NAME=self._str_replace(name),
SEC=self._str_replace(self._str_replace(sections)),
GO=goid.replace(":", ""),
DSTR=self._get_depthsr(goobj),
D1s=self.gosubdag.go2nt[goobj.id].D1) | [
"def",
"get_fout_base",
"(",
"self",
",",
"goid",
",",
"name",
"=",
"None",
",",
"pre",
"=",
"\"gogrp\"",
")",
":",
"goobj",
"=",
"self",
".",
"gosubdag",
".",
"go2obj",
"[",
"goid",
"]",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
... | Get filename for a group of GO IDs under a single header GO ID. | [
"Get",
"filename",
"for",
"a",
"group",
"of",
"GO",
"IDs",
"under",
"a",
"single",
"header",
"GO",
"ID",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L245-L258 |
242,496 | tanghaibao/goatools | goatools/grouper/grprobj.py | Grouper._get_depthsr | def _get_depthsr(self, goobj):
"""Return DNN or RNN depending on if relationships are loaded."""
if 'reldepth' in self.gosubdag.prt_attr['flds']:
return "R{R:02}".format(R=goobj.reldepth)
return "D{D:02}".format(D=goobj.depth) | python | def _get_depthsr(self, goobj):
if 'reldepth' in self.gosubdag.prt_attr['flds']:
return "R{R:02}".format(R=goobj.reldepth)
return "D{D:02}".format(D=goobj.depth) | [
"def",
"_get_depthsr",
"(",
"self",
",",
"goobj",
")",
":",
"if",
"'reldepth'",
"in",
"self",
".",
"gosubdag",
".",
"prt_attr",
"[",
"'flds'",
"]",
":",
"return",
"\"R{R:02}\"",
".",
"format",
"(",
"R",
"=",
"goobj",
".",
"reldepth",
")",
"return",
"\"... | Return DNN or RNN depending on if relationships are loaded. | [
"Return",
"DNN",
"or",
"RNN",
"depending",
"on",
"if",
"relationships",
"are",
"loaded",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L260-L264 |
242,497 | tanghaibao/goatools | goatools/grouper/grprobj.py | Grouper._str_replace | def _str_replace(txt):
"""Makes a small text amenable to being used in a filename."""
txt = txt.replace(",", "")
txt = txt.replace(" ", "_")
txt = txt.replace(":", "")
txt = txt.replace(".", "")
txt = txt.replace("/", "")
txt = txt.replace("", "")
return txt | python | def _str_replace(txt):
txt = txt.replace(",", "")
txt = txt.replace(" ", "_")
txt = txt.replace(":", "")
txt = txt.replace(".", "")
txt = txt.replace("/", "")
txt = txt.replace("", "")
return txt | [
"def",
"_str_replace",
"(",
"txt",
")",
":",
"txt",
"=",
"txt",
".",
"replace",
"(",
"\",\"",
",",
"\"\"",
")",
"txt",
"=",
"txt",
".",
"replace",
"(",
"\" \"",
",",
"\"_\"",
")",
"txt",
"=",
"txt",
".",
"replace",
"(",
"\":\"",
",",
"\"\"",
")",... | Makes a small text amenable to being used in a filename. | [
"Makes",
"a",
"small",
"text",
"amenable",
"to",
"being",
"used",
"in",
"a",
"filename",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L267-L275 |
242,498 | tanghaibao/goatools | goatools/rpt/prtfmt.py | PrtFmt.get_prtfmt_list | def get_prtfmt_list(self, flds, add_nl=True):
"""Get print format, given fields."""
fmts = []
for fld in flds:
if fld[:2] == 'p_':
fmts.append('{{{FLD}:8.2e}}'.format(FLD=fld))
elif fld in self.default_fld2fmt:
fmts.append(self.default_fld2fmt[fld])
else:
raise Exception("UNKNOWN FORMAT: {FLD}".format(FLD=fld))
if add_nl:
fmts.append("\n")
return fmts | python | def get_prtfmt_list(self, flds, add_nl=True):
fmts = []
for fld in flds:
if fld[:2] == 'p_':
fmts.append('{{{FLD}:8.2e}}'.format(FLD=fld))
elif fld in self.default_fld2fmt:
fmts.append(self.default_fld2fmt[fld])
else:
raise Exception("UNKNOWN FORMAT: {FLD}".format(FLD=fld))
if add_nl:
fmts.append("\n")
return fmts | [
"def",
"get_prtfmt_list",
"(",
"self",
",",
"flds",
",",
"add_nl",
"=",
"True",
")",
":",
"fmts",
"=",
"[",
"]",
"for",
"fld",
"in",
"flds",
":",
"if",
"fld",
"[",
":",
"2",
"]",
"==",
"'p_'",
":",
"fmts",
".",
"append",
"(",
"'{{{FLD}:8.2e}}'",
... | Get print format, given fields. | [
"Get",
"print",
"format",
"given",
"fields",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/rpt/prtfmt.py#L55-L67 |
242,499 | tanghaibao/goatools | scripts/fetch_associations.py | main | def main():
"""Fetch simple gene-term assocaitions from Golr using bioentity document type, one line per gene."""
import argparse
prs = argparse.ArgumentParser(__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
prs.add_argument('--taxon_id', type=str,
help='NCBI taxon ID, must match exact species/strain used by GO Central, e.g. 4896 for S Pombe')
prs.add_argument('--golr_url', default='http://golr.geneontology.org/solr/', type=str,
help='NCBI taxon ID, must match exact species/strain used by GO Central, e.g. 4896 for S Pombe')
prs.add_argument('-o', default=None, type=str,
help="Specifies the name of the output file")
prs.add_argument('--max_rows', default=100000, type=int,
help="maximum rows to be fetched")
args = prs.parse_args()
solr = pysolr.Solr(args.golr_url, timeout=30)
sys.stderr.write("TAX:"+args.taxon_id+"\n")
results = solr.search(q='document_category:"bioentity" AND taxon:"NCBITaxon:'+args.taxon_id+'"',
fl='bioentity_label,annotation_class_list', rows=args.max_rows)
sys.stderr.write("NUM GENES:"+str(len(results))+"\n")
if (len(results) ==0):
sys.stderr.write("NO RESULTS")
exit(1)
if (len(results) == args.max_rows):
sys.stderr.write("max_rows set too low")
exit(1)
file_out = sys.stdout if args.o is None else open(args.o, 'w')
for r in results:
gene_symbol = r['bioentity_label']
sys.stderr.write(gene_symbol+"\n")
if 'annotation_class_list' in r:
file_out.write(r['bioentity_label']+"\t" + ';'.join(r['annotation_class_list'])+"\n")
else:
sys.stderr.write("no annotations for "+gene_symbol+"\n")
if args.o is not None:
file_out.close()
sys.stdout.write(" WROTE: {}\n".format(args.o)) | python | def main():
import argparse
prs = argparse.ArgumentParser(__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
prs.add_argument('--taxon_id', type=str,
help='NCBI taxon ID, must match exact species/strain used by GO Central, e.g. 4896 for S Pombe')
prs.add_argument('--golr_url', default='http://golr.geneontology.org/solr/', type=str,
help='NCBI taxon ID, must match exact species/strain used by GO Central, e.g. 4896 for S Pombe')
prs.add_argument('-o', default=None, type=str,
help="Specifies the name of the output file")
prs.add_argument('--max_rows', default=100000, type=int,
help="maximum rows to be fetched")
args = prs.parse_args()
solr = pysolr.Solr(args.golr_url, timeout=30)
sys.stderr.write("TAX:"+args.taxon_id+"\n")
results = solr.search(q='document_category:"bioentity" AND taxon:"NCBITaxon:'+args.taxon_id+'"',
fl='bioentity_label,annotation_class_list', rows=args.max_rows)
sys.stderr.write("NUM GENES:"+str(len(results))+"\n")
if (len(results) ==0):
sys.stderr.write("NO RESULTS")
exit(1)
if (len(results) == args.max_rows):
sys.stderr.write("max_rows set too low")
exit(1)
file_out = sys.stdout if args.o is None else open(args.o, 'w')
for r in results:
gene_symbol = r['bioentity_label']
sys.stderr.write(gene_symbol+"\n")
if 'annotation_class_list' in r:
file_out.write(r['bioentity_label']+"\t" + ';'.join(r['annotation_class_list'])+"\n")
else:
sys.stderr.write("no annotations for "+gene_symbol+"\n")
if args.o is not None:
file_out.close()
sys.stdout.write(" WROTE: {}\n".format(args.o)) | [
"def",
"main",
"(",
")",
":",
"import",
"argparse",
"prs",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"__doc__",
",",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
")",
"prs",
".",
"add_argument",
"(",
"'--taxon_id'",
",",
"type",
... | Fetch simple gene-term assocaitions from Golr using bioentity document type, one line per gene. | [
"Fetch",
"simple",
"gene",
"-",
"term",
"assocaitions",
"from",
"Golr",
"using",
"bioentity",
"document",
"type",
"one",
"line",
"per",
"gene",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/scripts/fetch_associations.py#L34-L76 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.