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 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
228,600 | 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):
"""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 | [
"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"
] | 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 |
228,601 | 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):
"""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) | [
"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",
")"
] | 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 |
228,602 | 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):
"""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) | [
"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",
")"
] | 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 |
228,603 | 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):
"""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) | [
"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",
")"
] | 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 |
228,604 | 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):
"""Write info for all GO Terms in obo file, sorted numerically."""
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 |
228,605 | 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):
"""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 | [
"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"
] | 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 |
228,606 | 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):
"""Label text for plot."""
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 |
228,607 | 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):
"""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 | [
"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"
] | 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 |
228,608 | 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):
"""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) | [
"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",
")"
] | Draw GO DAG subplot. | [
"Draw",
"GO",
"DAG",
"subplot",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L601-L633 |
228,609 | 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):
"""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 | [
"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"
] | 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 |
228,610 | 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):
"""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) | [
"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",
")"
] | 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 |
228,611 | 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):
"""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) | [
"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",
")"
] | 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 |
228,612 | 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):
"""Create a namedtuple object for each annotation"""
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\"",
",",
"hdrs",
")"
] | 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 |
228,613 | 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):
"""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 | [
"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"
] | 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 |
228,614 | 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):
"""If this line contains desired header info, save it."""
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 |
228,615 | 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=""):
"""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) | [
"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",
")"
] | 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 |
228,616 | 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=""):
"""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 | [
"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"
] | 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 |
228,617 | 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=""):
"""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 | [
"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"
] | 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 |
228,618 | 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"):
"""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)) | [
"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",
")",
")"
] | 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 |
228,619 | 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=' '):
"""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") | [
"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\"",
")"
] | 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 |
228,620 | 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):
"""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 | [
"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"
] | 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 |
228,621 | 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):
"""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 | [
"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"
] | 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 |
228,622 | 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):
"""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} | [
"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",
"}"
] | 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 |
228,623 | 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):
"""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 | [
"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"
] | 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 |
228,624 | 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 |
228,625 | 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):
"""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 | [
"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"
] | 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 |
228,626 | 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):
"""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 | [
"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"
] | 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 |
228,627 | 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):
"""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) | [
"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",
")"
] | 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 |
228,628 | 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):
"""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 "", "" | [
"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",
"\"\"",
",",
"\"\""
] | 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 |
228,629 | 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):
"""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)) | [
"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",
")",
")"
] | 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 |
228,630 | 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 evidence codes in order shown in code2name."""
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 |
228,631 | 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):
"""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 | [
"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"
] | 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 |
228,632 | 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):
"""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))] | [
"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",
")",
")",
"]"
] | 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 |
228,633 | 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):
"""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) | [
"def",
"get_grp2codes",
"(",
"self",
")",
":",
"grp2codes",
"=",
"cx",
".",
"defaultdict",
"(",
"set",
")",
"for",
"code",
",",
"ntd",
"in",
"self",
".",
"code2nt",
".",
"items",
"(",
")",
":",
"grp2codes",
"[",
"ntd",
".",
"group",
"]",
".",
"add",
"(",
"code",
")",
"return",
"dict",
"(",
"grp2codes",
")"
] | 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 |
228,634 | 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):
"""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) | [
"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",
")"
] | 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 |
228,635 | 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):
"""Plot one GO header group in Grouper."""
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 |
228,636 | 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):
"""Plot each GO group."""
# 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",
"(",
"fout_dir",
",",
"*",
"*",
"kws_usr",
")"
] | Plot each GO group. | [
"Plot",
"each",
"GO",
"group",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprplt.py#L52-L56 |
228,637 | 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):
"""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 | [
"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"
] | 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 |
228,638 | 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):
"""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 | [
"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"
] | 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 |
228,639 | 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):
"""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 | [
"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"
] | Download Ontologies, if necessary. | [
"Download",
"Ontologies",
"if",
"necessary",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/base.py#L113-L125 |
228,640 | 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 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 | [
"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"
] | 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 |
228,641 | 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):
"""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 | [
"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"
] | 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 |
228,642 | 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):
"""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) | [
"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",
")"
] | 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 |
228,643 | 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):
"""Download GAF file if necessary."""
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 |
228,644 | 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):
"""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 | [
"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"
] | Download GAF files if necessary. | [
"Download",
"GAF",
"files",
"if",
"necessary",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/base.py#L157-L173 |
228,645 | 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):
"""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 | [
"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"
] | 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 |
228,646 | 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):
"""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() | [
"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",
"(",
")"
] | 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 |
228,647 | 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):
"""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) | [
"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",
")"
] | Download specified file if necessary. | [
"Download",
"specified",
"file",
"if",
"necessary",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/base.py#L207-L230 |
228,648 | 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):
"""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 = {} | [
"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",
"=",
"{",
"}"
] | 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 |
228,649 | 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):
"""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]) | [
"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",
"]",
")"
] | 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 |
228,650 | 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):
"""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(' ', '') | [
"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",
"(",
"' '",
",",
"''",
")"
] | 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 |
228,651 | 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):
"""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 | [
"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"
] | 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 |
228,652 | 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():
"""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) | [
"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",
")"
] | 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 |
228,653 | 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):
"""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 | [
"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"
] | Get output filename. | [
"Get",
"output",
"filename",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/wr_hierarchy.py#L107-L114 |
228,654 | 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):
"""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') | [
"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'",
")"
] | 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 |
228,655 | 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):
"""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)) | [
"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 |
228,656 | 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):
"""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) | [
"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",
")"
] | 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 |
228,657 | 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):
"""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 | [
"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"
] | 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 |
228,658 | 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):
"""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)) | [
"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",
")",
")"
] | 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 |
228,659 | 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):
"""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)) | [
"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",
")",
")"
] | 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 |
228,660 | 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):
""" 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) | [
"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",
")"
] | 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 |
228,661 | 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"):
""" 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)) | [
"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",
")",
")"
] | 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 |
228,662 | 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):
""" Find what's missing
"""
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",
"specifier"
] | Find what's missing | [
"Find",
"what",
"s",
"missing"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/setup_helper.py#L49-L56 |
228,663 | 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):
""" 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) | [
"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",
")"
] | Install the listed requirements | [
"Install",
"the",
"listed",
"requirements"
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/setup_helper.py#L58-L69 |
228,664 | 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'):
""" 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 | [
"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"
] | 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 |
228,665 | 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):
"""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 | [
"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"
] | 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 |
228,666 | 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):
"""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 | [
"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"
] | 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 |
228,667 | 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):
"""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 | [
"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"
] | 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 |
228,668 | 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):
"""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() | [
"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",
"(",
")"
] | 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 |
228,669 | 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):
"""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) | [
"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",
")"
] | Get dict section2usrnts. | [
"Get",
"dict",
"section2usrnts",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L108-L114 |
228,670 | 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):
"""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) | [
"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",
")"
] | 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 |
228,671 | 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):
"""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 | [
"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"
] | 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 |
228,672 | 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):
"""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 | [
"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"
] | 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 |
228,673 | 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):
"""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 | [
"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"
] | 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 |
228,674 | 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):
"""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 | [
"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"
] | Return usrgos under provided hdrgos. | [
"Return",
"usrgos",
"under",
"provided",
"hdrgos",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L171-L182 |
228,675 | 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):
"""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} | [
"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",
"}"
] | Return a subset of hdrgo2usrgos. | [
"Return",
"a",
"subset",
"of",
"hdrgo2usrgos",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L196-L200 |
228,676 | 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):
"""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 | [
"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"
] | 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 |
228,677 | 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):
"""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 | [
"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"
] | 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 |
228,678 | 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):
"""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 | [
"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"
] | 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 |
228,679 | 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"):
"""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) | [
"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",
")"
] | 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 |
228,680 | 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):
"""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) | [
"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",
")"
] | 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 |
228,681 | 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):
"""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 | [
"def",
"_str_replace",
"(",
"txt",
")",
":",
"txt",
"=",
"txt",
".",
"replace",
"(",
"\",\"",
",",
"\"\"",
")",
"txt",
"=",
"txt",
".",
"replace",
"(",
"\" \"",
",",
"\"_\"",
")",
"txt",
"=",
"txt",
".",
"replace",
"(",
"\":\"",
",",
"\"\"",
")",
"txt",
"=",
"txt",
".",
"replace",
"(",
"\".\"",
",",
"\"\"",
")",
"txt",
"=",
"txt",
".",
"replace",
"(",
"\"/\"",
",",
"\"\"",
")",
"txt",
"=",
"txt",
".",
"replace",
"(",
"\"\"",
",",
"\"\"",
")",
"return",
"txt"
] | 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 |
228,682 | 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):
"""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 | [
"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"
] | Get print format, given fields. | [
"Get",
"print",
"format",
"given",
"fields",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/rpt/prtfmt.py#L55-L67 |
228,683 | 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():
"""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)) | [
"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",
")",
")"
] | 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 |
228,684 | tanghaibao/goatools | goatools/gosubdag/plot/go_name_shorten.py | ShortenText.get_short_plot_name | def get_short_plot_name(self, goobj):
"""Shorten some GO names so plots are smaller."""
name = goobj.name
if self._keep_this(name):
return self.replace_greek(name)
name = name.replace("cellular response to chemical stimulus",
"cellular rsp. to chemical stim.")
depth = goobj.depth
if depth > 1:
name = name.replace("regulation of ", "reg. of ")
name = name.replace("positive reg", "+reg")
name = name.replace("negative reg", "-reg")
name = name.replace("involved in", "in")
if depth > 2:
name = name.replace("antigen processing and presentation", "a.p.p")
name = name.replace("MHC class I", "MHC-I")
if depth == 4:
if goobj.id == "GO:0002460":
before = " ".join([
"adaptive immune response based on somatic recombination of",
"immune receptors built from immunoglobulin superfamily domains"])
name = name.replace(
before,
"rsp. based on somatic recombination of Ig immune receptors")
if depth > 3:
name = name.replace("signaling pathway", "sig. pw.")
name = name.replace("response", "rsp.")
name = name.replace("immunoglobulin superfamily domains", "Ig domains")
name = name.replace("immunoglobulin", "Ig")
if depth > 4:
name = name.replace("production", "prod.")
if depth == 6 or depth == 5:
name = name.replace("tumor necrosis factor", "TNF")
name = self.replace_greek(name)
return name | python | def get_short_plot_name(self, goobj):
"""Shorten some GO names so plots are smaller."""
name = goobj.name
if self._keep_this(name):
return self.replace_greek(name)
name = name.replace("cellular response to chemical stimulus",
"cellular rsp. to chemical stim.")
depth = goobj.depth
if depth > 1:
name = name.replace("regulation of ", "reg. of ")
name = name.replace("positive reg", "+reg")
name = name.replace("negative reg", "-reg")
name = name.replace("involved in", "in")
if depth > 2:
name = name.replace("antigen processing and presentation", "a.p.p")
name = name.replace("MHC class I", "MHC-I")
if depth == 4:
if goobj.id == "GO:0002460":
before = " ".join([
"adaptive immune response based on somatic recombination of",
"immune receptors built from immunoglobulin superfamily domains"])
name = name.replace(
before,
"rsp. based on somatic recombination of Ig immune receptors")
if depth > 3:
name = name.replace("signaling pathway", "sig. pw.")
name = name.replace("response", "rsp.")
name = name.replace("immunoglobulin superfamily domains", "Ig domains")
name = name.replace("immunoglobulin", "Ig")
if depth > 4:
name = name.replace("production", "prod.")
if depth == 6 or depth == 5:
name = name.replace("tumor necrosis factor", "TNF")
name = self.replace_greek(name)
return name | [
"def",
"get_short_plot_name",
"(",
"self",
",",
"goobj",
")",
":",
"name",
"=",
"goobj",
".",
"name",
"if",
"self",
".",
"_keep_this",
"(",
"name",
")",
":",
"return",
"self",
".",
"replace_greek",
"(",
"name",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"cellular response to chemical stimulus\"",
",",
"\"cellular rsp. to chemical stim.\"",
")",
"depth",
"=",
"goobj",
".",
"depth",
"if",
"depth",
">",
"1",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"\"regulation of \"",
",",
"\"reg. of \"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"positive reg\"",
",",
"\"+reg\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"negative reg\"",
",",
"\"-reg\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"involved in\"",
",",
"\"in\"",
")",
"if",
"depth",
">",
"2",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"\"antigen processing and presentation\"",
",",
"\"a.p.p\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"MHC class I\"",
",",
"\"MHC-I\"",
")",
"if",
"depth",
"==",
"4",
":",
"if",
"goobj",
".",
"id",
"==",
"\"GO:0002460\"",
":",
"before",
"=",
"\" \"",
".",
"join",
"(",
"[",
"\"adaptive immune response based on somatic recombination of\"",
",",
"\"immune receptors built from immunoglobulin superfamily domains\"",
"]",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"before",
",",
"\"rsp. based on somatic recombination of Ig immune receptors\"",
")",
"if",
"depth",
">",
"3",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"\"signaling pathway\"",
",",
"\"sig. pw.\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"response\"",
",",
"\"rsp.\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"immunoglobulin superfamily domains\"",
",",
"\"Ig domains\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"immunoglobulin\"",
",",
"\"Ig\"",
")",
"if",
"depth",
">",
"4",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"\"production\"",
",",
"\"prod.\"",
")",
"if",
"depth",
"==",
"6",
"or",
"depth",
"==",
"5",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"\"tumor necrosis factor\"",
",",
"\"TNF\"",
")",
"name",
"=",
"self",
".",
"replace_greek",
"(",
"name",
")",
"return",
"name"
] | Shorten some GO names so plots are smaller. | [
"Shorten",
"some",
"GO",
"names",
"so",
"plots",
"are",
"smaller",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/plot/go_name_shorten.py#L26-L60 |
228,685 | tanghaibao/goatools | goatools/gosubdag/plot/go_name_shorten.py | ShortenText.shorten_go_name_ptbl1 | def shorten_go_name_ptbl1(self, name):
"""Shorten GO name for tables in paper."""
if self._keep_this(name):
return name
name = name.replace("negative", "neg.")
name = name.replace("positive", "pos.")
name = name.replace("response", "rsp.")
name = name.replace("regulation", "reg.")
name = name.replace("antigen processing and presentation", "app.")
return name | python | def shorten_go_name_ptbl1(self, name):
"""Shorten GO name for tables in paper."""
if self._keep_this(name):
return name
name = name.replace("negative", "neg.")
name = name.replace("positive", "pos.")
name = name.replace("response", "rsp.")
name = name.replace("regulation", "reg.")
name = name.replace("antigen processing and presentation", "app.")
return name | [
"def",
"shorten_go_name_ptbl1",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"_keep_this",
"(",
"name",
")",
":",
"return",
"name",
"name",
"=",
"name",
".",
"replace",
"(",
"\"negative\"",
",",
"\"neg.\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"positive\"",
",",
"\"pos.\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"response\"",
",",
"\"rsp.\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"regulation\"",
",",
"\"reg.\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"antigen processing and presentation\"",
",",
"\"app.\"",
")",
"return",
"name"
] | Shorten GO name for tables in paper. | [
"Shorten",
"GO",
"name",
"for",
"tables",
"in",
"paper",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/plot/go_name_shorten.py#L62-L71 |
228,686 | tanghaibao/goatools | goatools/gosubdag/plot/go_name_shorten.py | ShortenText.shorten_go_name_ptbl3 | def shorten_go_name_ptbl3(self, name, dcnt):
"""Shorten GO description for Table 3 in manuscript."""
if self._keep_this(name):
return name
name = name.replace("positive regulation of immune system process",
"+ reg. of immune sys. process")
name = name.replace("positive regulation of immune response",
"+ reg. of immune response")
name = name.replace("positive regulation of cytokine production",
"+ reg. of cytokine production")
if dcnt < 40:
name = name.replace("antigen processing and presentation", "a.p.p.")
if dcnt < 10:
name = name.replace("negative", "-")
name = name.replace("positive", "+")
#name = name.replace("tumor necrosis factor production", "tumor necrosis factor prod.")
name = name.replace("tumor necrosis factor production", "TNF production")
if dcnt < 4:
name = name.replace("regulation", "reg.")
name = name.replace("exogenous ", "")
name = name.replace(" via ", " w/")
name = name.replace("T cell mediated cytotoxicity", "cytotoxicity via T cell")
name = name.replace('involved in', 'in')
name = name.replace('-positive', '+')
return name | python | def shorten_go_name_ptbl3(self, name, dcnt):
"""Shorten GO description for Table 3 in manuscript."""
if self._keep_this(name):
return name
name = name.replace("positive regulation of immune system process",
"+ reg. of immune sys. process")
name = name.replace("positive regulation of immune response",
"+ reg. of immune response")
name = name.replace("positive regulation of cytokine production",
"+ reg. of cytokine production")
if dcnt < 40:
name = name.replace("antigen processing and presentation", "a.p.p.")
if dcnt < 10:
name = name.replace("negative", "-")
name = name.replace("positive", "+")
#name = name.replace("tumor necrosis factor production", "tumor necrosis factor prod.")
name = name.replace("tumor necrosis factor production", "TNF production")
if dcnt < 4:
name = name.replace("regulation", "reg.")
name = name.replace("exogenous ", "")
name = name.replace(" via ", " w/")
name = name.replace("T cell mediated cytotoxicity", "cytotoxicity via T cell")
name = name.replace('involved in', 'in')
name = name.replace('-positive', '+')
return name | [
"def",
"shorten_go_name_ptbl3",
"(",
"self",
",",
"name",
",",
"dcnt",
")",
":",
"if",
"self",
".",
"_keep_this",
"(",
"name",
")",
":",
"return",
"name",
"name",
"=",
"name",
".",
"replace",
"(",
"\"positive regulation of immune system process\"",
",",
"\"+ reg. of immune sys. process\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"positive regulation of immune response\"",
",",
"\"+ reg. of immune response\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"positive regulation of cytokine production\"",
",",
"\"+ reg. of cytokine production\"",
")",
"if",
"dcnt",
"<",
"40",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"\"antigen processing and presentation\"",
",",
"\"a.p.p.\"",
")",
"if",
"dcnt",
"<",
"10",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"\"negative\"",
",",
"\"-\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"positive\"",
",",
"\"+\"",
")",
"#name = name.replace(\"tumor necrosis factor production\", \"tumor necrosis factor prod.\")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"tumor necrosis factor production\"",
",",
"\"TNF production\"",
")",
"if",
"dcnt",
"<",
"4",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"\"regulation\"",
",",
"\"reg.\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"exogenous \"",
",",
"\"\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\" via \"",
",",
"\" w/\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"T cell mediated cytotoxicity\"",
",",
"\"cytotoxicity via T cell\"",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"'involved in'",
",",
"'in'",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"'-positive'",
",",
"'+'",
")",
"return",
"name"
] | Shorten GO description for Table 3 in manuscript. | [
"Shorten",
"GO",
"description",
"for",
"Table",
"3",
"in",
"manuscript",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/plot/go_name_shorten.py#L73-L97 |
228,687 | tanghaibao/goatools | goatools/gosubdag/plot/go_name_shorten.py | ShortenText.shorten_go_name_all | def shorten_go_name_all(self, name):
"""Shorten GO name for tables in paper, supplemental materials, and plots."""
name = self.replace_greek(name)
name = name.replace("MHC class I", "MHC-I")
return name | python | def shorten_go_name_all(self, name):
"""Shorten GO name for tables in paper, supplemental materials, and plots."""
name = self.replace_greek(name)
name = name.replace("MHC class I", "MHC-I")
return name | [
"def",
"shorten_go_name_all",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"self",
".",
"replace_greek",
"(",
"name",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"MHC class I\"",
",",
"\"MHC-I\"",
")",
"return",
"name"
] | Shorten GO name for tables in paper, supplemental materials, and plots. | [
"Shorten",
"GO",
"name",
"for",
"tables",
"in",
"paper",
"supplemental",
"materials",
"and",
"plots",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/plot/go_name_shorten.py#L125-L129 |
228,688 | tanghaibao/goatools | goatools/gosubdag/plot/go_name_shorten.py | ShortenText._keep_this | def _keep_this(self, name):
"""Return True if there are to be no modifications to name."""
for keep_name in self.keep:
if name == keep_name:
return True
return False | python | def _keep_this(self, name):
"""Return True if there are to be no modifications to name."""
for keep_name in self.keep:
if name == keep_name:
return True
return False | [
"def",
"_keep_this",
"(",
"self",
",",
"name",
")",
":",
"for",
"keep_name",
"in",
"self",
".",
"keep",
":",
"if",
"name",
"==",
"keep_name",
":",
"return",
"True",
"return",
"False"
] | Return True if there are to be no modifications to name. | [
"Return",
"True",
"if",
"there",
"are",
"to",
"be",
"no",
"modifications",
"to",
"name",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/plot/go_name_shorten.py#L131-L136 |
228,689 | tanghaibao/goatools | goatools/gosubdag/rpt/wr_xlsx.py | read_d1_letter | def read_d1_letter(fin_txt):
"""Reads letter aliases from a text file created by GoDepth1LettersWr."""
go2letter = {}
re_goid = re.compile(r"(GO:\d{7})")
with open(fin_txt) as ifstrm:
for line in ifstrm:
mtch = re_goid.search(line)
if mtch and line[:1] != ' ':
# Alias is expected to be the first character
go2letter[mtch.group(1)] = line[:1]
return go2letter | python | def read_d1_letter(fin_txt):
"""Reads letter aliases from a text file created by GoDepth1LettersWr."""
go2letter = {}
re_goid = re.compile(r"(GO:\d{7})")
with open(fin_txt) as ifstrm:
for line in ifstrm:
mtch = re_goid.search(line)
if mtch and line[:1] != ' ':
# Alias is expected to be the first character
go2letter[mtch.group(1)] = line[:1]
return go2letter | [
"def",
"read_d1_letter",
"(",
"fin_txt",
")",
":",
"go2letter",
"=",
"{",
"}",
"re_goid",
"=",
"re",
".",
"compile",
"(",
"r\"(GO:\\d{7})\"",
")",
"with",
"open",
"(",
"fin_txt",
")",
"as",
"ifstrm",
":",
"for",
"line",
"in",
"ifstrm",
":",
"mtch",
"=",
"re_goid",
".",
"search",
"(",
"line",
")",
"if",
"mtch",
"and",
"line",
"[",
":",
"1",
"]",
"!=",
"' '",
":",
"# Alias is expected to be the first character",
"go2letter",
"[",
"mtch",
".",
"group",
"(",
"1",
")",
"]",
"=",
"line",
"[",
":",
"1",
"]",
"return",
"go2letter"
] | Reads letter aliases from a text file created by GoDepth1LettersWr. | [
"Reads",
"letter",
"aliases",
"from",
"a",
"text",
"file",
"created",
"by",
"GoDepth1LettersWr",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/rpt/wr_xlsx.py#L66-L76 |
228,690 | tanghaibao/goatools | goatools/gosubdag/rpt/wr_xlsx.py | GoSubDagWr.get_goids_sections | def get_goids_sections(sections):
"""Return all the GO IDs in a 2-D sections list."""
goids_all = set()
for _, goids_sec in sections:
goids_all |= set(goids_sec)
return goids_all | python | def get_goids_sections(sections):
"""Return all the GO IDs in a 2-D sections list."""
goids_all = set()
for _, goids_sec in sections:
goids_all |= set(goids_sec)
return goids_all | [
"def",
"get_goids_sections",
"(",
"sections",
")",
":",
"goids_all",
"=",
"set",
"(",
")",
"for",
"_",
",",
"goids_sec",
"in",
"sections",
":",
"goids_all",
"|=",
"set",
"(",
"goids_sec",
")",
"return",
"goids_all"
] | Return all the GO IDs in a 2-D sections list. | [
"Return",
"all",
"the",
"GO",
"IDs",
"in",
"a",
"2",
"-",
"D",
"sections",
"list",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/rpt/wr_xlsx.py#L58-L63 |
228,691 | tanghaibao/goatools | goatools/gosubdag/rpt/wr_xlsx.py | GoDepth1LettersWr.prt_txt | def prt_txt(self, prt=sys.stdout, pre=''):
"""Print letters, descendant count, and GO information."""
data_nts = self.get_d1nts()
for ntdata in data_nts:
prt.write("{PRE}{L:1} {NS} {d:6,} D{D:02} {GO} {NAME}\n".format(
PRE=pre,
L=ntdata.D1,
d=ntdata.dcnt,
NS=ntdata.NS,
D=ntdata.depth,
GO=ntdata.GO,
NAME=ntdata.name))
return data_nts | python | def prt_txt(self, prt=sys.stdout, pre=''):
"""Print letters, descendant count, and GO information."""
data_nts = self.get_d1nts()
for ntdata in data_nts:
prt.write("{PRE}{L:1} {NS} {d:6,} D{D:02} {GO} {NAME}\n".format(
PRE=pre,
L=ntdata.D1,
d=ntdata.dcnt,
NS=ntdata.NS,
D=ntdata.depth,
GO=ntdata.GO,
NAME=ntdata.name))
return data_nts | [
"def",
"prt_txt",
"(",
"self",
",",
"prt",
"=",
"sys",
".",
"stdout",
",",
"pre",
"=",
"''",
")",
":",
"data_nts",
"=",
"self",
".",
"get_d1nts",
"(",
")",
"for",
"ntdata",
"in",
"data_nts",
":",
"prt",
".",
"write",
"(",
"\"{PRE}{L:1} {NS} {d:6,} D{D:02} {GO} {NAME}\\n\"",
".",
"format",
"(",
"PRE",
"=",
"pre",
",",
"L",
"=",
"ntdata",
".",
"D1",
",",
"d",
"=",
"ntdata",
".",
"dcnt",
",",
"NS",
"=",
"ntdata",
".",
"NS",
",",
"D",
"=",
"ntdata",
".",
"depth",
",",
"GO",
"=",
"ntdata",
".",
"GO",
",",
"NAME",
"=",
"ntdata",
".",
"name",
")",
")",
"return",
"data_nts"
] | Print letters, descendant count, and GO information. | [
"Print",
"letters",
"descendant",
"count",
"and",
"GO",
"information",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/rpt/wr_xlsx.py#L88-L100 |
228,692 | tanghaibao/goatools | goatools/gosubdag/rpt/wr_xlsx.py | GoDepth1LettersWr.wr_xlsx | def wr_xlsx(self, fout_xlsx="gos_depth01.xlsx", **kws):
"""Write xlsx table of depth-01 GO terms and their letter representation."""
data_nts = self.get_d1nts()
if 'fld2col_widths' not in kws:
kws['fld2col_widths'] = {'D1': 6, 'NS':3, 'depth': 5, 'GO': 12, 'name': 40}
if 'hdrs' not in kws:
kws['hdrs'] = self.hdrs
wr_xlsx_tbl(fout_xlsx, data_nts, **kws) | python | def wr_xlsx(self, fout_xlsx="gos_depth01.xlsx", **kws):
"""Write xlsx table of depth-01 GO terms and their letter representation."""
data_nts = self.get_d1nts()
if 'fld2col_widths' not in kws:
kws['fld2col_widths'] = {'D1': 6, 'NS':3, 'depth': 5, 'GO': 12, 'name': 40}
if 'hdrs' not in kws:
kws['hdrs'] = self.hdrs
wr_xlsx_tbl(fout_xlsx, data_nts, **kws) | [
"def",
"wr_xlsx",
"(",
"self",
",",
"fout_xlsx",
"=",
"\"gos_depth01.xlsx\"",
",",
"*",
"*",
"kws",
")",
":",
"data_nts",
"=",
"self",
".",
"get_d1nts",
"(",
")",
"if",
"'fld2col_widths'",
"not",
"in",
"kws",
":",
"kws",
"[",
"'fld2col_widths'",
"]",
"=",
"{",
"'D1'",
":",
"6",
",",
"'NS'",
":",
"3",
",",
"'depth'",
":",
"5",
",",
"'GO'",
":",
"12",
",",
"'name'",
":",
"40",
"}",
"if",
"'hdrs'",
"not",
"in",
"kws",
":",
"kws",
"[",
"'hdrs'",
"]",
"=",
"self",
".",
"hdrs",
"wr_xlsx_tbl",
"(",
"fout_xlsx",
",",
"data_nts",
",",
"*",
"*",
"kws",
")"
] | Write xlsx table of depth-01 GO terms and their letter representation. | [
"Write",
"xlsx",
"table",
"of",
"depth",
"-",
"01",
"GO",
"terms",
"and",
"their",
"letter",
"representation",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/rpt/wr_xlsx.py#L102-L109 |
228,693 | tanghaibao/goatools | goatools/gosubdag/rpt/wr_xlsx.py | GoDepth1LettersWr.get_d1nts | def get_d1nts(self):
"""Get letters for depth-01 GO terms, descendants count, and GO information."""
data = []
ntdata = cx.namedtuple("NtPrt", "D1 NS dcnt depth GO name")
namespace = None
for ntlet in sorted(self.goone2ntletter.values(),
key=lambda nt: [nt.goobj.namespace, -1 * nt.dcnt, nt.D1]):
goobj = ntlet.goobj
goid = goobj.id
assert len(goobj.parents) == 1
if namespace != goobj.namespace:
namespace = goobj.namespace
ntns = self.ns2nt[namespace]
pobj = ntns.goobj
ns2 = self.str2ns[goobj.namespace]
data.append(ntdata._make([" ", ns2, ntns.dcnt, pobj.depth, pobj.id, pobj.name]))
data.append(ntdata._make(
[ntlet.D1, self.str2ns[namespace], ntlet.dcnt, goobj.depth, goid, goobj.name]))
return data | python | def get_d1nts(self):
"""Get letters for depth-01 GO terms, descendants count, and GO information."""
data = []
ntdata = cx.namedtuple("NtPrt", "D1 NS dcnt depth GO name")
namespace = None
for ntlet in sorted(self.goone2ntletter.values(),
key=lambda nt: [nt.goobj.namespace, -1 * nt.dcnt, nt.D1]):
goobj = ntlet.goobj
goid = goobj.id
assert len(goobj.parents) == 1
if namespace != goobj.namespace:
namespace = goobj.namespace
ntns = self.ns2nt[namespace]
pobj = ntns.goobj
ns2 = self.str2ns[goobj.namespace]
data.append(ntdata._make([" ", ns2, ntns.dcnt, pobj.depth, pobj.id, pobj.name]))
data.append(ntdata._make(
[ntlet.D1, self.str2ns[namespace], ntlet.dcnt, goobj.depth, goid, goobj.name]))
return data | [
"def",
"get_d1nts",
"(",
"self",
")",
":",
"data",
"=",
"[",
"]",
"ntdata",
"=",
"cx",
".",
"namedtuple",
"(",
"\"NtPrt\"",
",",
"\"D1 NS dcnt depth GO name\"",
")",
"namespace",
"=",
"None",
"for",
"ntlet",
"in",
"sorted",
"(",
"self",
".",
"goone2ntletter",
".",
"values",
"(",
")",
",",
"key",
"=",
"lambda",
"nt",
":",
"[",
"nt",
".",
"goobj",
".",
"namespace",
",",
"-",
"1",
"*",
"nt",
".",
"dcnt",
",",
"nt",
".",
"D1",
"]",
")",
":",
"goobj",
"=",
"ntlet",
".",
"goobj",
"goid",
"=",
"goobj",
".",
"id",
"assert",
"len",
"(",
"goobj",
".",
"parents",
")",
"==",
"1",
"if",
"namespace",
"!=",
"goobj",
".",
"namespace",
":",
"namespace",
"=",
"goobj",
".",
"namespace",
"ntns",
"=",
"self",
".",
"ns2nt",
"[",
"namespace",
"]",
"pobj",
"=",
"ntns",
".",
"goobj",
"ns2",
"=",
"self",
".",
"str2ns",
"[",
"goobj",
".",
"namespace",
"]",
"data",
".",
"append",
"(",
"ntdata",
".",
"_make",
"(",
"[",
"\" \"",
",",
"ns2",
",",
"ntns",
".",
"dcnt",
",",
"pobj",
".",
"depth",
",",
"pobj",
".",
"id",
",",
"pobj",
".",
"name",
"]",
")",
")",
"data",
".",
"append",
"(",
"ntdata",
".",
"_make",
"(",
"[",
"ntlet",
".",
"D1",
",",
"self",
".",
"str2ns",
"[",
"namespace",
"]",
",",
"ntlet",
".",
"dcnt",
",",
"goobj",
".",
"depth",
",",
"goid",
",",
"goobj",
".",
"name",
"]",
")",
")",
"return",
"data"
] | Get letters for depth-01 GO terms, descendants count, and GO information. | [
"Get",
"letters",
"for",
"depth",
"-",
"01",
"GO",
"terms",
"descendants",
"count",
"and",
"GO",
"information",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/rpt/wr_xlsx.py#L172-L190 |
228,694 | tanghaibao/goatools | goatools/gosubdag/rpt/wr_xlsx.py | GoDepth1LettersWr._init_ns2nt | def _init_ns2nt(rcntobj):
"""Save depth-00 GO terms ordered using descendants cnt."""
go2dcnt = rcntobj.go2dcnt
ntobj = cx.namedtuple("NtD1", "D1 dcnt goobj")
d0s = rcntobj.depth2goobjs[0]
ns_nt = [(o.namespace, ntobj(D1="", dcnt=go2dcnt[o.id], goobj=o)) for o in d0s]
return cx.OrderedDict(ns_nt) | python | def _init_ns2nt(rcntobj):
"""Save depth-00 GO terms ordered using descendants cnt."""
go2dcnt = rcntobj.go2dcnt
ntobj = cx.namedtuple("NtD1", "D1 dcnt goobj")
d0s = rcntobj.depth2goobjs[0]
ns_nt = [(o.namespace, ntobj(D1="", dcnt=go2dcnt[o.id], goobj=o)) for o in d0s]
return cx.OrderedDict(ns_nt) | [
"def",
"_init_ns2nt",
"(",
"rcntobj",
")",
":",
"go2dcnt",
"=",
"rcntobj",
".",
"go2dcnt",
"ntobj",
"=",
"cx",
".",
"namedtuple",
"(",
"\"NtD1\"",
",",
"\"D1 dcnt goobj\"",
")",
"d0s",
"=",
"rcntobj",
".",
"depth2goobjs",
"[",
"0",
"]",
"ns_nt",
"=",
"[",
"(",
"o",
".",
"namespace",
",",
"ntobj",
"(",
"D1",
"=",
"\"\"",
",",
"dcnt",
"=",
"go2dcnt",
"[",
"o",
".",
"id",
"]",
",",
"goobj",
"=",
"o",
")",
")",
"for",
"o",
"in",
"d0s",
"]",
"return",
"cx",
".",
"OrderedDict",
"(",
"ns_nt",
")"
] | Save depth-00 GO terms ordered using descendants cnt. | [
"Save",
"depth",
"-",
"00",
"GO",
"terms",
"ordered",
"using",
"descendants",
"cnt",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/rpt/wr_xlsx.py#L193-L199 |
228,695 | tanghaibao/goatools | goatools/grouper/wrxlsx.py | WrXlsxSortedGos._get_xlsx_kws | def _get_xlsx_kws(self, **kws_usr):
"""Return keyword arguments relevant to writing an xlsx."""
kws_xlsx = {'fld2col_widths':self._get_fld2col_widths(**kws_usr), 'items':'GO IDs'}
remaining_keys = set(['title', 'hdrs', 'prt_flds', 'fld2fmt',
'ntval2wbfmtdict', 'ntfld_wbfmt'])
for usr_key, usr_val in kws_usr.items():
if usr_key in remaining_keys:
kws_xlsx[usr_key] = usr_val
return kws_xlsx | python | def _get_xlsx_kws(self, **kws_usr):
"""Return keyword arguments relevant to writing an xlsx."""
kws_xlsx = {'fld2col_widths':self._get_fld2col_widths(**kws_usr), 'items':'GO IDs'}
remaining_keys = set(['title', 'hdrs', 'prt_flds', 'fld2fmt',
'ntval2wbfmtdict', 'ntfld_wbfmt'])
for usr_key, usr_val in kws_usr.items():
if usr_key in remaining_keys:
kws_xlsx[usr_key] = usr_val
return kws_xlsx | [
"def",
"_get_xlsx_kws",
"(",
"self",
",",
"*",
"*",
"kws_usr",
")",
":",
"kws_xlsx",
"=",
"{",
"'fld2col_widths'",
":",
"self",
".",
"_get_fld2col_widths",
"(",
"*",
"*",
"kws_usr",
")",
",",
"'items'",
":",
"'GO IDs'",
"}",
"remaining_keys",
"=",
"set",
"(",
"[",
"'title'",
",",
"'hdrs'",
",",
"'prt_flds'",
",",
"'fld2fmt'",
",",
"'ntval2wbfmtdict'",
",",
"'ntfld_wbfmt'",
"]",
")",
"for",
"usr_key",
",",
"usr_val",
"in",
"kws_usr",
".",
"items",
"(",
")",
":",
"if",
"usr_key",
"in",
"remaining_keys",
":",
"kws_xlsx",
"[",
"usr_key",
"]",
"=",
"usr_val",
"return",
"kws_xlsx"
] | Return keyword arguments relevant to writing an xlsx. | [
"Return",
"keyword",
"arguments",
"relevant",
"to",
"writing",
"an",
"xlsx",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/wrxlsx.py#L113-L121 |
228,696 | tanghaibao/goatools | goatools/grouper/wrxlsx.py | WrXlsxSortedGos._adjust_prt_flds | def _adjust_prt_flds(self, kws_xlsx, desc2nts, shade_hdrgos):
"""Print user-requested fields or provided fields minus info fields."""
# Use xlsx prt_flds from the user, if provided
if "prt_flds" in kws_xlsx:
return kws_xlsx["prt_flds"]
# If the user did not provide specific fields to print in an xlsx file:
dont_print = set(['hdr_idx', 'is_hdrgo', 'is_usrgo'])
# Are we printing GO group headers?
# Build new list of xlsx print fields, excluding those which add no new information
prt_flds_adjusted = []
# Get all namedtuple fields
nt_flds = self.sortobj.get_fields(desc2nts)
# Keep fields intended for print and optionally gray-shade field (format_txt)
# print('FFFFFFFFFFFFFFF WrXlsxSortedGos::_adjust_prt_flds:', nt_flds)
for nt_fld in nt_flds:
if nt_fld not in dont_print:
# Only add grey-shade to hdrgo and section name rows if hdrgo_prt=True
if nt_fld == "format_txt":
if shade_hdrgos is True:
prt_flds_adjusted.append(nt_fld)
else:
prt_flds_adjusted.append(nt_fld)
kws_xlsx['prt_flds'] = prt_flds_adjusted | python | def _adjust_prt_flds(self, kws_xlsx, desc2nts, shade_hdrgos):
"""Print user-requested fields or provided fields minus info fields."""
# Use xlsx prt_flds from the user, if provided
if "prt_flds" in kws_xlsx:
return kws_xlsx["prt_flds"]
# If the user did not provide specific fields to print in an xlsx file:
dont_print = set(['hdr_idx', 'is_hdrgo', 'is_usrgo'])
# Are we printing GO group headers?
# Build new list of xlsx print fields, excluding those which add no new information
prt_flds_adjusted = []
# Get all namedtuple fields
nt_flds = self.sortobj.get_fields(desc2nts)
# Keep fields intended for print and optionally gray-shade field (format_txt)
# print('FFFFFFFFFFFFFFF WrXlsxSortedGos::_adjust_prt_flds:', nt_flds)
for nt_fld in nt_flds:
if nt_fld not in dont_print:
# Only add grey-shade to hdrgo and section name rows if hdrgo_prt=True
if nt_fld == "format_txt":
if shade_hdrgos is True:
prt_flds_adjusted.append(nt_fld)
else:
prt_flds_adjusted.append(nt_fld)
kws_xlsx['prt_flds'] = prt_flds_adjusted | [
"def",
"_adjust_prt_flds",
"(",
"self",
",",
"kws_xlsx",
",",
"desc2nts",
",",
"shade_hdrgos",
")",
":",
"# Use xlsx prt_flds from the user, if provided",
"if",
"\"prt_flds\"",
"in",
"kws_xlsx",
":",
"return",
"kws_xlsx",
"[",
"\"prt_flds\"",
"]",
"# If the user did not provide specific fields to print in an xlsx file:",
"dont_print",
"=",
"set",
"(",
"[",
"'hdr_idx'",
",",
"'is_hdrgo'",
",",
"'is_usrgo'",
"]",
")",
"# Are we printing GO group headers?",
"# Build new list of xlsx print fields, excluding those which add no new information",
"prt_flds_adjusted",
"=",
"[",
"]",
"# Get all namedtuple fields",
"nt_flds",
"=",
"self",
".",
"sortobj",
".",
"get_fields",
"(",
"desc2nts",
")",
"# Keep fields intended for print and optionally gray-shade field (format_txt)",
"# print('FFFFFFFFFFFFFFF WrXlsxSortedGos::_adjust_prt_flds:', nt_flds)",
"for",
"nt_fld",
"in",
"nt_flds",
":",
"if",
"nt_fld",
"not",
"in",
"dont_print",
":",
"# Only add grey-shade to hdrgo and section name rows if hdrgo_prt=True",
"if",
"nt_fld",
"==",
"\"format_txt\"",
":",
"if",
"shade_hdrgos",
"is",
"True",
":",
"prt_flds_adjusted",
".",
"append",
"(",
"nt_fld",
")",
"else",
":",
"prt_flds_adjusted",
".",
"append",
"(",
"nt_fld",
")",
"kws_xlsx",
"[",
"'prt_flds'",
"]",
"=",
"prt_flds_adjusted"
] | Print user-requested fields or provided fields minus info fields. | [
"Print",
"user",
"-",
"requested",
"fields",
"or",
"provided",
"fields",
"minus",
"info",
"fields",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/wrxlsx.py#L123-L145 |
228,697 | tanghaibao/goatools | goatools/grouper/wrxlsx.py | WrXlsxSortedGos._get_fld2col_widths | def _get_fld2col_widths(self, **kws):
"""Return xlsx column widths based on default and user-specified field-value pairs."""
fld2col_widths = self._init_fld2col_widths()
if 'fld2col_widths' not in kws:
return fld2col_widths
for fld, val in kws['fld2col_widths'].items():
fld2col_widths[fld] = val
return fld2col_widths | python | def _get_fld2col_widths(self, **kws):
"""Return xlsx column widths based on default and user-specified field-value pairs."""
fld2col_widths = self._init_fld2col_widths()
if 'fld2col_widths' not in kws:
return fld2col_widths
for fld, val in kws['fld2col_widths'].items():
fld2col_widths[fld] = val
return fld2col_widths | [
"def",
"_get_fld2col_widths",
"(",
"self",
",",
"*",
"*",
"kws",
")",
":",
"fld2col_widths",
"=",
"self",
".",
"_init_fld2col_widths",
"(",
")",
"if",
"'fld2col_widths'",
"not",
"in",
"kws",
":",
"return",
"fld2col_widths",
"for",
"fld",
",",
"val",
"in",
"kws",
"[",
"'fld2col_widths'",
"]",
".",
"items",
"(",
")",
":",
"fld2col_widths",
"[",
"fld",
"]",
"=",
"val",
"return",
"fld2col_widths"
] | Return xlsx column widths based on default and user-specified field-value pairs. | [
"Return",
"xlsx",
"column",
"widths",
"based",
"on",
"default",
"and",
"user",
"-",
"specified",
"field",
"-",
"value",
"pairs",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/wrxlsx.py#L147-L154 |
228,698 | tanghaibao/goatools | goatools/grouper/wrxlsx.py | WrXlsxSortedGos._init_fld2col_widths | def _init_fld2col_widths(self):
"""Return default column widths for writing an Excel Spreadsheet."""
# GO info namedtuple fields: NS dcnt level depth GO D1 name
# GO header namedtuple fields: format_txt hdr_idx
fld2col_widths = GoSubDagWr.fld2col_widths.copy()
for fld, wid in self.oprtfmt.default_fld2col_widths.items():
fld2col_widths[fld] = wid
for fld in get_hdridx_flds():
fld2col_widths[fld] = 2
return fld2col_widths | python | def _init_fld2col_widths(self):
"""Return default column widths for writing an Excel Spreadsheet."""
# GO info namedtuple fields: NS dcnt level depth GO D1 name
# GO header namedtuple fields: format_txt hdr_idx
fld2col_widths = GoSubDagWr.fld2col_widths.copy()
for fld, wid in self.oprtfmt.default_fld2col_widths.items():
fld2col_widths[fld] = wid
for fld in get_hdridx_flds():
fld2col_widths[fld] = 2
return fld2col_widths | [
"def",
"_init_fld2col_widths",
"(",
"self",
")",
":",
"# GO info namedtuple fields: NS dcnt level depth GO D1 name",
"# GO header namedtuple fields: format_txt hdr_idx",
"fld2col_widths",
"=",
"GoSubDagWr",
".",
"fld2col_widths",
".",
"copy",
"(",
")",
"for",
"fld",
",",
"wid",
"in",
"self",
".",
"oprtfmt",
".",
"default_fld2col_widths",
".",
"items",
"(",
")",
":",
"fld2col_widths",
"[",
"fld",
"]",
"=",
"wid",
"for",
"fld",
"in",
"get_hdridx_flds",
"(",
")",
":",
"fld2col_widths",
"[",
"fld",
"]",
"=",
"2",
"return",
"fld2col_widths"
] | Return default column widths for writing an Excel Spreadsheet. | [
"Return",
"default",
"column",
"widths",
"for",
"writing",
"an",
"Excel",
"Spreadsheet",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/wrxlsx.py#L156-L165 |
228,699 | tanghaibao/goatools | goatools/grouper/wrxlsx.py | WrXlsxSortedGos._get_shade_hdrgos | def _get_shade_hdrgos(**kws):
"""If no hdrgo_prt specified, and these conditions are present -> hdrgo_prt=F."""
# KWS: shade_hdrgos hdrgo_prt section_sortby top_n
if 'shade_hdrgos' in kws:
return kws['shade_hdrgos']
# Return user-sepcified hdrgo_prt, if provided
if 'hdrgo_prt' in kws:
return kws['hdrgo_prt']
# If no hdrgo_prt provided, set hdrgo_prt to False if:
# * section_sortby == True
# * section_sortby = user_sort
# * top_n == N
if 'section_sortby' in kws and kws['section_sortby']:
return False
if 'top_n' in kws and isinstance(kws['top_n'], int):
return False
return True | python | def _get_shade_hdrgos(**kws):
"""If no hdrgo_prt specified, and these conditions are present -> hdrgo_prt=F."""
# KWS: shade_hdrgos hdrgo_prt section_sortby top_n
if 'shade_hdrgos' in kws:
return kws['shade_hdrgos']
# Return user-sepcified hdrgo_prt, if provided
if 'hdrgo_prt' in kws:
return kws['hdrgo_prt']
# If no hdrgo_prt provided, set hdrgo_prt to False if:
# * section_sortby == True
# * section_sortby = user_sort
# * top_n == N
if 'section_sortby' in kws and kws['section_sortby']:
return False
if 'top_n' in kws and isinstance(kws['top_n'], int):
return False
return True | [
"def",
"_get_shade_hdrgos",
"(",
"*",
"*",
"kws",
")",
":",
"# KWS: shade_hdrgos hdrgo_prt section_sortby top_n",
"if",
"'shade_hdrgos'",
"in",
"kws",
":",
"return",
"kws",
"[",
"'shade_hdrgos'",
"]",
"# Return user-sepcified hdrgo_prt, if provided",
"if",
"'hdrgo_prt'",
"in",
"kws",
":",
"return",
"kws",
"[",
"'hdrgo_prt'",
"]",
"# If no hdrgo_prt provided, set hdrgo_prt to False if:",
"# * section_sortby == True",
"# * section_sortby = user_sort",
"# * top_n == N",
"if",
"'section_sortby'",
"in",
"kws",
"and",
"kws",
"[",
"'section_sortby'",
"]",
":",
"return",
"False",
"if",
"'top_n'",
"in",
"kws",
"and",
"isinstance",
"(",
"kws",
"[",
"'top_n'",
"]",
",",
"int",
")",
":",
"return",
"False",
"return",
"True"
] | If no hdrgo_prt specified, and these conditions are present -> hdrgo_prt=F. | [
"If",
"no",
"hdrgo_prt",
"specified",
"and",
"these",
"conditions",
"are",
"present",
"-",
">",
"hdrgo_prt",
"=",
"F",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/wrxlsx.py#L174-L190 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.