partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | get_root_resource | Returns the root resource. | nefertari/resource.py | def get_root_resource(config):
"""Returns the root resource."""
app_package_name = get_app_package_name(config)
return config.registry._root_resources.setdefault(
app_package_name, Resource(config)) | def get_root_resource(config):
"""Returns the root resource."""
app_package_name = get_app_package_name(config)
return config.registry._root_resources.setdefault(
app_package_name, Resource(config)) | [
"Returns",
"the",
"root",
"resource",
"."
] | ramses-tech/nefertari | python | https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/resource.py#L46-L50 | [
"def",
"get_root_resource",
"(",
"config",
")",
":",
"app_package_name",
"=",
"get_app_package_name",
"(",
"config",
")",
"return",
"config",
".",
"registry",
".",
"_root_resources",
".",
"setdefault",
"(",
"app_package_name",
",",
"Resource",
"(",
"config",
")",
... | c7caffe11576c11aa111adbdbadeff70ce66b1dd |
train | add_resource_routes | ``view`` is a dotted name of (or direct reference to) a
Python view class,
e.g. ``'my.package.views.MyView'``.
``member_name`` should be the appropriate singular version of the resource
given your locale and used with members of the collection.
``collection_name`` will be used to refer to the reso... | nefertari/resource.py | def add_resource_routes(config, view, member_name, collection_name, **kwargs):
"""
``view`` is a dotted name of (or direct reference to) a
Python view class,
e.g. ``'my.package.views.MyView'``.
``member_name`` should be the appropriate singular version of the resource
given your locale and used... | def add_resource_routes(config, view, member_name, collection_name, **kwargs):
"""
``view`` is a dotted name of (or direct reference to) a
Python view class,
e.g. ``'my.package.views.MyView'``.
``member_name`` should be the appropriate singular version of the resource
given your locale and used... | [
"view",
"is",
"a",
"dotted",
"name",
"of",
"(",
"or",
"direct",
"reference",
"to",
")",
"a",
"Python",
"view",
"class",
"e",
".",
"g",
".",
"my",
".",
"package",
".",
"views",
".",
"MyView",
"."
] | ramses-tech/nefertari | python | https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/resource.py#L57-L190 | [
"def",
"add_resource_routes",
"(",
"config",
",",
"view",
",",
"member_name",
",",
"collection_name",
",",
"*",
"*",
"kwargs",
")",
":",
"view",
"=",
"maybe_dotted",
"(",
"view",
")",
"path_prefix",
"=",
"kwargs",
".",
"pop",
"(",
"'path_prefix'",
",",
"''... | c7caffe11576c11aa111adbdbadeff70ce66b1dd |
train | get_default_view_path | Returns the dotted path to the default view class. | nefertari/resource.py | def get_default_view_path(resource):
"Returns the dotted path to the default view class."
parts = [a.member_name for a in resource.ancestors] +\
[resource.collection_name or resource.member_name]
if resource.prefix:
parts.insert(-1, resource.prefix)
view_file = '%s' % '_'.join(par... | def get_default_view_path(resource):
"Returns the dotted path to the default view class."
parts = [a.member_name for a in resource.ancestors] +\
[resource.collection_name or resource.member_name]
if resource.prefix:
parts.insert(-1, resource.prefix)
view_file = '%s' % '_'.join(par... | [
"Returns",
"the",
"dotted",
"path",
"to",
"the",
"default",
"view",
"class",
"."
] | ramses-tech/nefertari | python | https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/resource.py#L193-L206 | [
"def",
"get_default_view_path",
"(",
"resource",
")",
":",
"parts",
"=",
"[",
"a",
".",
"member_name",
"for",
"a",
"in",
"resource",
".",
"ancestors",
"]",
"+",
"[",
"resource",
".",
"collection_name",
"or",
"resource",
".",
"member_name",
"]",
"if",
"reso... | c7caffe11576c11aa111adbdbadeff70ce66b1dd |
train | Resource.get_ancestors | Returns the list of ancestor resources. | nefertari/resource.py | def get_ancestors(self):
"Returns the list of ancestor resources."
if self._ancestors:
return self._ancestors
if not self.parent:
return []
obj = self.resource_map.get(self.parent.uid)
while obj and obj.member_name:
self._ancestors.append(o... | def get_ancestors(self):
"Returns the list of ancestor resources."
if self._ancestors:
return self._ancestors
if not self.parent:
return []
obj = self.resource_map.get(self.parent.uid)
while obj and obj.member_name:
self._ancestors.append(o... | [
"Returns",
"the",
"list",
"of",
"ancestor",
"resources",
"."
] | ramses-tech/nefertari | python | https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/resource.py#L231-L247 | [
"def",
"get_ancestors",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ancestors",
":",
"return",
"self",
".",
"_ancestors",
"if",
"not",
"self",
".",
"parent",
":",
"return",
"[",
"]",
"obj",
"=",
"self",
".",
"resource_map",
".",
"get",
"(",
"self",
"... | c7caffe11576c11aa111adbdbadeff70ce66b1dd |
train | Resource.add | :param member_name: singular name of the resource. It should be the
appropriate singular version of the resource given your locale
and used with members of the collection.
:param collection_name: plural name of the resource. It will be used
to refer to the resource collectio... | nefertari/resource.py | def add(self, member_name, collection_name='', parent=None, uid='',
**kwargs):
"""
:param member_name: singular name of the resource. It should be the
appropriate singular version of the resource given your locale
and used with members of the collection.
:par... | def add(self, member_name, collection_name='', parent=None, uid='',
**kwargs):
"""
:param member_name: singular name of the resource. It should be the
appropriate singular version of the resource given your locale
and used with members of the collection.
:par... | [
":",
"param",
"member_name",
":",
"singular",
"name",
"of",
"the",
"resource",
".",
"It",
"should",
"be",
"the",
"appropriate",
"singular",
"version",
"of",
"the",
"resource",
"given",
"your",
"locale",
"and",
"used",
"with",
"members",
"of",
"the",
"collect... | ramses-tech/nefertari | python | https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/resource.py#L257-L379 | [
"def",
"add",
"(",
"self",
",",
"member_name",
",",
"collection_name",
"=",
"''",
",",
"parent",
"=",
"None",
",",
"uid",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"# self is the parent resource on which this method is called.",
"parent",
"=",
"(",
"self",... | c7caffe11576c11aa111adbdbadeff70ce66b1dd |
train | Resource.add_from_child | Add a resource with its all children resources to the current
resource. | nefertari/resource.py | def add_from_child(self, resource, **kwargs):
""" Add a resource with its all children resources to the current
resource.
"""
new_resource = self.add(
resource.member_name, resource.collection_name, **kwargs)
for child in resource.children:
new_resource.a... | def add_from_child(self, resource, **kwargs):
""" Add a resource with its all children resources to the current
resource.
"""
new_resource = self.add(
resource.member_name, resource.collection_name, **kwargs)
for child in resource.children:
new_resource.a... | [
"Add",
"a",
"resource",
"with",
"its",
"all",
"children",
"resources",
"to",
"the",
"current",
"resource",
"."
] | ramses-tech/nefertari | python | https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/resource.py#L381-L389 | [
"def",
"add_from_child",
"(",
"self",
",",
"resource",
",",
"*",
"*",
"kwargs",
")",
":",
"new_resource",
"=",
"self",
".",
"add",
"(",
"resource",
".",
"member_name",
",",
"resource",
".",
"collection_name",
",",
"*",
"*",
"kwargs",
")",
"for",
"child",... | c7caffe11576c11aa111adbdbadeff70ce66b1dd |
train | DatasetContainer.add | Add the path of a data set to the list of available sets
NOTE: a data set is assumed to be a pickled
and gzip compressed Pandas DataFrame
Parameters
----------
path : str | opengrid/datasets/datasets.py | def add(self, path):
"""
Add the path of a data set to the list of available sets
NOTE: a data set is assumed to be a pickled
and gzip compressed Pandas DataFrame
Parameters
----------
path : str
"""
name_with_ext = os.path.split(path)[1] # spli... | def add(self, path):
"""
Add the path of a data set to the list of available sets
NOTE: a data set is assumed to be a pickled
and gzip compressed Pandas DataFrame
Parameters
----------
path : str
"""
name_with_ext = os.path.split(path)[1] # spli... | [
"Add",
"the",
"path",
"of",
"a",
"data",
"set",
"to",
"the",
"list",
"of",
"available",
"sets"
] | opengridcc/opengrid | python | https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/datasets/datasets.py#L27-L40 | [
"def",
"add",
"(",
"self",
",",
"path",
")",
":",
"name_with_ext",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"[",
"1",
"]",
"# split directory and filename",
"name",
"=",
"name_with_ext",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"#... | 69b8da3c8fcea9300226c45ef0628cd6d4307651 |
train | DatasetContainer.unpack | Unpacks a data set to a Pandas DataFrame
Parameters
----------
name : str
call `.list` to see all availble datasets
Returns
-------
pd.DataFrame | opengrid/datasets/datasets.py | def unpack(self, name):
"""
Unpacks a data set to a Pandas DataFrame
Parameters
----------
name : str
call `.list` to see all availble datasets
Returns
-------
pd.DataFrame
"""
path = self.list[name]
df = pd.read_pickl... | def unpack(self, name):
"""
Unpacks a data set to a Pandas DataFrame
Parameters
----------
name : str
call `.list` to see all availble datasets
Returns
-------
pd.DataFrame
"""
path = self.list[name]
df = pd.read_pickl... | [
"Unpacks",
"a",
"data",
"set",
"to",
"a",
"Pandas",
"DataFrame"
] | opengridcc/opengrid | python | https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/datasets/datasets.py#L42-L57 | [
"def",
"unpack",
"(",
"self",
",",
"name",
")",
":",
"path",
"=",
"self",
".",
"list",
"[",
"name",
"]",
"df",
"=",
"pd",
".",
"read_pickle",
"(",
"path",
",",
"compression",
"=",
"'gzip'",
")",
"return",
"df"
] | 69b8da3c8fcea9300226c45ef0628cd6d4307651 |
train | six_frame | translate each sequence into six reading frames | ctbBio/sixframe.py | def six_frame(genome, table, minimum = 10):
"""
translate each sequence into six reading frames
"""
for seq in parse_fasta(genome):
dna = Seq(seq[1].upper().replace('U', 'T'), IUPAC.ambiguous_dna)
counter = 0
for sequence in ['f', dna], ['rc', dna.reverse_complement()]:
... | def six_frame(genome, table, minimum = 10):
"""
translate each sequence into six reading frames
"""
for seq in parse_fasta(genome):
dna = Seq(seq[1].upper().replace('U', 'T'), IUPAC.ambiguous_dna)
counter = 0
for sequence in ['f', dna], ['rc', dna.reverse_complement()]:
... | [
"translate",
"each",
"sequence",
"into",
"six",
"reading",
"frames"
] | christophertbrown/bioscripts | python | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/sixframe.py#L13-L32 | [
"def",
"six_frame",
"(",
"genome",
",",
"table",
",",
"minimum",
"=",
"10",
")",
":",
"for",
"seq",
"in",
"parse_fasta",
"(",
"genome",
")",
":",
"dna",
"=",
"Seq",
"(",
"seq",
"[",
"1",
"]",
".",
"upper",
"(",
")",
".",
"replace",
"(",
"'U'",
... | 83b2566b3a5745437ec651cd6cafddd056846240 |
train | publish_processed_network_packets | # Redis/RabbitMQ/SQS messaging endpoints for pub-sub
routing_key = ev("PUBLISH_EXCHANGE",
"reporting.accounts")
queue_name = ev("PUBLISH_QUEUE",
"reporting.accounts")
auth_url = ev("PUB_BROKER_URL",
"redis://localhost:6379/15")
serializer = "jso... | network_pipeline/scripts/network_agent.py | def publish_processed_network_packets(
name="not-set",
task_queue=None,
result_queue=None,
need_response=False,
shutdown_msg="SHUTDOWN"):
"""
# Redis/RabbitMQ/SQS messaging endpoints for pub-sub
routing_key = ev("PUBLISH_EXCHANGE",
"reporting.acc... | def publish_processed_network_packets(
name="not-set",
task_queue=None,
result_queue=None,
need_response=False,
shutdown_msg="SHUTDOWN"):
"""
# Redis/RabbitMQ/SQS messaging endpoints for pub-sub
routing_key = ev("PUBLISH_EXCHANGE",
"reporting.acc... | [
"#",
"Redis",
"/",
"RabbitMQ",
"/",
"SQS",
"messaging",
"endpoints",
"for",
"pub",
"-",
"sub",
"routing_key",
"=",
"ev",
"(",
"PUBLISH_EXCHANGE",
"reporting",
".",
"accounts",
")",
"queue_name",
"=",
"ev",
"(",
"PUBLISH_QUEUE",
"reporting",
".",
"accounts",
... | jay-johnson/network-pipeline | python | https://github.com/jay-johnson/network-pipeline/blob/4e53ae13fe12085e0cf2e5e1aff947368f4f1ffa/network_pipeline/scripts/network_agent.py#L35-L244 | [
"def",
"publish_processed_network_packets",
"(",
"name",
"=",
"\"not-set\"",
",",
"task_queue",
"=",
"None",
",",
"result_queue",
"=",
"None",
",",
"need_response",
"=",
"False",
",",
"shutdown_msg",
"=",
"\"SHUTDOWN\"",
")",
":",
"# these keys need to be cycled to pr... | 4e53ae13fe12085e0cf2e5e1aff947368f4f1ffa |
train | run_main | run_main
start the packet consumers and the packet processors
:param need_response: should send response back to publisher
:param callback: handler method | network_pipeline/scripts/network_agent.py | def run_main(
need_response=False,
callback=None):
"""run_main
start the packet consumers and the packet processors
:param need_response: should send response back to publisher
:param callback: handler method
"""
stop_file = ev("STOP_FILE",
"/opt/stop_record... | def run_main(
need_response=False,
callback=None):
"""run_main
start the packet consumers and the packet processors
:param need_response: should send response back to publisher
:param callback: handler method
"""
stop_file = ev("STOP_FILE",
"/opt/stop_record... | [
"run_main"
] | jay-johnson/network-pipeline | python | https://github.com/jay-johnson/network-pipeline/blob/4e53ae13fe12085e0cf2e5e1aff947368f4f1ffa/network_pipeline/scripts/network_agent.py#L248-L341 | [
"def",
"run_main",
"(",
"need_response",
"=",
"False",
",",
"callback",
"=",
"None",
")",
":",
"stop_file",
"=",
"ev",
"(",
"\"STOP_FILE\"",
",",
"\"/opt/stop_recording\"",
")",
"num_workers",
"=",
"int",
"(",
"ev",
"(",
"\"NUM_WORKERS\"",
",",
"\"1\"",
")",... | 4e53ae13fe12085e0cf2e5e1aff947368f4f1ffa |
train | best_model | determine the best model: archaea, bacteria, eukarya (best score) | ctbBio/16SfromHMM.py | def best_model(seq2hmm):
"""
determine the best model: archaea, bacteria, eukarya (best score)
"""
for seq in seq2hmm:
best = []
for model in seq2hmm[seq]:
best.append([model, sorted([i[-1] for i in seq2hmm[seq][model]], reverse = True)[0]])
best_model = sorted(best, ... | def best_model(seq2hmm):
"""
determine the best model: archaea, bacteria, eukarya (best score)
"""
for seq in seq2hmm:
best = []
for model in seq2hmm[seq]:
best.append([model, sorted([i[-1] for i in seq2hmm[seq][model]], reverse = True)[0]])
best_model = sorted(best, ... | [
"determine",
"the",
"best",
"model",
":",
"archaea",
"bacteria",
"eukarya",
"(",
"best",
"score",
")"
] | christophertbrown/bioscripts | python | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L21-L31 | [
"def",
"best_model",
"(",
"seq2hmm",
")",
":",
"for",
"seq",
"in",
"seq2hmm",
":",
"best",
"=",
"[",
"]",
"for",
"model",
"in",
"seq2hmm",
"[",
"seq",
"]",
":",
"best",
".",
"append",
"(",
"[",
"model",
",",
"sorted",
"(",
"[",
"i",
"[",
"-",
"... | 83b2566b3a5745437ec651cd6cafddd056846240 |
train | check_gaps | check for large gaps between alignment windows | ctbBio/16SfromHMM.py | def check_gaps(matches, gap_threshold = 0):
"""
check for large gaps between alignment windows
"""
gaps = []
prev = None
for match in sorted(matches, key = itemgetter(0)):
if prev is None:
prev = match
continue
if match[0] - prev[1] >= gap_threshold:
... | def check_gaps(matches, gap_threshold = 0):
"""
check for large gaps between alignment windows
"""
gaps = []
prev = None
for match in sorted(matches, key = itemgetter(0)):
if prev is None:
prev = match
continue
if match[0] - prev[1] >= gap_threshold:
... | [
"check",
"for",
"large",
"gaps",
"between",
"alignment",
"windows"
] | christophertbrown/bioscripts | python | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L33-L46 | [
"def",
"check_gaps",
"(",
"matches",
",",
"gap_threshold",
"=",
"0",
")",
":",
"gaps",
"=",
"[",
"]",
"prev",
"=",
"None",
"for",
"match",
"in",
"sorted",
"(",
"matches",
",",
"key",
"=",
"itemgetter",
"(",
"0",
")",
")",
":",
"if",
"prev",
"is",
... | 83b2566b3a5745437ec651cd6cafddd056846240 |
train | check_overlap | determine if sequence has already hit the same part of the model,
indicating that this hit is for another 16S rRNA gene | ctbBio/16SfromHMM.py | def check_overlap(current, hit, overlap = 200):
"""
determine if sequence has already hit the same part of the model,
indicating that this hit is for another 16S rRNA gene
"""
for prev in current:
p_coords = prev[2:4]
coords = hit[2:4]
if get_overlap(coords, p_coords) >= over... | def check_overlap(current, hit, overlap = 200):
"""
determine if sequence has already hit the same part of the model,
indicating that this hit is for another 16S rRNA gene
"""
for prev in current:
p_coords = prev[2:4]
coords = hit[2:4]
if get_overlap(coords, p_coords) >= over... | [
"determine",
"if",
"sequence",
"has",
"already",
"hit",
"the",
"same",
"part",
"of",
"the",
"model",
"indicating",
"that",
"this",
"hit",
"is",
"for",
"another",
"16S",
"rRNA",
"gene"
] | christophertbrown/bioscripts | python | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L51-L61 | [
"def",
"check_overlap",
"(",
"current",
",",
"hit",
",",
"overlap",
"=",
"200",
")",
":",
"for",
"prev",
"in",
"current",
":",
"p_coords",
"=",
"prev",
"[",
"2",
":",
"4",
"]",
"coords",
"=",
"hit",
"[",
"2",
":",
"4",
"]",
"if",
"get_overlap",
"... | 83b2566b3a5745437ec651cd6cafddd056846240 |
train | check_order | determine if hits are sequential on model and on the
same strand
* if not, they should be split into different groups | ctbBio/16SfromHMM.py | def check_order(current, hit, overlap = 200):
"""
determine if hits are sequential on model and on the
same strand
* if not, they should be split into different groups
"""
prev_model = current[-1][2:4]
prev_strand = current[-1][-2]
hit_model = hit[2:4]
hit_strand = hit[-2]
# ... | def check_order(current, hit, overlap = 200):
"""
determine if hits are sequential on model and on the
same strand
* if not, they should be split into different groups
"""
prev_model = current[-1][2:4]
prev_strand = current[-1][-2]
hit_model = hit[2:4]
hit_strand = hit[-2]
# ... | [
"determine",
"if",
"hits",
"are",
"sequential",
"on",
"model",
"and",
"on",
"the",
"same",
"strand",
"*",
"if",
"not",
"they",
"should",
"be",
"split",
"into",
"different",
"groups"
] | christophertbrown/bioscripts | python | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L63-L83 | [
"def",
"check_order",
"(",
"current",
",",
"hit",
",",
"overlap",
"=",
"200",
")",
":",
"prev_model",
"=",
"current",
"[",
"-",
"1",
"]",
"[",
"2",
":",
"4",
"]",
"prev_strand",
"=",
"current",
"[",
"-",
"1",
"]",
"[",
"-",
"2",
"]",
"hit_model",... | 83b2566b3a5745437ec651cd6cafddd056846240 |
train | hit_groups | * each sequence may have more than one 16S rRNA gene
* group hits for each gene | ctbBio/16SfromHMM.py | def hit_groups(hits):
"""
* each sequence may have more than one 16S rRNA gene
* group hits for each gene
"""
groups = []
current = False
for hit in sorted(hits, key = itemgetter(0)):
if current is False:
current = [hit]
elif check_overlap(current, hit) is True or... | def hit_groups(hits):
"""
* each sequence may have more than one 16S rRNA gene
* group hits for each gene
"""
groups = []
current = False
for hit in sorted(hits, key = itemgetter(0)):
if current is False:
current = [hit]
elif check_overlap(current, hit) is True or... | [
"*",
"each",
"sequence",
"may",
"have",
"more",
"than",
"one",
"16S",
"rRNA",
"gene",
"*",
"group",
"hits",
"for",
"each",
"gene"
] | christophertbrown/bioscripts | python | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L85-L101 | [
"def",
"hit_groups",
"(",
"hits",
")",
":",
"groups",
"=",
"[",
"]",
"current",
"=",
"False",
"for",
"hit",
"in",
"sorted",
"(",
"hits",
",",
"key",
"=",
"itemgetter",
"(",
"0",
")",
")",
":",
"if",
"current",
"is",
"False",
":",
"current",
"=",
... | 83b2566b3a5745437ec651cd6cafddd056846240 |
train | find_coordinates | find 16S rRNA gene sequence coordinates | ctbBio/16SfromHMM.py | def find_coordinates(hmms, bit_thresh):
"""
find 16S rRNA gene sequence coordinates
"""
# get coordinates from cmsearch output
seq2hmm = parse_hmm(hmms, bit_thresh)
seq2hmm = best_model(seq2hmm)
group2hmm = {} # group2hmm[seq][group] = [model, strand, coordinates, matches, gaps]
for seq,... | def find_coordinates(hmms, bit_thresh):
"""
find 16S rRNA gene sequence coordinates
"""
# get coordinates from cmsearch output
seq2hmm = parse_hmm(hmms, bit_thresh)
seq2hmm = best_model(seq2hmm)
group2hmm = {} # group2hmm[seq][group] = [model, strand, coordinates, matches, gaps]
for seq,... | [
"find",
"16S",
"rRNA",
"gene",
"sequence",
"coordinates"
] | christophertbrown/bioscripts | python | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L103-L126 | [
"def",
"find_coordinates",
"(",
"hmms",
",",
"bit_thresh",
")",
":",
"# get coordinates from cmsearch output",
"seq2hmm",
"=",
"parse_hmm",
"(",
"hmms",
",",
"bit_thresh",
")",
"seq2hmm",
"=",
"best_model",
"(",
"seq2hmm",
")",
"group2hmm",
"=",
"{",
"}",
"# gro... | 83b2566b3a5745437ec651cd6cafddd056846240 |
train | get_info | get info from either ssu-cmsearch or cmsearch output | ctbBio/16SfromHMM.py | def get_info(line, bit_thresh):
"""
get info from either ssu-cmsearch or cmsearch output
"""
if len(line) >= 18: # output is from cmsearch
id, model, bit, inc = line[0].split()[0], line[2], float(line[14]), line[16]
sstart, send, strand = int(line[7]), int(line[8]), line[9]
mstar... | def get_info(line, bit_thresh):
"""
get info from either ssu-cmsearch or cmsearch output
"""
if len(line) >= 18: # output is from cmsearch
id, model, bit, inc = line[0].split()[0], line[2], float(line[14]), line[16]
sstart, send, strand = int(line[7]), int(line[8]), line[9]
mstar... | [
"get",
"info",
"from",
"either",
"ssu",
"-",
"cmsearch",
"or",
"cmsearch",
"output"
] | christophertbrown/bioscripts | python | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L128-L157 | [
"def",
"get_info",
"(",
"line",
",",
"bit_thresh",
")",
":",
"if",
"len",
"(",
"line",
")",
">=",
"18",
":",
"# output is from cmsearch",
"id",
",",
"model",
",",
"bit",
",",
"inc",
"=",
"line",
"[",
"0",
"]",
".",
"split",
"(",
")",
"[",
"0",
"]... | 83b2566b3a5745437ec651cd6cafddd056846240 |
train | check_buffer | check to see how much of the buffer is being used | ctbBio/16SfromHMM.py | def check_buffer(coords, length, buffer):
"""
check to see how much of the buffer is being used
"""
s = min(coords[0], buffer)
e = min(length - coords[1], buffer)
return [s, e] | def check_buffer(coords, length, buffer):
"""
check to see how much of the buffer is being used
"""
s = min(coords[0], buffer)
e = min(length - coords[1], buffer)
return [s, e] | [
"check",
"to",
"see",
"how",
"much",
"of",
"the",
"buffer",
"is",
"being",
"used"
] | christophertbrown/bioscripts | python | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L189-L195 | [
"def",
"check_buffer",
"(",
"coords",
",",
"length",
",",
"buffer",
")",
":",
"s",
"=",
"min",
"(",
"coords",
"[",
"0",
"]",
",",
"buffer",
")",
"e",
"=",
"min",
"(",
"length",
"-",
"coords",
"[",
"1",
"]",
",",
"buffer",
")",
"return",
"[",
"s... | 83b2566b3a5745437ec651cd6cafddd056846240 |
train | convert_parser_to | :return: a parser of type parser_or_type, initialized with the properties of parser. If parser_or_type
is a type, an instance of it must contain a update method. The update method must also process
the set of properties supported by MetadataParser for the conversion to have any affect.
:param parser: the pa... | gis_metadata/metadata_parser.py | def convert_parser_to(parser, parser_or_type, metadata_props=None):
"""
:return: a parser of type parser_or_type, initialized with the properties of parser. If parser_or_type
is a type, an instance of it must contain a update method. The update method must also process
the set of properties supported by... | def convert_parser_to(parser, parser_or_type, metadata_props=None):
"""
:return: a parser of type parser_or_type, initialized with the properties of parser. If parser_or_type
is a type, an instance of it must contain a update method. The update method must also process
the set of properties supported by... | [
":",
"return",
":",
"a",
"parser",
"of",
"type",
"parser_or_type",
"initialized",
"with",
"the",
"properties",
"of",
"parser",
".",
"If",
"parser_or_type",
"is",
"a",
"type",
"an",
"instance",
"of",
"it",
"must",
"contain",
"a",
"update",
"method",
".",
"T... | consbio/gis-metadata-parser | python | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L30-L48 | [
"def",
"convert_parser_to",
"(",
"parser",
",",
"parser_or_type",
",",
"metadata_props",
"=",
"None",
")",
":",
"old_parser",
"=",
"parser",
"if",
"isinstance",
"(",
"parser",
",",
"MetadataParser",
")",
"else",
"get_metadata_parser",
"(",
"parser",
")",
"new_pa... | 59eefb2e51cd4d8cc3e94623a2167499ca9ef70f |
train | get_metadata_parser | Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file.
:return: a new instance of a parser corresponding to the standard represented by metadata_container
:see: get_parsed_content(metdata_content) for more on types of content that can be parsed | gis_metadata/metadata_parser.py | def get_metadata_parser(metadata_container, **metadata_defaults):
"""
Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file.
:return: a new instance of a parser corresponding to the standard represented by metadata_container
:see: get_parsed_content(metdata_con... | def get_metadata_parser(metadata_container, **metadata_defaults):
"""
Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file.
:return: a new instance of a parser corresponding to the standard represented by metadata_container
:see: get_parsed_content(metdata_con... | [
"Takes",
"a",
"metadata_container",
"which",
"may",
"be",
"a",
"type",
"or",
"instance",
"of",
"a",
"parser",
"a",
"dict",
"string",
"or",
"file",
".",
":",
"return",
":",
"a",
"new",
"instance",
"of",
"a",
"parser",
"corresponding",
"to",
"the",
"standa... | consbio/gis-metadata-parser | python | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L51-L85 | [
"def",
"get_metadata_parser",
"(",
"metadata_container",
",",
"*",
"*",
"metadata_defaults",
")",
":",
"parser_type",
"=",
"None",
"if",
"isinstance",
"(",
"metadata_container",
",",
"MetadataParser",
")",
":",
"parser_type",
"=",
"type",
"(",
"metadata_container",
... | 59eefb2e51cd4d8cc3e94623a2167499ca9ef70f |
train | get_parsed_content | Parses any of the following types of content:
1. XML string or file object: parses XML content
2. MetadataParser instance: deep copies xml_tree
3. Dictionary with nested objects containing:
- name (required): the name of the element tag
- text: the text contained by element
- tail: t... | gis_metadata/metadata_parser.py | def get_parsed_content(metadata_content):
"""
Parses any of the following types of content:
1. XML string or file object: parses XML content
2. MetadataParser instance: deep copies xml_tree
3. Dictionary with nested objects containing:
- name (required): the name of the element tag
-... | def get_parsed_content(metadata_content):
"""
Parses any of the following types of content:
1. XML string or file object: parses XML content
2. MetadataParser instance: deep copies xml_tree
3. Dictionary with nested objects containing:
- name (required): the name of the element tag
-... | [
"Parses",
"any",
"of",
"the",
"following",
"types",
"of",
"content",
":",
"1",
".",
"XML",
"string",
"or",
"file",
"object",
":",
"parses",
"XML",
"content",
"2",
".",
"MetadataParser",
"instance",
":",
"deep",
"copies",
"xml_tree",
"3",
".",
"Dictionary",... | consbio/gis-metadata-parser | python | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L88-L138 | [
"def",
"get_parsed_content",
"(",
"metadata_content",
")",
":",
"_import_parsers",
"(",
")",
"# Prevents circular dependencies between modules",
"xml_tree",
"=",
"None",
"if",
"metadata_content",
"is",
"None",
":",
"raise",
"NoContent",
"(",
"'Metadata has no data'",
")",... | 59eefb2e51cd4d8cc3e94623a2167499ca9ef70f |
train | _import_parsers | Lazy imports to prevent circular dependencies between this module and utils | gis_metadata/metadata_parser.py | def _import_parsers():
""" Lazy imports to prevent circular dependencies between this module and utils """
global ARCGIS_NODES
global ARCGIS_ROOTS
global ArcGISParser
global FGDC_ROOT
global FgdcParser
global ISO_ROOTS
global IsoParser
global VALID_ROOTS
if ARCGIS_NODES is N... | def _import_parsers():
""" Lazy imports to prevent circular dependencies between this module and utils """
global ARCGIS_NODES
global ARCGIS_ROOTS
global ArcGISParser
global FGDC_ROOT
global FgdcParser
global ISO_ROOTS
global IsoParser
global VALID_ROOTS
if ARCGIS_NODES is N... | [
"Lazy",
"imports",
"to",
"prevent",
"circular",
"dependencies",
"between",
"this",
"module",
"and",
"utils"
] | consbio/gis-metadata-parser | python | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L141-L170 | [
"def",
"_import_parsers",
"(",
")",
":",
"global",
"ARCGIS_NODES",
"global",
"ARCGIS_ROOTS",
"global",
"ArcGISParser",
"global",
"FGDC_ROOT",
"global",
"FgdcParser",
"global",
"ISO_ROOTS",
"global",
"IsoParser",
"global",
"VALID_ROOTS",
"if",
"ARCGIS_NODES",
"is",
"No... | 59eefb2e51cd4d8cc3e94623a2167499ca9ef70f |
train | MetadataParser._init_metadata | Dynamically sets attributes from a Dictionary passed in by children.
The Dictionary will contain the name of each attribute as keys, and
either an XPATH mapping to a text value in _xml_tree, or a function
that takes no parameters and returns the intended value. | gis_metadata/metadata_parser.py | def _init_metadata(self):
"""
Dynamically sets attributes from a Dictionary passed in by children.
The Dictionary will contain the name of each attribute as keys, and
either an XPATH mapping to a text value in _xml_tree, or a function
that takes no parameters and returns the inte... | def _init_metadata(self):
"""
Dynamically sets attributes from a Dictionary passed in by children.
The Dictionary will contain the name of each attribute as keys, and
either an XPATH mapping to a text value in _xml_tree, or a function
that takes no parameters and returns the inte... | [
"Dynamically",
"sets",
"attributes",
"from",
"a",
"Dictionary",
"passed",
"in",
"by",
"children",
".",
"The",
"Dictionary",
"will",
"contain",
"the",
"name",
"of",
"each",
"attribute",
"as",
"keys",
"and",
"either",
"an",
"XPATH",
"mapping",
"to",
"a",
"text... | consbio/gis-metadata-parser | python | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L236-L254 | [
"def",
"_init_metadata",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data_map",
"is",
"None",
":",
"self",
".",
"_init_data_map",
"(",
")",
"validate_properties",
"(",
"self",
".",
"_data_map",
",",
"self",
".",
"_metadata_props",
")",
"# Parse attribute value... | 59eefb2e51cd4d8cc3e94623a2167499ca9ef70f |
train | MetadataParser._init_data_map | Default data map initialization: MUST be overridden in children | gis_metadata/metadata_parser.py | def _init_data_map(self):
""" Default data map initialization: MUST be overridden in children """
if self._data_map is None:
self._data_map = {'_root': None}
self._data_map.update({}.fromkeys(self._metadata_props)) | def _init_data_map(self):
""" Default data map initialization: MUST be overridden in children """
if self._data_map is None:
self._data_map = {'_root': None}
self._data_map.update({}.fromkeys(self._metadata_props)) | [
"Default",
"data",
"map",
"initialization",
":",
"MUST",
"be",
"overridden",
"in",
"children"
] | consbio/gis-metadata-parser | python | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L256-L261 | [
"def",
"_init_data_map",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data_map",
"is",
"None",
":",
"self",
".",
"_data_map",
"=",
"{",
"'_root'",
":",
"None",
"}",
"self",
".",
"_data_map",
".",
"update",
"(",
"{",
"}",
".",
"fromkeys",
"(",
"self",
... | 59eefb2e51cd4d8cc3e94623a2167499ca9ef70f |
train | MetadataParser._get_template | Iterate over items metadata_defaults {prop: val, ...} to populate template | gis_metadata/metadata_parser.py | def _get_template(self, root=None, **metadata_defaults):
""" Iterate over items metadata_defaults {prop: val, ...} to populate template """
if root is None:
if self._data_map is None:
self._init_data_map()
root = self._xml_root = self._data_map['_root']
... | def _get_template(self, root=None, **metadata_defaults):
""" Iterate over items metadata_defaults {prop: val, ...} to populate template """
if root is None:
if self._data_map is None:
self._init_data_map()
root = self._xml_root = self._data_map['_root']
... | [
"Iterate",
"over",
"items",
"metadata_defaults",
"{",
"prop",
":",
"val",
"...",
"}",
"to",
"populate",
"template"
] | consbio/gis-metadata-parser | python | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L263-L280 | [
"def",
"_get_template",
"(",
"self",
",",
"root",
"=",
"None",
",",
"*",
"*",
"metadata_defaults",
")",
":",
"if",
"root",
"is",
"None",
":",
"if",
"self",
".",
"_data_map",
"is",
"None",
":",
"self",
".",
"_init_data_map",
"(",
")",
"root",
"=",
"se... | 59eefb2e51cd4d8cc3e94623a2167499ca9ef70f |
train | MetadataParser._get_xpath_for | :return: the configured xpath for a given property | gis_metadata/metadata_parser.py | def _get_xpath_for(self, prop):
""" :return: the configured xpath for a given property """
xpath = self._data_map.get(prop)
return getattr(xpath, 'xpath', xpath) | def _get_xpath_for(self, prop):
""" :return: the configured xpath for a given property """
xpath = self._data_map.get(prop)
return getattr(xpath, 'xpath', xpath) | [
":",
"return",
":",
"the",
"configured",
"xpath",
"for",
"a",
"given",
"property"
] | consbio/gis-metadata-parser | python | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L282-L286 | [
"def",
"_get_xpath_for",
"(",
"self",
",",
"prop",
")",
":",
"xpath",
"=",
"self",
".",
"_data_map",
".",
"get",
"(",
"prop",
")",
"return",
"getattr",
"(",
"xpath",
",",
"'xpath'",
",",
"xpath",
")"
] | 59eefb2e51cd4d8cc3e94623a2167499ca9ef70f |
train | MetadataParser._parse_complex | Default parsing operation for a complex struct | gis_metadata/metadata_parser.py | def _parse_complex(self, prop):
""" Default parsing operation for a complex struct """
xpath_root = None
xpath_map = self._data_structures[prop]
return parse_complex(self._xml_tree, xpath_root, xpath_map, prop) | def _parse_complex(self, prop):
""" Default parsing operation for a complex struct """
xpath_root = None
xpath_map = self._data_structures[prop]
return parse_complex(self._xml_tree, xpath_root, xpath_map, prop) | [
"Default",
"parsing",
"operation",
"for",
"a",
"complex",
"struct"
] | consbio/gis-metadata-parser | python | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L293-L299 | [
"def",
"_parse_complex",
"(",
"self",
",",
"prop",
")",
":",
"xpath_root",
"=",
"None",
"xpath_map",
"=",
"self",
".",
"_data_structures",
"[",
"prop",
"]",
"return",
"parse_complex",
"(",
"self",
".",
"_xml_tree",
",",
"xpath_root",
",",
"xpath_map",
",",
... | 59eefb2e51cd4d8cc3e94623a2167499ca9ef70f |
train | MetadataParser._parse_complex_list | Default parsing operation for lists of complex structs | gis_metadata/metadata_parser.py | def _parse_complex_list(self, prop):
""" Default parsing operation for lists of complex structs """
xpath_root = self._get_xroot_for(prop)
xpath_map = self._data_structures[prop]
return parse_complex_list(self._xml_tree, xpath_root, xpath_map, prop) | def _parse_complex_list(self, prop):
""" Default parsing operation for lists of complex structs """
xpath_root = self._get_xroot_for(prop)
xpath_map = self._data_structures[prop]
return parse_complex_list(self._xml_tree, xpath_root, xpath_map, prop) | [
"Default",
"parsing",
"operation",
"for",
"lists",
"of",
"complex",
"structs"
] | consbio/gis-metadata-parser | python | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L301-L307 | [
"def",
"_parse_complex_list",
"(",
"self",
",",
"prop",
")",
":",
"xpath_root",
"=",
"self",
".",
"_get_xroot_for",
"(",
"prop",
")",
"xpath_map",
"=",
"self",
".",
"_data_structures",
"[",
"prop",
"]",
"return",
"parse_complex_list",
"(",
"self",
".",
"_xml... | 59eefb2e51cd4d8cc3e94623a2167499ca9ef70f |
train | MetadataParser._parse_dates | Creates and returns a Date Types data structure parsed from the metadata | gis_metadata/metadata_parser.py | def _parse_dates(self, prop=DATES):
""" Creates and returns a Date Types data structure parsed from the metadata """
return parse_dates(self._xml_tree, self._data_structures[prop]) | def _parse_dates(self, prop=DATES):
""" Creates and returns a Date Types data structure parsed from the metadata """
return parse_dates(self._xml_tree, self._data_structures[prop]) | [
"Creates",
"and",
"returns",
"a",
"Date",
"Types",
"data",
"structure",
"parsed",
"from",
"the",
"metadata"
] | consbio/gis-metadata-parser | python | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L309-L312 | [
"def",
"_parse_dates",
"(",
"self",
",",
"prop",
"=",
"DATES",
")",
":",
"return",
"parse_dates",
"(",
"self",
".",
"_xml_tree",
",",
"self",
".",
"_data_structures",
"[",
"prop",
"]",
")"
] | 59eefb2e51cd4d8cc3e94623a2167499ca9ef70f |
train | MetadataParser._update_complex | Default update operation for a complex struct | gis_metadata/metadata_parser.py | def _update_complex(self, **update_props):
""" Default update operation for a complex struct """
prop = update_props['prop']
xpath_root = self._get_xroot_for(prop)
xpath_map = self._data_structures[prop]
return update_complex(xpath_root=xpath_root, xpath_map=xpath_map, **update... | def _update_complex(self, **update_props):
""" Default update operation for a complex struct """
prop = update_props['prop']
xpath_root = self._get_xroot_for(prop)
xpath_map = self._data_structures[prop]
return update_complex(xpath_root=xpath_root, xpath_map=xpath_map, **update... | [
"Default",
"update",
"operation",
"for",
"a",
"complex",
"struct"
] | consbio/gis-metadata-parser | python | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L314-L321 | [
"def",
"_update_complex",
"(",
"self",
",",
"*",
"*",
"update_props",
")",
":",
"prop",
"=",
"update_props",
"[",
"'prop'",
"]",
"xpath_root",
"=",
"self",
".",
"_get_xroot_for",
"(",
"prop",
")",
"xpath_map",
"=",
"self",
".",
"_data_structures",
"[",
"pr... | 59eefb2e51cd4d8cc3e94623a2167499ca9ef70f |
train | MetadataParser._update_complex_list | Default update operation for lists of complex structs | gis_metadata/metadata_parser.py | def _update_complex_list(self, **update_props):
""" Default update operation for lists of complex structs """
prop = update_props['prop']
xpath_root = self._get_xroot_for(prop)
xpath_map = self._data_structures[prop]
return update_complex_list(xpath_root=xpath_root, xpath_map=x... | def _update_complex_list(self, **update_props):
""" Default update operation for lists of complex structs """
prop = update_props['prop']
xpath_root = self._get_xroot_for(prop)
xpath_map = self._data_structures[prop]
return update_complex_list(xpath_root=xpath_root, xpath_map=x... | [
"Default",
"update",
"operation",
"for",
"lists",
"of",
"complex",
"structs"
] | consbio/gis-metadata-parser | python | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L323-L330 | [
"def",
"_update_complex_list",
"(",
"self",
",",
"*",
"*",
"update_props",
")",
":",
"prop",
"=",
"update_props",
"[",
"'prop'",
"]",
"xpath_root",
"=",
"self",
".",
"_get_xroot_for",
"(",
"prop",
")",
"xpath_map",
"=",
"self",
".",
"_data_structures",
"[",
... | 59eefb2e51cd4d8cc3e94623a2167499ca9ef70f |
train | MetadataParser._update_dates | Default update operation for Dates metadata
:see: gis_metadata.utils._complex_definitions[DATES] | gis_metadata/metadata_parser.py | def _update_dates(self, xpath_root=None, **update_props):
"""
Default update operation for Dates metadata
:see: gis_metadata.utils._complex_definitions[DATES]
"""
tree_to_update = update_props['tree_to_update']
prop = update_props['prop']
values = (update_props['... | def _update_dates(self, xpath_root=None, **update_props):
"""
Default update operation for Dates metadata
:see: gis_metadata.utils._complex_definitions[DATES]
"""
tree_to_update = update_props['tree_to_update']
prop = update_props['prop']
values = (update_props['... | [
"Default",
"update",
"operation",
"for",
"Dates",
"metadata",
":",
"see",
":",
"gis_metadata",
".",
"utils",
".",
"_complex_definitions",
"[",
"DATES",
"]"
] | consbio/gis-metadata-parser | python | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L332-L356 | [
"def",
"_update_dates",
"(",
"self",
",",
"xpath_root",
"=",
"None",
",",
"*",
"*",
"update_props",
")",
":",
"tree_to_update",
"=",
"update_props",
"[",
"'tree_to_update'",
"]",
"prop",
"=",
"update_props",
"[",
"'prop'",
"]",
"values",
"=",
"(",
"update_pr... | 59eefb2e51cd4d8cc3e94623a2167499ca9ef70f |
train | MetadataParser.write | Validates instance properties, updates an XML tree with them, and writes the content to a file.
:param use_template: if True, updates a new template XML tree; otherwise the original XML tree
:param out_file_or_path: optionally override self.out_file_or_path with a custom file path
:param encodin... | gis_metadata/metadata_parser.py | def write(self, use_template=False, out_file_or_path=None, encoding=DEFAULT_ENCODING):
"""
Validates instance properties, updates an XML tree with them, and writes the content to a file.
:param use_template: if True, updates a new template XML tree; otherwise the original XML tree
:param... | def write(self, use_template=False, out_file_or_path=None, encoding=DEFAULT_ENCODING):
"""
Validates instance properties, updates an XML tree with them, and writes the content to a file.
:param use_template: if True, updates a new template XML tree; otherwise the original XML tree
:param... | [
"Validates",
"instance",
"properties",
"updates",
"an",
"XML",
"tree",
"with",
"them",
"and",
"writes",
"the",
"content",
"to",
"a",
"file",
".",
":",
"param",
"use_template",
":",
"if",
"True",
"updates",
"a",
"new",
"template",
"XML",
"tree",
";",
"other... | consbio/gis-metadata-parser | python | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L373-L388 | [
"def",
"write",
"(",
"self",
",",
"use_template",
"=",
"False",
",",
"out_file_or_path",
"=",
"None",
",",
"encoding",
"=",
"DEFAULT_ENCODING",
")",
":",
"if",
"not",
"out_file_or_path",
":",
"out_file_or_path",
"=",
"self",
".",
"out_file_or_path",
"if",
"not... | 59eefb2e51cd4d8cc3e94623a2167499ca9ef70f |
train | MetadataParser.validate | Default validation for updated properties: MAY be overridden in children | gis_metadata/metadata_parser.py | def validate(self):
""" Default validation for updated properties: MAY be overridden in children """
validate_properties(self._data_map, self._metadata_props)
for prop in self._data_map:
validate_any(prop, getattr(self, prop), self._data_structures.get(prop))
return self | def validate(self):
""" Default validation for updated properties: MAY be overridden in children """
validate_properties(self._data_map, self._metadata_props)
for prop in self._data_map:
validate_any(prop, getattr(self, prop), self._data_structures.get(prop))
return self | [
"Default",
"validation",
"for",
"updated",
"properties",
":",
"MAY",
"be",
"overridden",
"in",
"children"
] | consbio/gis-metadata-parser | python | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/metadata_parser.py#L410-L418 | [
"def",
"validate",
"(",
"self",
")",
":",
"validate_properties",
"(",
"self",
".",
"_data_map",
",",
"self",
".",
"_metadata_props",
")",
"for",
"prop",
"in",
"self",
".",
"_data_map",
":",
"validate_any",
"(",
"prop",
",",
"getattr",
"(",
"self",
",",
"... | 59eefb2e51cd4d8cc3e94623a2167499ca9ef70f |
train | _search_regex | Search order:
* specified regexps
* operators sorted from longer to shorter | sugartex/sugartex_filter.py | def _search_regex(ops: dict, regex_pat: str):
"""
Search order:
* specified regexps
* operators sorted from longer to shorter
"""
custom_regexps = list(filter(None, [dic['regex'] for op, dic in ops.items() if 'regex' in dic]))
op_names = [op for op, dic in ops.items() if 'regex' not in d... | def _search_regex(ops: dict, regex_pat: str):
"""
Search order:
* specified regexps
* operators sorted from longer to shorter
"""
custom_regexps = list(filter(None, [dic['regex'] for op, dic in ops.items() if 'regex' in dic]))
op_names = [op for op, dic in ops.items() if 'regex' not in d... | [
"Search",
"order",
":",
"*",
"specified",
"regexps",
"*",
"operators",
"sorted",
"from",
"longer",
"to",
"shorter"
] | kiwi0fruit/sugartex | python | https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L165-L174 | [
"def",
"_search_regex",
"(",
"ops",
":",
"dict",
",",
"regex_pat",
":",
"str",
")",
":",
"custom_regexps",
"=",
"list",
"(",
"filter",
"(",
"None",
",",
"[",
"dic",
"[",
"'regex'",
"]",
"for",
"op",
",",
"dic",
"in",
"ops",
".",
"items",
"(",
")",
... | 9eb13703cb02d3e2163c9c5f29df280f6bf49cec |
train | Styles.spec | Return prefix unary operators list | sugartex/sugartex_filter.py | def spec(self, postf_un_ops: str) -> list:
"""Return prefix unary operators list"""
spec = [(l + op, {'pat': self.pat(pat),
'postf': self.postf(r, postf_un_ops),
'regex': None})
for op, pat in self.styles.items()
for l, ... | def spec(self, postf_un_ops: str) -> list:
"""Return prefix unary operators list"""
spec = [(l + op, {'pat': self.pat(pat),
'postf': self.postf(r, postf_un_ops),
'regex': None})
for op, pat in self.styles.items()
for l, ... | [
"Return",
"prefix",
"unary",
"operators",
"list"
] | kiwi0fruit/sugartex | python | https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L216-L227 | [
"def",
"spec",
"(",
"self",
",",
"postf_un_ops",
":",
"str",
")",
"->",
"list",
":",
"spec",
"=",
"[",
"(",
"l",
"+",
"op",
",",
"{",
"'pat'",
":",
"self",
".",
"pat",
"(",
"pat",
")",
",",
"'postf'",
":",
"self",
".",
"postf",
"(",
"r",
",",... | 9eb13703cb02d3e2163c9c5f29df280f6bf49cec |
train | PrefUnGreedy.spec | Returns prefix unary operators list.
Sets only one regex for all items in the dict. | sugartex/sugartex_filter.py | def spec(self) -> list:
"""Returns prefix unary operators list.
Sets only one regex for all items in the dict."""
spec = [item
for op, pat in self.ops.items()
for item in [('{' + op, {'pat': pat, 'postf': self.postf, 'regex': None}),
(... | def spec(self) -> list:
"""Returns prefix unary operators list.
Sets only one regex for all items in the dict."""
spec = [item
for op, pat in self.ops.items()
for item in [('{' + op, {'pat': pat, 'postf': self.postf, 'regex': None}),
(... | [
"Returns",
"prefix",
"unary",
"operators",
"list",
".",
"Sets",
"only",
"one",
"regex",
"for",
"all",
"items",
"in",
"the",
"dict",
"."
] | kiwi0fruit/sugartex | python | https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L242-L251 | [
"def",
"spec",
"(",
"self",
")",
"->",
"list",
":",
"spec",
"=",
"[",
"item",
"for",
"op",
",",
"pat",
"in",
"self",
".",
"ops",
".",
"items",
"(",
")",
"for",
"item",
"in",
"[",
"(",
"'{'",
"+",
"op",
",",
"{",
"'pat'",
":",
"pat",
",",
"'... | 9eb13703cb02d3e2163c9c5f29df280f6bf49cec |
train | PrefUnOps.fill | Insert:
* math styles
* other styles
* unary prefix operators without brackets
* defaults | sugartex/sugartex_filter.py | def fill(self, postf_un_ops: str):
"""
Insert:
* math styles
* other styles
* unary prefix operators without brackets
* defaults
"""
for op, dic in self.ops.items():
if 'postf' not in dic:
dic['postf'] = self.postf
... | def fill(self, postf_un_ops: str):
"""
Insert:
* math styles
* other styles
* unary prefix operators without brackets
* defaults
"""
for op, dic in self.ops.items():
if 'postf' not in dic:
dic['postf'] = self.postf
... | [
"Insert",
":",
"*",
"math",
"styles",
"*",
"other",
"styles",
"*",
"unary",
"prefix",
"operators",
"without",
"brackets",
"*",
"defaults"
] | kiwi0fruit/sugartex | python | https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L325-L344 | [
"def",
"fill",
"(",
"self",
",",
"postf_un_ops",
":",
"str",
")",
":",
"for",
"op",
",",
"dic",
"in",
"self",
".",
"ops",
".",
"items",
"(",
")",
":",
"if",
"'postf'",
"not",
"in",
"dic",
":",
"dic",
"[",
"'postf'",
"]",
"=",
"self",
".",
"post... | 9eb13703cb02d3e2163c9c5f29df280f6bf49cec |
train | PostfUnOps.one_symbol_ops_str | Regex-escaped string with all one-symbol operators | sugartex/sugartex_filter.py | def one_symbol_ops_str(self) -> str:
"""Regex-escaped string with all one-symbol operators"""
return re.escape(''.join((key for key in self.ops.keys() if len(key) == 1))) | def one_symbol_ops_str(self) -> str:
"""Regex-escaped string with all one-symbol operators"""
return re.escape(''.join((key for key in self.ops.keys() if len(key) == 1))) | [
"Regex",
"-",
"escaped",
"string",
"with",
"all",
"one",
"-",
"symbol",
"operators"
] | kiwi0fruit/sugartex | python | https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L389-L391 | [
"def",
"one_symbol_ops_str",
"(",
"self",
")",
"->",
"str",
":",
"return",
"re",
".",
"escape",
"(",
"''",
".",
"join",
"(",
"(",
"key",
"for",
"key",
"in",
"self",
".",
"ops",
".",
"keys",
"(",
")",
"if",
"len",
"(",
"key",
")",
"==",
"1",
")"... | 9eb13703cb02d3e2163c9c5f29df280f6bf49cec |
train | SugarTeX._su_scripts_regex | :return:
[compiled regex, function] | sugartex/sugartex_filter.py | def _su_scripts_regex(self):
"""
:return:
[compiled regex, function]
"""
sups = re.escape(''.join([k for k in self.superscripts.keys()]))
subs = re.escape(''.join([k for k in self.subscripts.keys()])) # language=PythonRegExp
su_regex = (r'\\([{su_}])|([{sub}]... | def _su_scripts_regex(self):
"""
:return:
[compiled regex, function]
"""
sups = re.escape(''.join([k for k in self.superscripts.keys()]))
subs = re.escape(''.join([k for k in self.subscripts.keys()])) # language=PythonRegExp
su_regex = (r'\\([{su_}])|([{sub}]... | [
":",
"return",
":",
"[",
"compiled",
"regex",
"function",
"]"
] | kiwi0fruit/sugartex | python | https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L671-L696 | [
"def",
"_su_scripts_regex",
"(",
"self",
")",
":",
"sups",
"=",
"re",
".",
"escape",
"(",
"''",
".",
"join",
"(",
"[",
"k",
"for",
"k",
"in",
"self",
".",
"superscripts",
".",
"keys",
"(",
")",
"]",
")",
")",
"subs",
"=",
"re",
".",
"escape",
"... | 9eb13703cb02d3e2163c9c5f29df280f6bf49cec |
train | SugarTeX._local_map | :param match:
:param loc: str
"l" or "r" or "lr"
turns on/off left/right local area calculation
:return: list
list of the same size as the string + 2
it's the local map that counted { and }
list can contain: None or int>=0
from the ... | sugartex/sugartex_filter.py | def _local_map(match, loc: str = 'lr') -> list:
"""
:param match:
:param loc: str
"l" or "r" or "lr"
turns on/off left/right local area calculation
:return: list
list of the same size as the string + 2
it's the local map that counted { and ... | def _local_map(match, loc: str = 'lr') -> list:
"""
:param match:
:param loc: str
"l" or "r" or "lr"
turns on/off left/right local area calculation
:return: list
list of the same size as the string + 2
it's the local map that counted { and ... | [
":",
"param",
"match",
":",
":",
"param",
"loc",
":",
"str",
"l",
"or",
"r",
"or",
"lr",
"turns",
"on",
"/",
"off",
"left",
"/",
"right",
"local",
"area",
"calculation",
":",
"return",
":",
"list",
"list",
"of",
"the",
"same",
"size",
"as",
"the",
... | kiwi0fruit/sugartex | python | https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L708-L753 | [
"def",
"_local_map",
"(",
"match",
",",
"loc",
":",
"str",
"=",
"'lr'",
")",
"->",
"list",
":",
"s",
"=",
"match",
".",
"string",
"map_",
"=",
"[",
"None",
"]",
"*",
"(",
"len",
"(",
"s",
")",
"+",
"2",
")",
"if",
"loc",
"==",
"'l'",
"or",
... | 9eb13703cb02d3e2163c9c5f29df280f6bf49cec |
train | SugarTeX._operators_replace | Searches for first unary or binary operator (via self.op_regex
that has only one group that contain operator)
then replaces it (or escapes it if brackets do not match).
Everything until:
* space ' '
* begin/end of the string
* bracket from outer scope (like '{a/b}':... | sugartex/sugartex_filter.py | def _operators_replace(self, string: str) -> str:
"""
Searches for first unary or binary operator (via self.op_regex
that has only one group that contain operator)
then replaces it (or escapes it if brackets do not match).
Everything until:
* space ' '
* begin... | def _operators_replace(self, string: str) -> str:
"""
Searches for first unary or binary operator (via self.op_regex
that has only one group that contain operator)
then replaces it (or escapes it if brackets do not match).
Everything until:
* space ' '
* begin... | [
"Searches",
"for",
"first",
"unary",
"or",
"binary",
"operator",
"(",
"via",
"self",
".",
"op_regex",
"that",
"has",
"only",
"one",
"group",
"that",
"contain",
"operator",
")",
"then",
"replaces",
"it",
"(",
"or",
"escapes",
"it",
"if",
"brackets",
"do",
... | kiwi0fruit/sugartex | python | https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L755-L849 | [
"def",
"_operators_replace",
"(",
"self",
",",
"string",
":",
"str",
")",
"->",
"str",
":",
"# noinspection PyShadowingNames",
"def",
"replace",
"(",
"string",
":",
"str",
",",
"start",
":",
"int",
",",
"end",
":",
"int",
",",
"substring",
":",
"str",
")... | 9eb13703cb02d3e2163c9c5f29df280f6bf49cec |
train | SugarTeX.replace | Extends LaTeX syntax via regex preprocess
:param src: str
LaTeX string
:return: str
New LaTeX string | sugartex/sugartex_filter.py | def replace(self, src: str) -> str:
"""
Extends LaTeX syntax via regex preprocess
:param src: str
LaTeX string
:return: str
New LaTeX string
"""
if not self.readied:
self.ready()
# Brackets + simple pre replacements:
sr... | def replace(self, src: str) -> str:
"""
Extends LaTeX syntax via regex preprocess
:param src: str
LaTeX string
:return: str
New LaTeX string
"""
if not self.readied:
self.ready()
# Brackets + simple pre replacements:
sr... | [
"Extends",
"LaTeX",
"syntax",
"via",
"regex",
"preprocess",
":",
"param",
"src",
":",
"str",
"LaTeX",
"string",
":",
"return",
":",
"str",
"New",
"LaTeX",
"string"
] | kiwi0fruit/sugartex | python | https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L863-L904 | [
"def",
"replace",
"(",
"self",
",",
"src",
":",
"str",
")",
"->",
"str",
":",
"if",
"not",
"self",
".",
"readied",
":",
"self",
".",
"ready",
"(",
")",
"# Brackets + simple pre replacements:",
"src",
"=",
"self",
".",
"_dict_replace",
"(",
"self",
".",
... | 9eb13703cb02d3e2163c9c5f29df280f6bf49cec |
train | plot_gaps | plot % of gaps at each position | ctbBio/strip_align.py | def plot_gaps(plot, columns):
"""
plot % of gaps at each position
"""
from plot_window import window_plot_convolve as plot_window
# plot_window([columns], len(columns)*.01, plot)
plot_window([[100 - i for i in columns]], len(columns)*.01, plot) | def plot_gaps(plot, columns):
"""
plot % of gaps at each position
"""
from plot_window import window_plot_convolve as plot_window
# plot_window([columns], len(columns)*.01, plot)
plot_window([[100 - i for i in columns]], len(columns)*.01, plot) | [
"plot",
"%",
"of",
"gaps",
"at",
"each",
"position"
] | christophertbrown/bioscripts | python | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/strip_align.py#L11-L17 | [
"def",
"plot_gaps",
"(",
"plot",
",",
"columns",
")",
":",
"from",
"plot_window",
"import",
"window_plot_convolve",
"as",
"plot_window",
"#\tplot_window([columns], len(columns)*.01, plot)",
"plot_window",
"(",
"[",
"[",
"100",
"-",
"i",
"for",
"i",
"in",
"columns",
... | 83b2566b3a5745437ec651cd6cafddd056846240 |
train | strip_msa_100 | strip out columns of a MSA that represent gaps for X percent (threshold) of sequences | ctbBio/strip_align.py | def strip_msa_100(msa, threshold, plot = False):
"""
strip out columns of a MSA that represent gaps for X percent (threshold) of sequences
"""
msa = [seq for seq in parse_fasta(msa)]
columns = [[0, 0] for pos in msa[0][1]] # [[#bases, #gaps], [#bases, #gaps], ...]
for seq in msa:
for position, base in enumerate... | def strip_msa_100(msa, threshold, plot = False):
"""
strip out columns of a MSA that represent gaps for X percent (threshold) of sequences
"""
msa = [seq for seq in parse_fasta(msa)]
columns = [[0, 0] for pos in msa[0][1]] # [[#bases, #gaps], [#bases, #gaps], ...]
for seq in msa:
for position, base in enumerate... | [
"strip",
"out",
"columns",
"of",
"a",
"MSA",
"that",
"represent",
"gaps",
"for",
"X",
"percent",
"(",
"threshold",
")",
"of",
"sequences"
] | christophertbrown/bioscripts | python | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/strip_align.py#L19-L39 | [
"def",
"strip_msa_100",
"(",
"msa",
",",
"threshold",
",",
"plot",
"=",
"False",
")",
":",
"msa",
"=",
"[",
"seq",
"for",
"seq",
"in",
"parse_fasta",
"(",
"msa",
")",
"]",
"columns",
"=",
"[",
"[",
"0",
",",
"0",
"]",
"for",
"pos",
"in",
"msa",
... | 83b2566b3a5745437ec651cd6cafddd056846240 |
train | sample_group | Iterate through all categories in an OrderedDict and return category name if SampleID
present in that category.
:type sid: str
:param sid: SampleID from dataset.
:type groups: OrderedDict
:param groups: Returned dict from phylotoast.util.gather_categories() function.
:return type: str
:re... | bin/extract_shared_or_unique_otuids.py | def sample_group(sid, groups):
"""
Iterate through all categories in an OrderedDict and return category name if SampleID
present in that category.
:type sid: str
:param sid: SampleID from dataset.
:type groups: OrderedDict
:param groups: Returned dict from phylotoast.util.gather_categories... | def sample_group(sid, groups):
"""
Iterate through all categories in an OrderedDict and return category name if SampleID
present in that category.
:type sid: str
:param sid: SampleID from dataset.
:type groups: OrderedDict
:param groups: Returned dict from phylotoast.util.gather_categories... | [
"Iterate",
"through",
"all",
"categories",
"in",
"an",
"OrderedDict",
"and",
"return",
"category",
"name",
"if",
"SampleID",
"present",
"in",
"that",
"category",
"."
] | smdabdoub/phylotoast | python | https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/bin/extract_shared_or_unique_otuids.py#L22-L38 | [
"def",
"sample_group",
"(",
"sid",
",",
"groups",
")",
":",
"for",
"name",
"in",
"groups",
":",
"if",
"sid",
"in",
"groups",
"[",
"name",
"]",
".",
"sids",
":",
"return",
"name"
] | 0b74ef171e6a84761710548501dfac71285a58a3 |
train | combine_sets | Combine multiple sets to create a single larger set. | bin/extract_shared_or_unique_otuids.py | def combine_sets(*sets):
"""
Combine multiple sets to create a single larger set.
"""
combined = set()
for s in sets:
combined.update(s)
return combined | def combine_sets(*sets):
"""
Combine multiple sets to create a single larger set.
"""
combined = set()
for s in sets:
combined.update(s)
return combined | [
"Combine",
"multiple",
"sets",
"to",
"create",
"a",
"single",
"larger",
"set",
"."
] | smdabdoub/phylotoast | python | https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/bin/extract_shared_or_unique_otuids.py#L41-L48 | [
"def",
"combine_sets",
"(",
"*",
"sets",
")",
":",
"combined",
"=",
"set",
"(",
")",
"for",
"s",
"in",
"sets",
":",
"combined",
".",
"update",
"(",
"s",
")",
"return",
"combined"
] | 0b74ef171e6a84761710548501dfac71285a58a3 |
train | unique_otuids | Get unique OTUIDs of each category.
:type groups: Dict
:param groups: {Category name: OTUIDs in category}
:return type: dict
:return: Dict keyed on category name and unique OTUIDs as values. | bin/extract_shared_or_unique_otuids.py | def unique_otuids(groups):
"""
Get unique OTUIDs of each category.
:type groups: Dict
:param groups: {Category name: OTUIDs in category}
:return type: dict
:return: Dict keyed on category name and unique OTUIDs as values.
"""
uniques = {key: set() for key in groups}
for i, group in... | def unique_otuids(groups):
"""
Get unique OTUIDs of each category.
:type groups: Dict
:param groups: {Category name: OTUIDs in category}
:return type: dict
:return: Dict keyed on category name and unique OTUIDs as values.
"""
uniques = {key: set() for key in groups}
for i, group in... | [
"Get",
"unique",
"OTUIDs",
"of",
"each",
"category",
"."
] | smdabdoub/phylotoast | python | https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/bin/extract_shared_or_unique_otuids.py#L51-L66 | [
"def",
"unique_otuids",
"(",
"groups",
")",
":",
"uniques",
"=",
"{",
"key",
":",
"set",
"(",
")",
"for",
"key",
"in",
"groups",
"}",
"for",
"i",
",",
"group",
"in",
"enumerate",
"(",
"groups",
")",
":",
"to_combine",
"=",
"groups",
".",
"values",
... | 0b74ef171e6a84761710548501dfac71285a58a3 |
train | shared_otuids | Get shared OTUIDs between all unique combinations of groups.
:type groups: Dict
:param groups: {Category name: OTUIDs in category}
:return type: dict
:return: Dict keyed on group combination and their shared OTUIDs as values. | bin/extract_shared_or_unique_otuids.py | def shared_otuids(groups):
"""
Get shared OTUIDs between all unique combinations of groups.
:type groups: Dict
:param groups: {Category name: OTUIDs in category}
:return type: dict
:return: Dict keyed on group combination and their shared OTUIDs as values.
"""
for g in sorted(groups):
... | def shared_otuids(groups):
"""
Get shared OTUIDs between all unique combinations of groups.
:type groups: Dict
:param groups: {Category name: OTUIDs in category}
:return type: dict
:return: Dict keyed on group combination and their shared OTUIDs as values.
"""
for g in sorted(groups):
... | [
"Get",
"shared",
"OTUIDs",
"between",
"all",
"unique",
"combinations",
"of",
"groups",
"."
] | smdabdoub/phylotoast | python | https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/bin/extract_shared_or_unique_otuids.py#L69-L93 | [
"def",
"shared_otuids",
"(",
"groups",
")",
":",
"for",
"g",
"in",
"sorted",
"(",
"groups",
")",
":",
"print",
"(",
"\"Number of OTUs in {0}: {1}\"",
".",
"format",
"(",
"g",
",",
"len",
"(",
"groups",
"[",
"g",
"]",
".",
"results",
"[",
"\"otuids\"",
... | 0b74ef171e6a84761710548501dfac71285a58a3 |
train | write_uniques | Given a path, the method writes out one file for each group name in the
uniques dictionary with the file name in the pattern
PATH/prefix_group.txt
with each file containing the unique OTUIDs found when comparing that group
to all the other groups in uniques.
:type path: str
:param path: O... | bin/extract_shared_or_unique_otuids.py | def write_uniques(path, prefix, uniques):
"""
Given a path, the method writes out one file for each group name in the
uniques dictionary with the file name in the pattern
PATH/prefix_group.txt
with each file containing the unique OTUIDs found when comparing that group
to all the other grou... | def write_uniques(path, prefix, uniques):
"""
Given a path, the method writes out one file for each group name in the
uniques dictionary with the file name in the pattern
PATH/prefix_group.txt
with each file containing the unique OTUIDs found when comparing that group
to all the other grou... | [
"Given",
"a",
"path",
"the",
"method",
"writes",
"out",
"one",
"file",
"for",
"each",
"group",
"name",
"in",
"the",
"uniques",
"dictionary",
"with",
"the",
"file",
"name",
"in",
"the",
"pattern"
] | smdabdoub/phylotoast | python | https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/bin/extract_shared_or_unique_otuids.py#L96-L118 | [
"def",
"write_uniques",
"(",
"path",
",",
"prefix",
",",
"uniques",
")",
":",
"for",
"group",
"in",
"uniques",
":",
"fp",
"=",
"osp",
".",
"join",
"(",
"path",
",",
"\"{}_{}.txt\"",
".",
"format",
"(",
"prefix",
",",
"group",
")",
")",
"with",
"open"... | 0b74ef171e6a84761710548501dfac71285a58a3 |
train | storeFASTA | Parse the records in a FASTA-format file by first reading the entire file into memory.
:type source: path to FAST file or open file handle
:param source: The data source from which to parse the FASTA records. Expects the
input to resolve to a collection that can be iterated through, such as
... | phylotoast/util.py | def storeFASTA(fastaFNH):
"""
Parse the records in a FASTA-format file by first reading the entire file into memory.
:type source: path to FAST file or open file handle
:param source: The data source from which to parse the FASTA records. Expects the
input to resolve to a collection ... | def storeFASTA(fastaFNH):
"""
Parse the records in a FASTA-format file by first reading the entire file into memory.
:type source: path to FAST file or open file handle
:param source: The data source from which to parse the FASTA records. Expects the
input to resolve to a collection ... | [
"Parse",
"the",
"records",
"in",
"a",
"FASTA",
"-",
"format",
"file",
"by",
"first",
"reading",
"the",
"entire",
"file",
"into",
"memory",
"."
] | smdabdoub/phylotoast | python | https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/util.py#L20-L34 | [
"def",
"storeFASTA",
"(",
"fastaFNH",
")",
":",
"fasta",
"=",
"file_handle",
"(",
"fastaFNH",
")",
".",
"read",
"(",
")",
"return",
"[",
"FASTARecord",
"(",
"rec",
"[",
"0",
"]",
".",
"split",
"(",
")",
"[",
"0",
"]",
",",
"rec",
"[",
"0",
"]",
... | 0b74ef171e6a84761710548501dfac71285a58a3 |
train | parseFASTA | Parse the records in a FASTA-format file keeping the file open, and reading through
one line at a time.
:type source: path to FAST file or open file handle
:param source: The data source from which to parse the FASTA records.
Expects the input to resolve to a collection that can be itera... | phylotoast/util.py | def parseFASTA(fastaFNH):
"""
Parse the records in a FASTA-format file keeping the file open, and reading through
one line at a time.
:type source: path to FAST file or open file handle
:param source: The data source from which to parse the FASTA records.
Expects the input to res... | def parseFASTA(fastaFNH):
"""
Parse the records in a FASTA-format file keeping the file open, and reading through
one line at a time.
:type source: path to FAST file or open file handle
:param source: The data source from which to parse the FASTA records.
Expects the input to res... | [
"Parse",
"the",
"records",
"in",
"a",
"FASTA",
"-",
"format",
"file",
"keeping",
"the",
"file",
"open",
"and",
"reading",
"through",
"one",
"line",
"at",
"a",
"time",
"."
] | smdabdoub/phylotoast | python | https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/util.py#L37-L73 | [
"def",
"parseFASTA",
"(",
"fastaFNH",
")",
":",
"recs",
"=",
"[",
"]",
"seq",
"=",
"[",
"]",
"seqID",
"=",
"\"\"",
"descr",
"=",
"\"\"",
"for",
"line",
"in",
"file_handle",
"(",
"fastaFNH",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"... | 0b74ef171e6a84761710548501dfac71285a58a3 |
train | parse_map_file | Opens a QIIME mapping file and stores the contents in a dictionary keyed on SampleID
(default) or a user-supplied one. The only required fields are SampleID,
BarcodeSequence, LinkerPrimerSequence (in that order), and Description
(which must be the final field).
:type mapFNH: str
:param mapFNH: Eith... | phylotoast/util.py | def parse_map_file(mapFNH):
"""
Opens a QIIME mapping file and stores the contents in a dictionary keyed on SampleID
(default) or a user-supplied one. The only required fields are SampleID,
BarcodeSequence, LinkerPrimerSequence (in that order), and Description
(which must be the final field).
:... | def parse_map_file(mapFNH):
"""
Opens a QIIME mapping file and stores the contents in a dictionary keyed on SampleID
(default) or a user-supplied one. The only required fields are SampleID,
BarcodeSequence, LinkerPrimerSequence (in that order), and Description
(which must be the final field).
:... | [
"Opens",
"a",
"QIIME",
"mapping",
"file",
"and",
"stores",
"the",
"contents",
"in",
"a",
"dictionary",
"keyed",
"on",
"SampleID",
"(",
"default",
")",
"or",
"a",
"user",
"-",
"supplied",
"one",
".",
"The",
"only",
"required",
"fields",
"are",
"SampleID",
... | smdabdoub/phylotoast | python | https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/util.py#L76-L108 | [
"def",
"parse_map_file",
"(",
"mapFNH",
")",
":",
"m",
"=",
"OrderedDict",
"(",
")",
"map_header",
"=",
"None",
"with",
"file_handle",
"(",
"mapFNH",
")",
"as",
"mapF",
":",
"for",
"line",
"in",
"mapF",
":",
"if",
"line",
".",
"startswith",
"(",
"\"#Sa... | 0b74ef171e6a84761710548501dfac71285a58a3 |
valid | learn | Train a deepq model.
Parameters
-------
env: gym.Env
environment to train on
network: string or a function
neural network to use as a q function approximator. If string, has to be one of the names of registered models in baselines.common.models
(mlp, cnn, conv_only). If a functi... | baselines/deepq/deepq.py | def learn(env,
network,
seed=None,
lr=5e-4,
total_timesteps=100000,
buffer_size=50000,
exploration_fraction=0.1,
exploration_final_eps=0.02,
train_freq=1,
batch_size=32,
print_freq=100,
checkpoint_freq=10000,
... | def learn(env,
network,
seed=None,
lr=5e-4,
total_timesteps=100000,
buffer_size=50000,
exploration_fraction=0.1,
exploration_final_eps=0.02,
train_freq=1,
batch_size=32,
print_freq=100,
checkpoint_freq=10000,
... | [
"Train",
"a",
"deepq",
"model",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/deepq/deepq.py#L95-L333 | [
"def",
"learn",
"(",
"env",
",",
"network",
",",
"seed",
"=",
"None",
",",
"lr",
"=",
"5e-4",
",",
"total_timesteps",
"=",
"100000",
",",
"buffer_size",
"=",
"50000",
",",
"exploration_fraction",
"=",
"0.1",
",",
"exploration_final_eps",
"=",
"0.02",
",",
... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | ActWrapper.save_act | Save model to a pickle located at `path` | baselines/deepq/deepq.py | def save_act(self, path=None):
"""Save model to a pickle located at `path`"""
if path is None:
path = os.path.join(logger.get_dir(), "model.pkl")
with tempfile.TemporaryDirectory() as td:
save_variables(os.path.join(td, "model"))
arc_name = os.path.join(td, "... | def save_act(self, path=None):
"""Save model to a pickle located at `path`"""
if path is None:
path = os.path.join(logger.get_dir(), "model.pkl")
with tempfile.TemporaryDirectory() as td:
save_variables(os.path.join(td, "model"))
arc_name = os.path.join(td, "... | [
"Save",
"model",
"to",
"a",
"pickle",
"located",
"at",
"path"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/deepq/deepq.py#L55-L72 | [
"def",
"save_act",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"logger",
".",
"get_dir",
"(",
")",
",",
"\"model.pkl\"",
")",
"with",
"tempfile",
".",
"Temporar... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | nature_cnn | CNN from Nature paper. | baselines/common/models.py | def nature_cnn(unscaled_images, **conv_kwargs):
"""
CNN from Nature paper.
"""
scaled_images = tf.cast(unscaled_images, tf.float32) / 255.
activ = tf.nn.relu
h = activ(conv(scaled_images, 'c1', nf=32, rf=8, stride=4, init_scale=np.sqrt(2),
**conv_kwargs))
h2 = activ(conv(h... | def nature_cnn(unscaled_images, **conv_kwargs):
"""
CNN from Nature paper.
"""
scaled_images = tf.cast(unscaled_images, tf.float32) / 255.
activ = tf.nn.relu
h = activ(conv(scaled_images, 'c1', nf=32, rf=8, stride=4, init_scale=np.sqrt(2),
**conv_kwargs))
h2 = activ(conv(h... | [
"CNN",
"from",
"Nature",
"paper",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/models.py#L16-L27 | [
"def",
"nature_cnn",
"(",
"unscaled_images",
",",
"*",
"*",
"conv_kwargs",
")",
":",
"scaled_images",
"=",
"tf",
".",
"cast",
"(",
"unscaled_images",
",",
"tf",
".",
"float32",
")",
"/",
"255.",
"activ",
"=",
"tf",
".",
"nn",
".",
"relu",
"h",
"=",
"... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | mlp | Stack of fully-connected layers to be used in a policy / q-function approximator
Parameters:
----------
num_layers: int number of fully-connected layers (default: 2)
num_hidden: int size of fully-connected layers (default: 64)
activation: activ... | baselines/common/models.py | def mlp(num_layers=2, num_hidden=64, activation=tf.tanh, layer_norm=False):
"""
Stack of fully-connected layers to be used in a policy / q-function approximator
Parameters:
----------
num_layers: int number of fully-connected layers (default: 2)
num_hidden: int ... | def mlp(num_layers=2, num_hidden=64, activation=tf.tanh, layer_norm=False):
"""
Stack of fully-connected layers to be used in a policy / q-function approximator
Parameters:
----------
num_layers: int number of fully-connected layers (default: 2)
num_hidden: int ... | [
"Stack",
"of",
"fully",
"-",
"connected",
"layers",
"to",
"be",
"used",
"in",
"a",
"policy",
"/",
"q",
"-",
"function",
"approximator"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/models.py#L31-L59 | [
"def",
"mlp",
"(",
"num_layers",
"=",
"2",
",",
"num_hidden",
"=",
"64",
",",
"activation",
"=",
"tf",
".",
"tanh",
",",
"layer_norm",
"=",
"False",
")",
":",
"def",
"network_fn",
"(",
"X",
")",
":",
"h",
"=",
"tf",
".",
"layers",
".",
"flatten",
... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | lstm | Builds LSTM (Long-Short Term Memory) network to be used in a policy.
Note that the resulting function returns not only the output of the LSTM
(i.e. hidden state of lstm for each step in the sequence), but also a dictionary
with auxiliary tensors to be set as policy attributes.
Specifically,
S i... | baselines/common/models.py | def lstm(nlstm=128, layer_norm=False):
"""
Builds LSTM (Long-Short Term Memory) network to be used in a policy.
Note that the resulting function returns not only the output of the LSTM
(i.e. hidden state of lstm for each step in the sequence), but also a dictionary
with auxiliary tensors to be set a... | def lstm(nlstm=128, layer_norm=False):
"""
Builds LSTM (Long-Short Term Memory) network to be used in a policy.
Note that the resulting function returns not only the output of the LSTM
(i.e. hidden state of lstm for each step in the sequence), but also a dictionary
with auxiliary tensors to be set a... | [
"Builds",
"LSTM",
"(",
"Long",
"-",
"Short",
"Term",
"Memory",
")",
"network",
"to",
"be",
"used",
"in",
"a",
"policy",
".",
"Note",
"that",
"the",
"resulting",
"function",
"returns",
"not",
"only",
"the",
"output",
"of",
"the",
"LSTM",
"(",
"i",
".",
... | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/models.py#L84-L135 | [
"def",
"lstm",
"(",
"nlstm",
"=",
"128",
",",
"layer_norm",
"=",
"False",
")",
":",
"def",
"network_fn",
"(",
"X",
",",
"nenv",
"=",
"1",
")",
":",
"nbatch",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"nsteps",
"=",
"nbatch",
"//",
"nenv",
"h",
"="... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | conv_only | convolutions-only net
Parameters:
----------
conv: list of triples (filter_number, filter_size, stride) specifying parameters for each layer.
Returns:
function that takes tensorflow tensor as input and returns the output of the last convolutional layer | baselines/common/models.py | def conv_only(convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)], **conv_kwargs):
'''
convolutions-only net
Parameters:
----------
conv: list of triples (filter_number, filter_size, stride) specifying parameters for each layer.
Returns:
function that takes tensorflow tensor as input and re... | def conv_only(convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)], **conv_kwargs):
'''
convolutions-only net
Parameters:
----------
conv: list of triples (filter_number, filter_size, stride) specifying parameters for each layer.
Returns:
function that takes tensorflow tensor as input and re... | [
"convolutions",
"-",
"only",
"net"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/models.py#L171-L198 | [
"def",
"conv_only",
"(",
"convs",
"=",
"[",
"(",
"32",
",",
"8",
",",
"4",
")",
",",
"(",
"64",
",",
"4",
",",
"2",
")",
",",
"(",
"64",
",",
"3",
",",
"1",
")",
"]",
",",
"*",
"*",
"conv_kwargs",
")",
":",
"def",
"network_fn",
"(",
"X",
... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | get_network_builder | If you want to register your own network outside models.py, you just need:
Usage Example:
-------------
from baselines.common.models import register
@register("your_network_name")
def your_network_define(**net_kwargs):
...
return network_fn | baselines/common/models.py | def get_network_builder(name):
"""
If you want to register your own network outside models.py, you just need:
Usage Example:
-------------
from baselines.common.models import register
@register("your_network_name")
def your_network_define(**net_kwargs):
...
return network_fn... | def get_network_builder(name):
"""
If you want to register your own network outside models.py, you just need:
Usage Example:
-------------
from baselines.common.models import register
@register("your_network_name")
def your_network_define(**net_kwargs):
...
return network_fn... | [
"If",
"you",
"want",
"to",
"register",
"your",
"own",
"network",
"outside",
"models",
".",
"py",
"you",
"just",
"need",
":"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/models.py#L206-L224 | [
"def",
"get_network_builder",
"(",
"name",
")",
":",
"if",
"callable",
"(",
"name",
")",
":",
"return",
"name",
"elif",
"name",
"in",
"mapping",
":",
"return",
"mapping",
"[",
"name",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown network type: {}'"... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | mlp | This model takes as input an observation and returns values of all actions.
Parameters
----------
hiddens: [int]
list of sizes of hidden layers
layer_norm: bool
if true applies layer normalization for every layer
as described in https://arxiv.org/abs/1607.06450
Returns
... | baselines/deepq/models.py | def mlp(hiddens=[], layer_norm=False):
"""This model takes as input an observation and returns values of all actions.
Parameters
----------
hiddens: [int]
list of sizes of hidden layers
layer_norm: bool
if true applies layer normalization for every layer
as described in http... | def mlp(hiddens=[], layer_norm=False):
"""This model takes as input an observation and returns values of all actions.
Parameters
----------
hiddens: [int]
list of sizes of hidden layers
layer_norm: bool
if true applies layer normalization for every layer
as described in http... | [
"This",
"model",
"takes",
"as",
"input",
"an",
"observation",
"and",
"returns",
"values",
"of",
"all",
"actions",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/deepq/models.py#L17-L33 | [
"def",
"mlp",
"(",
"hiddens",
"=",
"[",
"]",
",",
"layer_norm",
"=",
"False",
")",
":",
"return",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"_mlp",
"(",
"hiddens",
",",
"layer_norm",
"=",
"layer_norm",
",",
"*",
"args",
",",
"*",
"*",
... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | cnn_to_mlp | This model takes as input an observation and returns values of all actions.
Parameters
----------
convs: [(int, int, int)]
list of convolutional layers in form of
(num_outputs, kernel_size, stride)
hiddens: [int]
list of sizes of hidden layers
dueling: bool
if true d... | baselines/deepq/models.py | def cnn_to_mlp(convs, hiddens, dueling=False, layer_norm=False):
"""This model takes as input an observation and returns values of all actions.
Parameters
----------
convs: [(int, int, int)]
list of convolutional layers in form of
(num_outputs, kernel_size, stride)
hiddens: [int]
... | def cnn_to_mlp(convs, hiddens, dueling=False, layer_norm=False):
"""This model takes as input an observation and returns values of all actions.
Parameters
----------
convs: [(int, int, int)]
list of convolutional layers in form of
(num_outputs, kernel_size, stride)
hiddens: [int]
... | [
"This",
"model",
"takes",
"as",
"input",
"an",
"observation",
"and",
"returns",
"values",
"of",
"all",
"actions",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/deepq/models.py#L73-L96 | [
"def",
"cnn_to_mlp",
"(",
"convs",
",",
"hiddens",
",",
"dueling",
"=",
"False",
",",
"layer_norm",
"=",
"False",
")",
":",
"return",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"_cnn_to_mlp",
"(",
"convs",
",",
"hiddens",
",",
"dueling",
",",... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | make_vec_env | Create a wrapped, monitored SubprocVecEnv for Atari and MuJoCo. | baselines/common/cmd_util.py | def make_vec_env(env_id, env_type, num_env, seed,
wrapper_kwargs=None,
start_index=0,
reward_scale=1.0,
flatten_dict_observations=True,
gamestate=None):
"""
Create a wrapped, monitored SubprocVecEnv for Atari and MuJoCo.
""... | def make_vec_env(env_id, env_type, num_env, seed,
wrapper_kwargs=None,
start_index=0,
reward_scale=1.0,
flatten_dict_observations=True,
gamestate=None):
"""
Create a wrapped, monitored SubprocVecEnv for Atari and MuJoCo.
""... | [
"Create",
"a",
"wrapped",
"monitored",
"SubprocVecEnv",
"for",
"Atari",
"and",
"MuJoCo",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/cmd_util.py#L21-L52 | [
"def",
"make_vec_env",
"(",
"env_id",
",",
"env_type",
",",
"num_env",
",",
"seed",
",",
"wrapper_kwargs",
"=",
"None",
",",
"start_index",
"=",
"0",
",",
"reward_scale",
"=",
"1.0",
",",
"flatten_dict_observations",
"=",
"True",
",",
"gamestate",
"=",
"None... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | make_mujoco_env | Create a wrapped, monitored gym.Env for MuJoCo. | baselines/common/cmd_util.py | def make_mujoco_env(env_id, seed, reward_scale=1.0):
"""
Create a wrapped, monitored gym.Env for MuJoCo.
"""
rank = MPI.COMM_WORLD.Get_rank()
myseed = seed + 1000 * rank if seed is not None else None
set_global_seeds(myseed)
env = gym.make(env_id)
logger_path = None if logger.get_dir() ... | def make_mujoco_env(env_id, seed, reward_scale=1.0):
"""
Create a wrapped, monitored gym.Env for MuJoCo.
"""
rank = MPI.COMM_WORLD.Get_rank()
myseed = seed + 1000 * rank if seed is not None else None
set_global_seeds(myseed)
env = gym.make(env_id)
logger_path = None if logger.get_dir() ... | [
"Create",
"a",
"wrapped",
"monitored",
"gym",
".",
"Env",
"for",
"MuJoCo",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/cmd_util.py#L88-L102 | [
"def",
"make_mujoco_env",
"(",
"env_id",
",",
"seed",
",",
"reward_scale",
"=",
"1.0",
")",
":",
"rank",
"=",
"MPI",
".",
"COMM_WORLD",
".",
"Get_rank",
"(",
")",
"myseed",
"=",
"seed",
"+",
"1000",
"*",
"rank",
"if",
"seed",
"is",
"not",
"None",
"el... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | make_robotics_env | Create a wrapped, monitored gym.Env for MuJoCo. | baselines/common/cmd_util.py | def make_robotics_env(env_id, seed, rank=0):
"""
Create a wrapped, monitored gym.Env for MuJoCo.
"""
set_global_seeds(seed)
env = gym.make(env_id)
env = FlattenDictWrapper(env, ['observation', 'desired_goal'])
env = Monitor(
env, logger.get_dir() and os.path.join(logger.get_dir(), st... | def make_robotics_env(env_id, seed, rank=0):
"""
Create a wrapped, monitored gym.Env for MuJoCo.
"""
set_global_seeds(seed)
env = gym.make(env_id)
env = FlattenDictWrapper(env, ['observation', 'desired_goal'])
env = Monitor(
env, logger.get_dir() and os.path.join(logger.get_dir(), st... | [
"Create",
"a",
"wrapped",
"monitored",
"gym",
".",
"Env",
"for",
"MuJoCo",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/cmd_util.py#L104-L115 | [
"def",
"make_robotics_env",
"(",
"env_id",
",",
"seed",
",",
"rank",
"=",
"0",
")",
":",
"set_global_seeds",
"(",
"seed",
")",
"env",
"=",
"gym",
".",
"make",
"(",
"env_id",
")",
"env",
"=",
"FlattenDictWrapper",
"(",
"env",
",",
"[",
"'observation'",
... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | common_arg_parser | Create an argparse.ArgumentParser for run_mujoco.py. | baselines/common/cmd_util.py | def common_arg_parser():
"""
Create an argparse.ArgumentParser for run_mujoco.py.
"""
parser = arg_parser()
parser.add_argument('--env', help='environment ID', type=str, default='Reacher-v2')
parser.add_argument('--env_type', help='type of environment, used when the environment type cannot be au... | def common_arg_parser():
"""
Create an argparse.ArgumentParser for run_mujoco.py.
"""
parser = arg_parser()
parser.add_argument('--env', help='environment ID', type=str, default='Reacher-v2')
parser.add_argument('--env_type', help='type of environment, used when the environment type cannot be au... | [
"Create",
"an",
"argparse",
".",
"ArgumentParser",
"for",
"run_mujoco",
".",
"py",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/cmd_util.py#L135-L153 | [
"def",
"common_arg_parser",
"(",
")",
":",
"parser",
"=",
"arg_parser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--env'",
",",
"help",
"=",
"'environment ID'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'Reacher-v2'",
")",
"parser",
".",
"add_ar... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | robotics_arg_parser | Create an argparse.ArgumentParser for run_mujoco.py. | baselines/common/cmd_util.py | def robotics_arg_parser():
"""
Create an argparse.ArgumentParser for run_mujoco.py.
"""
parser = arg_parser()
parser.add_argument('--env', help='environment ID', type=str, default='FetchReach-v0')
parser.add_argument('--seed', help='RNG seed', type=int, default=None)
parser.add_argument('--n... | def robotics_arg_parser():
"""
Create an argparse.ArgumentParser for run_mujoco.py.
"""
parser = arg_parser()
parser.add_argument('--env', help='environment ID', type=str, default='FetchReach-v0')
parser.add_argument('--seed', help='RNG seed', type=int, default=None)
parser.add_argument('--n... | [
"Create",
"an",
"argparse",
".",
"ArgumentParser",
"for",
"run_mujoco",
".",
"py",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/cmd_util.py#L155-L163 | [
"def",
"robotics_arg_parser",
"(",
")",
":",
"parser",
"=",
"arg_parser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--env'",
",",
"help",
"=",
"'environment ID'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'FetchReach-v0'",
")",
"parser",
".",
"a... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | parse_unknown_args | Parse arguments not consumed by arg parser into a dicitonary | baselines/common/cmd_util.py | def parse_unknown_args(args):
"""
Parse arguments not consumed by arg parser into a dicitonary
"""
retval = {}
preceded_by_key = False
for arg in args:
if arg.startswith('--'):
if '=' in arg:
key = arg.split('=')[0][2:]
value = arg.split('=')[1... | def parse_unknown_args(args):
"""
Parse arguments not consumed by arg parser into a dicitonary
"""
retval = {}
preceded_by_key = False
for arg in args:
if arg.startswith('--'):
if '=' in arg:
key = arg.split('=')[0][2:]
value = arg.split('=')[1... | [
"Parse",
"arguments",
"not",
"consumed",
"by",
"arg",
"parser",
"into",
"a",
"dicitonary"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/cmd_util.py#L166-L185 | [
"def",
"parse_unknown_args",
"(",
"args",
")",
":",
"retval",
"=",
"{",
"}",
"preceded_by_key",
"=",
"False",
"for",
"arg",
"in",
"args",
":",
"if",
"arg",
".",
"startswith",
"(",
"'--'",
")",
":",
"if",
"'='",
"in",
"arg",
":",
"key",
"=",
"arg",
... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | clear_mpi_env_vars | from mpi4py import MPI will call MPI_Init by default. If the child process has MPI environment variables, MPI will think that the child process is an MPI process just like the parent and do bad things such as hang.
This context manager is a hacky way to clear those environment variables temporarily such as when we... | baselines/common/vec_env/vec_env.py | def clear_mpi_env_vars():
"""
from mpi4py import MPI will call MPI_Init by default. If the child process has MPI environment variables, MPI will think that the child process is an MPI process just like the parent and do bad things such as hang.
This context manager is a hacky way to clear those environment... | def clear_mpi_env_vars():
"""
from mpi4py import MPI will call MPI_Init by default. If the child process has MPI environment variables, MPI will think that the child process is an MPI process just like the parent and do bad things such as hang.
This context manager is a hacky way to clear those environment... | [
"from",
"mpi4py",
"import",
"MPI",
"will",
"call",
"MPI_Init",
"by",
"default",
".",
"If",
"the",
"child",
"process",
"has",
"MPI",
"environment",
"variables",
"MPI",
"will",
"think",
"that",
"the",
"child",
"process",
"is",
"an",
"MPI",
"process",
"just",
... | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/vec_env/vec_env.py#L204-L219 | [
"def",
"clear_mpi_env_vars",
"(",
")",
":",
"removed_environment",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"os",
".",
"environ",
".",
"items",
"(",
")",
")",
":",
"for",
"prefix",
"in",
"[",
"'OMPI_'",
",",
"'PMI_'",
"]",
":",
"if",... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | learn | Learn policy using PPO algorithm (https://arxiv.org/abs/1707.06347)
Parameters:
----------
network: policy network architecture. Either string (mlp, lstm, lnlstm, cnn_lstm, cnn, cnn_small, conv_only - see baselines.common/models.py for full list)
... | baselines/ppo2/ppo2.py | def learn(*, network, env, total_timesteps, eval_env = None, seed=None, nsteps=2048, ent_coef=0.0, lr=3e-4,
vf_coef=0.5, max_grad_norm=0.5, gamma=0.99, lam=0.95,
log_interval=10, nminibatches=4, noptepochs=4, cliprange=0.2,
save_interval=0, load_path=None, model_fn=None, **network_k... | def learn(*, network, env, total_timesteps, eval_env = None, seed=None, nsteps=2048, ent_coef=0.0, lr=3e-4,
vf_coef=0.5, max_grad_norm=0.5, gamma=0.99, lam=0.95,
log_interval=10, nminibatches=4, noptepochs=4, cliprange=0.2,
save_interval=0, load_path=None, model_fn=None, **network_k... | [
"Learn",
"policy",
"using",
"PPO",
"algorithm",
"(",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1707",
".",
"06347",
")"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/ppo2/ppo2.py#L21-L204 | [
"def",
"learn",
"(",
"*",
",",
"network",
",",
"env",
",",
"total_timesteps",
",",
"eval_env",
"=",
"None",
",",
"seed",
"=",
"None",
",",
"nsteps",
"=",
"2048",
",",
"ent_coef",
"=",
"0.0",
",",
"lr",
"=",
"3e-4",
",",
"vf_coef",
"=",
"0.5",
",",
... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | cg | Demmel p 312 | baselines/common/cg.py | def cg(f_Ax, b, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10):
"""
Demmel p 312
"""
p = b.copy()
r = b.copy()
x = np.zeros_like(b)
rdotr = r.dot(r)
fmtstr = "%10i %10.3g %10.3g"
titlestr = "%10s %10s %10s"
if verbose: print(titlestr % ("iter", "residual norm",... | def cg(f_Ax, b, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10):
"""
Demmel p 312
"""
p = b.copy()
r = b.copy()
x = np.zeros_like(b)
rdotr = r.dot(r)
fmtstr = "%10i %10.3g %10.3g"
titlestr = "%10s %10s %10s"
if verbose: print(titlestr % ("iter", "residual norm",... | [
"Demmel",
"p",
"312"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/cg.py#L2-L34 | [
"def",
"cg",
"(",
"f_Ax",
",",
"b",
",",
"cg_iters",
"=",
"10",
",",
"callback",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"residual_tol",
"=",
"1e-10",
")",
":",
"p",
"=",
"b",
".",
"copy",
"(",
")",
"r",
"=",
"b",
".",
"copy",
"(",
")... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | observation_placeholder | Create placeholder to feed observations into of the size appropriate to the observation space
Parameters:
----------
ob_space: gym.Space observation space
batch_size: int size of the batch to be fed into input. Can be left None in most cases.
name: str name of the place... | baselines/common/input.py | def observation_placeholder(ob_space, batch_size=None, name='Ob'):
'''
Create placeholder to feed observations into of the size appropriate to the observation space
Parameters:
----------
ob_space: gym.Space observation space
batch_size: int size of the batch to be fed into input.... | def observation_placeholder(ob_space, batch_size=None, name='Ob'):
'''
Create placeholder to feed observations into of the size appropriate to the observation space
Parameters:
----------
ob_space: gym.Space observation space
batch_size: int size of the batch to be fed into input.... | [
"Create",
"placeholder",
"to",
"feed",
"observations",
"into",
"of",
"the",
"size",
"appropriate",
"to",
"the",
"observation",
"space"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/input.py#L5-L31 | [
"def",
"observation_placeholder",
"(",
"ob_space",
",",
"batch_size",
"=",
"None",
",",
"name",
"=",
"'Ob'",
")",
":",
"assert",
"isinstance",
"(",
"ob_space",
",",
"Discrete",
")",
"or",
"isinstance",
"(",
"ob_space",
",",
"Box",
")",
"or",
"isinstance",
... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | observation_input | Create placeholder to feed observations into of the size appropriate to the observation space, and add input
encoder of the appropriate type. | baselines/common/input.py | def observation_input(ob_space, batch_size=None, name='Ob'):
'''
Create placeholder to feed observations into of the size appropriate to the observation space, and add input
encoder of the appropriate type.
'''
placeholder = observation_placeholder(ob_space, batch_size, name)
return placeholder... | def observation_input(ob_space, batch_size=None, name='Ob'):
'''
Create placeholder to feed observations into of the size appropriate to the observation space, and add input
encoder of the appropriate type.
'''
placeholder = observation_placeholder(ob_space, batch_size, name)
return placeholder... | [
"Create",
"placeholder",
"to",
"feed",
"observations",
"into",
"of",
"the",
"size",
"appropriate",
"to",
"the",
"observation",
"space",
"and",
"add",
"input",
"encoder",
"of",
"the",
"appropriate",
"type",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/input.py#L34-L41 | [
"def",
"observation_input",
"(",
"ob_space",
",",
"batch_size",
"=",
"None",
",",
"name",
"=",
"'Ob'",
")",
":",
"placeholder",
"=",
"observation_placeholder",
"(",
"ob_space",
",",
"batch_size",
",",
"name",
")",
"return",
"placeholder",
",",
"encode_observatio... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | encode_observation | Encode input in the way that is appropriate to the observation space
Parameters:
----------
ob_space: gym.Space observation space
placeholder: tf.placeholder observation input placeholder | baselines/common/input.py | def encode_observation(ob_space, placeholder):
'''
Encode input in the way that is appropriate to the observation space
Parameters:
----------
ob_space: gym.Space observation space
placeholder: tf.placeholder observation input placeholder
'''
if isinstance(ob_space, Di... | def encode_observation(ob_space, placeholder):
'''
Encode input in the way that is appropriate to the observation space
Parameters:
----------
ob_space: gym.Space observation space
placeholder: tf.placeholder observation input placeholder
'''
if isinstance(ob_space, Di... | [
"Encode",
"input",
"in",
"the",
"way",
"that",
"is",
"appropriate",
"to",
"the",
"observation",
"space"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/input.py#L43-L63 | [
"def",
"encode_observation",
"(",
"ob_space",
",",
"placeholder",
")",
":",
"if",
"isinstance",
"(",
"ob_space",
",",
"Discrete",
")",
":",
"return",
"tf",
".",
"to_float",
"(",
"tf",
".",
"one_hot",
"(",
"placeholder",
",",
"ob_space",
".",
"n",
")",
")... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | RolloutWorker.generate_rollouts | Performs `rollout_batch_size` rollouts in parallel for time horizon `T` with the current
policy acting on it accordingly. | baselines/her/rollout.py | def generate_rollouts(self):
"""Performs `rollout_batch_size` rollouts in parallel for time horizon `T` with the current
policy acting on it accordingly.
"""
self.reset_all_rollouts()
# compute observations
o = np.empty((self.rollout_batch_size, self.dims['o']), np.float... | def generate_rollouts(self):
"""Performs `rollout_batch_size` rollouts in parallel for time horizon `T` with the current
policy acting on it accordingly.
"""
self.reset_all_rollouts()
# compute observations
o = np.empty((self.rollout_batch_size, self.dims['o']), np.float... | [
"Performs",
"rollout_batch_size",
"rollouts",
"in",
"parallel",
"for",
"time",
"horizon",
"T",
"with",
"the",
"current",
"policy",
"acting",
"on",
"it",
"accordingly",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/her/rollout.py#L51-L137 | [
"def",
"generate_rollouts",
"(",
"self",
")",
":",
"self",
".",
"reset_all_rollouts",
"(",
")",
"# compute observations",
"o",
"=",
"np",
".",
"empty",
"(",
"(",
"self",
".",
"rollout_batch_size",
",",
"self",
".",
"dims",
"[",
"'o'",
"]",
")",
",",
"np"... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | RolloutWorker.save_policy | Pickles the current policy for later inspection. | baselines/her/rollout.py | def save_policy(self, path):
"""Pickles the current policy for later inspection.
"""
with open(path, 'wb') as f:
pickle.dump(self.policy, f) | def save_policy(self, path):
"""Pickles the current policy for later inspection.
"""
with open(path, 'wb') as f:
pickle.dump(self.policy, f) | [
"Pickles",
"the",
"current",
"policy",
"for",
"later",
"inspection",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/her/rollout.py#L151-L155 | [
"def",
"save_policy",
"(",
"self",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"f",
":",
"pickle",
".",
"dump",
"(",
"self",
".",
"policy",
",",
"f",
")"
] | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | RolloutWorker.logs | Generates a dictionary that contains all collected statistics. | baselines/her/rollout.py | def logs(self, prefix='worker'):
"""Generates a dictionary that contains all collected statistics.
"""
logs = []
logs += [('success_rate', np.mean(self.success_history))]
if self.compute_Q:
logs += [('mean_Q', np.mean(self.Q_history))]
logs += [('episode', sel... | def logs(self, prefix='worker'):
"""Generates a dictionary that contains all collected statistics.
"""
logs = []
logs += [('success_rate', np.mean(self.success_history))]
if self.compute_Q:
logs += [('mean_Q', np.mean(self.Q_history))]
logs += [('episode', sel... | [
"Generates",
"a",
"dictionary",
"that",
"contains",
"all",
"collected",
"statistics",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/her/rollout.py#L157-L169 | [
"def",
"logs",
"(",
"self",
",",
"prefix",
"=",
"'worker'",
")",
":",
"logs",
"=",
"[",
"]",
"logs",
"+=",
"[",
"(",
"'success_rate'",
",",
"np",
".",
"mean",
"(",
"self",
".",
"success_history",
")",
")",
"]",
"if",
"self",
".",
"compute_Q",
":",
... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | smooth | Smooth signal y, where radius is determines the size of the window
mode='twosided':
average over the window [max(index - radius, 0), min(index + radius, len(y)-1)]
mode='causal':
average over the window [max(index - radius, 0), index]
valid_only: put nan in entries where the full-sized win... | baselines/common/plot_util.py | def smooth(y, radius, mode='two_sided', valid_only=False):
'''
Smooth signal y, where radius is determines the size of the window
mode='twosided':
average over the window [max(index - radius, 0), min(index + radius, len(y)-1)]
mode='causal':
average over the window [max(index - radius, ... | def smooth(y, radius, mode='two_sided', valid_only=False):
'''
Smooth signal y, where radius is determines the size of the window
mode='twosided':
average over the window [max(index - radius, 0), min(index + radius, len(y)-1)]
mode='causal':
average over the window [max(index - radius, ... | [
"Smooth",
"signal",
"y",
"where",
"radius",
"is",
"determines",
"the",
"size",
"of",
"the",
"window"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/plot_util.py#L11-L37 | [
"def",
"smooth",
"(",
"y",
",",
"radius",
",",
"mode",
"=",
"'two_sided'",
",",
"valid_only",
"=",
"False",
")",
":",
"assert",
"mode",
"in",
"(",
"'two_sided'",
",",
"'causal'",
")",
"if",
"len",
"(",
"y",
")",
"<",
"2",
"*",
"radius",
"+",
"1",
... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | one_sided_ema | perform one-sided (causal) EMA (exponential moving average)
smoothing and resampling to an even grid with n points.
Does not do extrapolation, so we assume
xolds[0] <= low && high <= xolds[-1]
Arguments:
xolds: array or list - x values of data. Needs to be sorted in ascending order
yolds: arr... | baselines/common/plot_util.py | def one_sided_ema(xolds, yolds, low=None, high=None, n=512, decay_steps=1., low_counts_threshold=1e-8):
'''
perform one-sided (causal) EMA (exponential moving average)
smoothing and resampling to an even grid with n points.
Does not do extrapolation, so we assume
xolds[0] <= low && high <= xolds[-1]... | def one_sided_ema(xolds, yolds, low=None, high=None, n=512, decay_steps=1., low_counts_threshold=1e-8):
'''
perform one-sided (causal) EMA (exponential moving average)
smoothing and resampling to an even grid with n points.
Does not do extrapolation, so we assume
xolds[0] <= low && high <= xolds[-1]... | [
"perform",
"one",
"-",
"sided",
"(",
"causal",
")",
"EMA",
"(",
"exponential",
"moving",
"average",
")",
"smoothing",
"and",
"resampling",
"to",
"an",
"even",
"grid",
"with",
"n",
"points",
".",
"Does",
"not",
"do",
"extrapolation",
"so",
"we",
"assume",
... | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/plot_util.py#L39-L109 | [
"def",
"one_sided_ema",
"(",
"xolds",
",",
"yolds",
",",
"low",
"=",
"None",
",",
"high",
"=",
"None",
",",
"n",
"=",
"512",
",",
"decay_steps",
"=",
"1.",
",",
"low_counts_threshold",
"=",
"1e-8",
")",
":",
"low",
"=",
"xolds",
"[",
"0",
"]",
"if"... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | symmetric_ema | perform symmetric EMA (exponential moving average)
smoothing and resampling to an even grid with n points.
Does not do extrapolation, so we assume
xolds[0] <= low && high <= xolds[-1]
Arguments:
xolds: array or list - x values of data. Needs to be sorted in ascending order
yolds: array of lis... | baselines/common/plot_util.py | def symmetric_ema(xolds, yolds, low=None, high=None, n=512, decay_steps=1., low_counts_threshold=1e-8):
'''
perform symmetric EMA (exponential moving average)
smoothing and resampling to an even grid with n points.
Does not do extrapolation, so we assume
xolds[0] <= low && high <= xolds[-1]
Arg... | def symmetric_ema(xolds, yolds, low=None, high=None, n=512, decay_steps=1., low_counts_threshold=1e-8):
'''
perform symmetric EMA (exponential moving average)
smoothing and resampling to an even grid with n points.
Does not do extrapolation, so we assume
xolds[0] <= low && high <= xolds[-1]
Arg... | [
"perform",
"symmetric",
"EMA",
"(",
"exponential",
"moving",
"average",
")",
"smoothing",
"and",
"resampling",
"to",
"an",
"even",
"grid",
"with",
"n",
"points",
".",
"Does",
"not",
"do",
"extrapolation",
"so",
"we",
"assume",
"xolds",
"[",
"0",
"]",
"<",
... | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/plot_util.py#L111-L147 | [
"def",
"symmetric_ema",
"(",
"xolds",
",",
"yolds",
",",
"low",
"=",
"None",
",",
"high",
"=",
"None",
",",
"n",
"=",
"512",
",",
"decay_steps",
"=",
"1.",
",",
"low_counts_threshold",
"=",
"1e-8",
")",
":",
"xs",
",",
"ys1",
",",
"count_ys1",
"=",
... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | load_results | load summaries of runs from a list of directories (including subdirectories)
Arguments:
enable_progress: bool - if True, will attempt to load data from progress.csv files (data saved by logger). Default: True
enable_monitor: bool - if True, will attempt to load data from monitor.csv files (data saved by M... | baselines/common/plot_util.py | def load_results(root_dir_or_dirs, enable_progress=True, enable_monitor=True, verbose=False):
'''
load summaries of runs from a list of directories (including subdirectories)
Arguments:
enable_progress: bool - if True, will attempt to load data from progress.csv files (data saved by logger). Default: T... | def load_results(root_dir_or_dirs, enable_progress=True, enable_monitor=True, verbose=False):
'''
load summaries of runs from a list of directories (including subdirectories)
Arguments:
enable_progress: bool - if True, will attempt to load data from progress.csv files (data saved by logger). Default: T... | [
"load",
"summaries",
"of",
"runs",
"from",
"a",
"list",
"of",
"directories",
"(",
"including",
"subdirectories",
")",
"Arguments",
":"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/plot_util.py#L152-L220 | [
"def",
"load_results",
"(",
"root_dir_or_dirs",
",",
"enable_progress",
"=",
"True",
",",
"enable_monitor",
"=",
"True",
",",
"verbose",
"=",
"False",
")",
":",
"import",
"re",
"if",
"isinstance",
"(",
"root_dir_or_dirs",
",",
"str",
")",
":",
"rootdirs",
"=... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | plot_results | Plot multiple Results objects
xy_fn: function Result -> x,y - function that converts results objects into tuple of x and y values.
By default, x is cumsum of episode lengths, and y is episode rewards
split_fn: function Result -> hashable - function tha... | baselines/common/plot_util.py | def plot_results(
allresults, *,
xy_fn=default_xy_fn,
split_fn=default_split_fn,
group_fn=default_split_fn,
average_group=False,
shaded_std=True,
shaded_err=True,
figsize=None,
legend_outside=False,
resample=0,
smooth_step=1.0
):
'''
Plot multiple Results objects
... | def plot_results(
allresults, *,
xy_fn=default_xy_fn,
split_fn=default_split_fn,
group_fn=default_split_fn,
average_group=False,
shaded_std=True,
shaded_err=True,
figsize=None,
legend_outside=False,
resample=0,
smooth_step=1.0
):
'''
Plot multiple Results objects
... | [
"Plot",
"multiple",
"Results",
"objects"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/plot_util.py#L240-L375 | [
"def",
"plot_results",
"(",
"allresults",
",",
"*",
",",
"xy_fn",
"=",
"default_xy_fn",
",",
"split_fn",
"=",
"default_split_fn",
",",
"group_fn",
"=",
"default_split_fn",
",",
"average_group",
"=",
"False",
",",
"shaded_std",
"=",
"True",
",",
"shaded_err",
"... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | check_synced | It's common to forget to initialize your variables to the same values, or
(less commonly) if you update them in some other way than adam, to get them out of sync.
This function checks that variables on all MPI workers are the same, and raises
an AssertionError otherwise
Arguments:
comm: MPI com... | baselines/common/mpi_adam_optimizer.py | def check_synced(localval, comm=None):
"""
It's common to forget to initialize your variables to the same values, or
(less commonly) if you update them in some other way than adam, to get them out of sync.
This function checks that variables on all MPI workers are the same, and raises
an AssertionEr... | def check_synced(localval, comm=None):
"""
It's common to forget to initialize your variables to the same values, or
(less commonly) if you update them in some other way than adam, to get them out of sync.
This function checks that variables on all MPI workers are the same, and raises
an AssertionEr... | [
"It",
"s",
"common",
"to",
"forget",
"to",
"initialize",
"your",
"variables",
"to",
"the",
"same",
"values",
"or",
"(",
"less",
"commonly",
")",
"if",
"you",
"update",
"them",
"in",
"some",
"other",
"way",
"than",
"adam",
"to",
"get",
"them",
"out",
"o... | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/mpi_adam_optimizer.py#L40-L54 | [
"def",
"check_synced",
"(",
"localval",
",",
"comm",
"=",
"None",
")",
":",
"comm",
"=",
"comm",
"or",
"MPI",
".",
"COMM_WORLD",
"vals",
"=",
"comm",
".",
"gather",
"(",
"localval",
")",
"if",
"comm",
".",
"rank",
"==",
"0",
":",
"assert",
"all",
"... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | copy_obs_dict | Deep-copy an observation dict. | baselines/common/vec_env/util.py | def copy_obs_dict(obs):
"""
Deep-copy an observation dict.
"""
return {k: np.copy(v) for k, v in obs.items()} | def copy_obs_dict(obs):
"""
Deep-copy an observation dict.
"""
return {k: np.copy(v) for k, v in obs.items()} | [
"Deep",
"-",
"copy",
"an",
"observation",
"dict",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/vec_env/util.py#L11-L15 | [
"def",
"copy_obs_dict",
"(",
"obs",
")",
":",
"return",
"{",
"k",
":",
"np",
".",
"copy",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"obs",
".",
"items",
"(",
")",
"}"
] | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | obs_space_info | Get dict-structured information about a gym.Space.
Returns:
A tuple (keys, shapes, dtypes):
keys: a list of dict keys.
shapes: a dict mapping keys to shapes.
dtypes: a dict mapping keys to dtypes. | baselines/common/vec_env/util.py | def obs_space_info(obs_space):
"""
Get dict-structured information about a gym.Space.
Returns:
A tuple (keys, shapes, dtypes):
keys: a list of dict keys.
shapes: a dict mapping keys to shapes.
dtypes: a dict mapping keys to dtypes.
"""
if isinstance(obs_space, gym.spac... | def obs_space_info(obs_space):
"""
Get dict-structured information about a gym.Space.
Returns:
A tuple (keys, shapes, dtypes):
keys: a list of dict keys.
shapes: a dict mapping keys to shapes.
dtypes: a dict mapping keys to dtypes.
"""
if isinstance(obs_space, gym.spac... | [
"Get",
"dict",
"-",
"structured",
"information",
"about",
"a",
"gym",
".",
"Space",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/vec_env/util.py#L28-L50 | [
"def",
"obs_space_info",
"(",
"obs_space",
")",
":",
"if",
"isinstance",
"(",
"obs_space",
",",
"gym",
".",
"spaces",
".",
"Dict",
")",
":",
"assert",
"isinstance",
"(",
"obs_space",
".",
"spaces",
",",
"OrderedDict",
")",
"subspaces",
"=",
"obs_space",
".... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | q_retrace | Calculates q_retrace targets
:param R: Rewards
:param D: Dones
:param q_i: Q values for actions taken
:param v: V values
:param rho_i: Importance weight for each action
:return: Q_retrace values | baselines/acer/acer.py | def q_retrace(R, D, q_i, v, rho_i, nenvs, nsteps, gamma):
"""
Calculates q_retrace targets
:param R: Rewards
:param D: Dones
:param q_i: Q values for actions taken
:param v: V values
:param rho_i: Importance weight for each action
:return: Q_retrace values
"""
rho_bar = batch_to... | def q_retrace(R, D, q_i, v, rho_i, nenvs, nsteps, gamma):
"""
Calculates q_retrace targets
:param R: Rewards
:param D: Dones
:param q_i: Q values for actions taken
:param v: V values
:param rho_i: Importance weight for each action
:return: Q_retrace values
"""
rho_bar = batch_to... | [
"Calculates",
"q_retrace",
"targets"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/acer/acer.py#L25-L51 | [
"def",
"q_retrace",
"(",
"R",
",",
"D",
",",
"q_i",
",",
"v",
",",
"rho_i",
",",
"nenvs",
",",
"nsteps",
",",
"gamma",
")",
":",
"rho_bar",
"=",
"batch_to_seq",
"(",
"tf",
".",
"minimum",
"(",
"1.0",
",",
"rho_i",
")",
",",
"nenvs",
",",
"nsteps"... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | learn | Main entrypoint for ACER (Actor-Critic with Experience Replay) algorithm (https://arxiv.org/pdf/1611.01224.pdf)
Train an agent with given network architecture on a given environment using ACER.
Parameters:
----------
network: policy network architecture. Either string (mlp, lstm, lnlstm, cn... | baselines/acer/acer.py | def learn(network, env, seed=None, nsteps=20, total_timesteps=int(80e6), q_coef=0.5, ent_coef=0.01,
max_grad_norm=10, lr=7e-4, lrschedule='linear', rprop_epsilon=1e-5, rprop_alpha=0.99, gamma=0.99,
log_interval=100, buffer_size=50000, replay_ratio=4, replay_start=10000, c=10.0,
trust_regio... | def learn(network, env, seed=None, nsteps=20, total_timesteps=int(80e6), q_coef=0.5, ent_coef=0.01,
max_grad_norm=10, lr=7e-4, lrschedule='linear', rprop_epsilon=1e-5, rprop_alpha=0.99, gamma=0.99,
log_interval=100, buffer_size=50000, replay_ratio=4, replay_start=10000, c=10.0,
trust_regio... | [
"Main",
"entrypoint",
"for",
"ACER",
"(",
"Actor",
"-",
"Critic",
"with",
"Experience",
"Replay",
")",
"algorithm",
"(",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"1611",
".",
"01224",
".",
"pdf",
")",
"Train",
"an",
"agent",
"with",
... | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/acer/acer.py#L274-L377 | [
"def",
"learn",
"(",
"network",
",",
"env",
",",
"seed",
"=",
"None",
",",
"nsteps",
"=",
"20",
",",
"total_timesteps",
"=",
"int",
"(",
"80e6",
")",
",",
"q_coef",
"=",
"0.5",
",",
"ent_coef",
"=",
"0.01",
",",
"max_grad_norm",
"=",
"10",
",",
"lr... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | KfacOptimizer.apply_stats | compute stats and update/apply the new stats to the running average | baselines/acktr/kfac.py | def apply_stats(self, statsUpdates):
""" compute stats and update/apply the new stats to the running average
"""
def updateAccumStats():
if self._full_stats_init:
return tf.cond(tf.greater(self.sgd_step, self._cold_iter), lambda: tf.group(*self._apply_stats(statsUpda... | def apply_stats(self, statsUpdates):
""" compute stats and update/apply the new stats to the running average
"""
def updateAccumStats():
if self._full_stats_init:
return tf.cond(tf.greater(self.sgd_step, self._cold_iter), lambda: tf.group(*self._apply_stats(statsUpda... | [
"compute",
"stats",
"and",
"update",
"/",
"apply",
"the",
"new",
"stats",
"to",
"the",
"running",
"average"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/acktr/kfac.py#L440-L474 | [
"def",
"apply_stats",
"(",
"self",
",",
"statsUpdates",
")",
":",
"def",
"updateAccumStats",
"(",
")",
":",
"if",
"self",
".",
"_full_stats_init",
":",
"return",
"tf",
".",
"cond",
"(",
"tf",
".",
"greater",
"(",
"self",
".",
"sgd_step",
",",
"self",
"... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | tile_images | Tile N images into one big PxQ image
(P,Q) are chosen to be as close as possible, and if N
is square, then P=Q.
input: img_nhwc, list or array of images, ndim=4 once turned into array
n = batch index, h = height, w = width, c = channel
returns:
bigim_HWc, ndarray with ndim=3 | baselines/common/tile_images.py | def tile_images(img_nhwc):
"""
Tile N images into one big PxQ image
(P,Q) are chosen to be as close as possible, and if N
is square, then P=Q.
input: img_nhwc, list or array of images, ndim=4 once turned into array
n = batch index, h = height, w = width, c = channel
returns:
big... | def tile_images(img_nhwc):
"""
Tile N images into one big PxQ image
(P,Q) are chosen to be as close as possible, and if N
is square, then P=Q.
input: img_nhwc, list or array of images, ndim=4 once turned into array
n = batch index, h = height, w = width, c = channel
returns:
big... | [
"Tile",
"N",
"images",
"into",
"one",
"big",
"PxQ",
"image",
"(",
"P",
"Q",
")",
"are",
"chosen",
"to",
"be",
"as",
"close",
"as",
"possible",
"and",
"if",
"N",
"is",
"square",
"then",
"P",
"=",
"Q",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/tile_images.py#L3-L22 | [
"def",
"tile_images",
"(",
"img_nhwc",
")",
":",
"img_nhwc",
"=",
"np",
".",
"asarray",
"(",
"img_nhwc",
")",
"N",
",",
"h",
",",
"w",
",",
"c",
"=",
"img_nhwc",
".",
"shape",
"H",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"np",
".",
"sqrt",
"("... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | SumSegmentTree.sum | Returns arr[start] + ... + arr[end] | baselines/common/segment_tree.py | def sum(self, start=0, end=None):
"""Returns arr[start] + ... + arr[end]"""
return super(SumSegmentTree, self).reduce(start, end) | def sum(self, start=0, end=None):
"""Returns arr[start] + ... + arr[end]"""
return super(SumSegmentTree, self).reduce(start, end) | [
"Returns",
"arr",
"[",
"start",
"]",
"+",
"...",
"+",
"arr",
"[",
"end",
"]"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/segment_tree.py#L101-L103 | [
"def",
"sum",
"(",
"self",
",",
"start",
"=",
"0",
",",
"end",
"=",
"None",
")",
":",
"return",
"super",
"(",
"SumSegmentTree",
",",
"self",
")",
".",
"reduce",
"(",
"start",
",",
"end",
")"
] | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | SumSegmentTree.find_prefixsum_idx | Find the highest index `i` in the array such that
sum(arr[0] + arr[1] + ... + arr[i - i]) <= prefixsum
if array values are probabilities, this function
allows to sample indexes according to the discrete
probability efficiently.
Parameters
----------
perfixsu... | baselines/common/segment_tree.py | def find_prefixsum_idx(self, prefixsum):
"""Find the highest index `i` in the array such that
sum(arr[0] + arr[1] + ... + arr[i - i]) <= prefixsum
if array values are probabilities, this function
allows to sample indexes according to the discrete
probability efficiently.
... | def find_prefixsum_idx(self, prefixsum):
"""Find the highest index `i` in the array such that
sum(arr[0] + arr[1] + ... + arr[i - i]) <= prefixsum
if array values are probabilities, this function
allows to sample indexes according to the discrete
probability efficiently.
... | [
"Find",
"the",
"highest",
"index",
"i",
"in",
"the",
"array",
"such",
"that",
"sum",
"(",
"arr",
"[",
"0",
"]",
"+",
"arr",
"[",
"1",
"]",
"+",
"...",
"+",
"arr",
"[",
"i",
"-",
"i",
"]",
")",
"<",
"=",
"prefixsum"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/segment_tree.py#L105-L131 | [
"def",
"find_prefixsum_idx",
"(",
"self",
",",
"prefixsum",
")",
":",
"assert",
"0",
"<=",
"prefixsum",
"<=",
"self",
".",
"sum",
"(",
")",
"+",
"1e-5",
"idx",
"=",
"1",
"while",
"idx",
"<",
"self",
".",
"_capacity",
":",
"# while non-leaf",
"if",
"sel... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | MinSegmentTree.min | Returns min(arr[start], ..., arr[end]) | baselines/common/segment_tree.py | def min(self, start=0, end=None):
"""Returns min(arr[start], ..., arr[end])"""
return super(MinSegmentTree, self).reduce(start, end) | def min(self, start=0, end=None):
"""Returns min(arr[start], ..., arr[end])"""
return super(MinSegmentTree, self).reduce(start, end) | [
"Returns",
"min",
"(",
"arr",
"[",
"start",
"]",
"...",
"arr",
"[",
"end",
"]",
")"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/segment_tree.py#L142-L145 | [
"def",
"min",
"(",
"self",
",",
"start",
"=",
"0",
",",
"end",
"=",
"None",
")",
":",
"return",
"super",
"(",
"MinSegmentTree",
",",
"self",
")",
".",
"reduce",
"(",
"start",
",",
"end",
")"
] | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | PiecewiseSchedule.value | See Schedule.value | baselines/common/schedules.py | def value(self, t):
"""See Schedule.value"""
for (l_t, l), (r_t, r) in zip(self._endpoints[:-1], self._endpoints[1:]):
if l_t <= t and t < r_t:
alpha = float(t - l_t) / (r_t - l_t)
return self._interpolation(l, r, alpha)
# t does not belong to any of ... | def value(self, t):
"""See Schedule.value"""
for (l_t, l), (r_t, r) in zip(self._endpoints[:-1], self._endpoints[1:]):
if l_t <= t and t < r_t:
alpha = float(t - l_t) / (r_t - l_t)
return self._interpolation(l, r, alpha)
# t does not belong to any of ... | [
"See",
"Schedule",
".",
"value"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/schedules.py#L64-L73 | [
"def",
"value",
"(",
"self",
",",
"t",
")",
":",
"for",
"(",
"l_t",
",",
"l",
")",
",",
"(",
"r_t",
",",
"r",
")",
"in",
"zip",
"(",
"self",
".",
"_endpoints",
"[",
":",
"-",
"1",
"]",
",",
"self",
".",
"_endpoints",
"[",
"1",
":",
"]",
"... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | _subproc_worker | Control a single environment instance using IPC and
shared memory. | baselines/common/vec_env/shmem_vec_env.py | def _subproc_worker(pipe, parent_pipe, env_fn_wrapper, obs_bufs, obs_shapes, obs_dtypes, keys):
"""
Control a single environment instance using IPC and
shared memory.
"""
def _write_obs(maybe_dict_obs):
flatdict = obs_to_dict(maybe_dict_obs)
for k in keys:
dst = obs_bufs[... | def _subproc_worker(pipe, parent_pipe, env_fn_wrapper, obs_bufs, obs_shapes, obs_dtypes, keys):
"""
Control a single environment instance using IPC and
shared memory.
"""
def _write_obs(maybe_dict_obs):
flatdict = obs_to_dict(maybe_dict_obs)
for k in keys:
dst = obs_bufs[... | [
"Control",
"a",
"single",
"environment",
"instance",
"using",
"IPC",
"and",
"shared",
"memory",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/vec_env/shmem_vec_env.py#L105-L139 | [
"def",
"_subproc_worker",
"(",
"pipe",
",",
"parent_pipe",
",",
"env_fn_wrapper",
",",
"obs_bufs",
",",
"obs_shapes",
",",
"obs_dtypes",
",",
"keys",
")",
":",
"def",
"_write_obs",
"(",
"maybe_dict_obs",
")",
":",
"flatdict",
"=",
"obs_to_dict",
"(",
"maybe_di... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | learn | Main entrypoint for A2C algorithm. Train a policy with given network architecture on a given environment using a2c algorithm.
Parameters:
-----------
network: policy network architecture. Either string (mlp, lstm, lnlstm, cnn_lstm, cnn, cnn_small, conv_only - see baselines.common/models.py for ... | baselines/a2c/a2c.py | def learn(
network,
env,
seed=None,
nsteps=5,
total_timesteps=int(80e6),
vf_coef=0.5,
ent_coef=0.01,
max_grad_norm=0.5,
lr=7e-4,
lrschedule='linear',
epsilon=1e-5,
alpha=0.99,
gamma=0.99,
log_interval=100,
load_path=None,
**network_kwargs):
'''
Ma... | def learn(
network,
env,
seed=None,
nsteps=5,
total_timesteps=int(80e6),
vf_coef=0.5,
ent_coef=0.01,
max_grad_norm=0.5,
lr=7e-4,
lrschedule='linear',
epsilon=1e-5,
alpha=0.99,
gamma=0.99,
log_interval=100,
load_path=None,
**network_kwargs):
'''
Ma... | [
"Main",
"entrypoint",
"for",
"A2C",
"algorithm",
".",
"Train",
"a",
"policy",
"with",
"given",
"network",
"architecture",
"on",
"a",
"given",
"environment",
"using",
"a2c",
"algorithm",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/a2c/a2c.py#L119-L231 | [
"def",
"learn",
"(",
"network",
",",
"env",
",",
"seed",
"=",
"None",
",",
"nsteps",
"=",
"5",
",",
"total_timesteps",
"=",
"int",
"(",
"80e6",
")",
",",
"vf_coef",
"=",
"0.5",
",",
"ent_coef",
"=",
"0.01",
",",
"max_grad_norm",
"=",
"0.5",
",",
"l... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | sf01 | swap and then flatten axes 0 and 1 | baselines/ppo2/runner.py | def sf01(arr):
"""
swap and then flatten axes 0 and 1
"""
s = arr.shape
return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:]) | def sf01(arr):
"""
swap and then flatten axes 0 and 1
"""
s = arr.shape
return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:]) | [
"swap",
"and",
"then",
"flatten",
"axes",
"0",
"and",
"1"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/ppo2/runner.py#L69-L74 | [
"def",
"sf01",
"(",
"arr",
")",
":",
"s",
"=",
"arr",
".",
"shape",
"return",
"arr",
".",
"swapaxes",
"(",
"0",
",",
"1",
")",
".",
"reshape",
"(",
"s",
"[",
"0",
"]",
"*",
"s",
"[",
"1",
"]",
",",
"*",
"s",
"[",
"2",
":",
"]",
")"
] | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | PolicyWithValue.step | Compute next action(s) given the observation(s)
Parameters:
----------
observation observation data (either single or a batch)
**extra_feed additional data such as state or mask (names of the arguments should match the ones in constructor, see __init__)
Returns:
... | baselines/common/policies.py | def step(self, observation, **extra_feed):
"""
Compute next action(s) given the observation(s)
Parameters:
----------
observation observation data (either single or a batch)
**extra_feed additional data such as state or mask (names of the arguments should match ... | def step(self, observation, **extra_feed):
"""
Compute next action(s) given the observation(s)
Parameters:
----------
observation observation data (either single or a batch)
**extra_feed additional data such as state or mask (names of the arguments should match ... | [
"Compute",
"next",
"action",
"(",
"s",
")",
"given",
"the",
"observation",
"(",
"s",
")"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/policies.py#L77-L96 | [
"def",
"step",
"(",
"self",
",",
"observation",
",",
"*",
"*",
"extra_feed",
")",
":",
"a",
",",
"v",
",",
"state",
",",
"neglogp",
"=",
"self",
".",
"_evaluate",
"(",
"[",
"self",
".",
"action",
",",
"self",
".",
"vf",
",",
"self",
".",
"state",... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | PolicyWithValue.value | Compute value estimate(s) given the observation(s)
Parameters:
----------
observation observation data (either single or a batch)
**extra_feed additional data such as state or mask (names of the arguments should match the ones in constructor, see __init__)
Returns:
... | baselines/common/policies.py | def value(self, ob, *args, **kwargs):
"""
Compute value estimate(s) given the observation(s)
Parameters:
----------
observation observation data (either single or a batch)
**extra_feed additional data such as state or mask (names of the arguments should match th... | def value(self, ob, *args, **kwargs):
"""
Compute value estimate(s) given the observation(s)
Parameters:
----------
observation observation data (either single or a batch)
**extra_feed additional data such as state or mask (names of the arguments should match th... | [
"Compute",
"value",
"estimate",
"(",
"s",
")",
"given",
"the",
"observation",
"(",
"s",
")"
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/policies.py#L98-L113 | [
"def",
"value",
"(",
"self",
",",
"ob",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_evaluate",
"(",
"self",
".",
"vf",
",",
"ob",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
valid | pretty_eta | Print the number of seconds in human readable format.
Examples:
2 days
2 hours and 37 minutes
less than a minute
Paramters
---------
seconds_left: int
Number of seconds to be converted to the ETA
Returns
-------
eta: str
String representing the pretty ETA. | baselines/common/misc_util.py | def pretty_eta(seconds_left):
"""Print the number of seconds in human readable format.
Examples:
2 days
2 hours and 37 minutes
less than a minute
Paramters
---------
seconds_left: int
Number of seconds to be converted to the ETA
Returns
-------
eta: str
Stri... | def pretty_eta(seconds_left):
"""Print the number of seconds in human readable format.
Examples:
2 days
2 hours and 37 minutes
less than a minute
Paramters
---------
seconds_left: int
Number of seconds to be converted to the ETA
Returns
-------
eta: str
Stri... | [
"Print",
"the",
"number",
"of",
"seconds",
"in",
"human",
"readable",
"format",
"."
] | openai/baselines | python | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/misc_util.py#L65-L104 | [
"def",
"pretty_eta",
"(",
"seconds_left",
")",
":",
"minutes_left",
"=",
"seconds_left",
"//",
"60",
"seconds_left",
"%=",
"60",
"hours_left",
"=",
"minutes_left",
"//",
"60",
"minutes_left",
"%=",
"60",
"days_left",
"=",
"hours_left",
"//",
"24",
"hours_left",
... | 3301089b48c42b87b396e246ea3f56fa4bfc9678 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.