id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
230,500 | cltk/cltk | cltk/corpus/greek/tei.py | onekgreek_tei_xml_to_text | def onekgreek_tei_xml_to_text():
"""Find TEI XML dir of TEI XML for the First 1k Years of Greek corpus."""
if not bs4_installed:
logger.error('Install `bs4` and `lxml` to parse these TEI files.')
raise ImportError
xml_dir = os.path.expanduser('~/cltk_data/greek/text/greek_text_first1kgreek/data/*/*/*.xml')
xml_paths = glob.glob(xml_dir)
if not len(xml_paths):
logger.error('1K Greek corpus not installed. Use CorpusInstaller to get `First1KGreek`.')
raise FileNotFoundError
xml_paths = [path for path in xml_paths if '__cts__' not in path]
# new dir
new_dir = os.path.expanduser('~/cltk_data/greek/text/greek_text_first1kgreek_plaintext/')
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
for xml_path in xml_paths:
_, xml_name = os.path.split(xml_path)
xml_name = xml_name.rstrip('.xml')
xml_name += '.txt'
with open(xml_path) as file_open:
soup = BeautifulSoup(file_open, 'lxml')
body = soup.body
text = body.get_text()
new_plaintext_path = os.path.join(new_dir, xml_name)
with open(new_plaintext_path, 'w') as file_open:
file_open.write(text) | python | def onekgreek_tei_xml_to_text():
if not bs4_installed:
logger.error('Install `bs4` and `lxml` to parse these TEI files.')
raise ImportError
xml_dir = os.path.expanduser('~/cltk_data/greek/text/greek_text_first1kgreek/data/*/*/*.xml')
xml_paths = glob.glob(xml_dir)
if not len(xml_paths):
logger.error('1K Greek corpus not installed. Use CorpusInstaller to get `First1KGreek`.')
raise FileNotFoundError
xml_paths = [path for path in xml_paths if '__cts__' not in path]
# new dir
new_dir = os.path.expanduser('~/cltk_data/greek/text/greek_text_first1kgreek_plaintext/')
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
for xml_path in xml_paths:
_, xml_name = os.path.split(xml_path)
xml_name = xml_name.rstrip('.xml')
xml_name += '.txt'
with open(xml_path) as file_open:
soup = BeautifulSoup(file_open, 'lxml')
body = soup.body
text = body.get_text()
new_plaintext_path = os.path.join(new_dir, xml_name)
with open(new_plaintext_path, 'w') as file_open:
file_open.write(text) | [
"def",
"onekgreek_tei_xml_to_text",
"(",
")",
":",
"if",
"not",
"bs4_installed",
":",
"logger",
".",
"error",
"(",
"'Install `bs4` and `lxml` to parse these TEI files.'",
")",
"raise",
"ImportError",
"xml_dir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/clt... | Find TEI XML dir of TEI XML for the First 1k Years of Greek corpus. | [
"Find",
"TEI",
"XML",
"dir",
"of",
"TEI",
"XML",
"for",
"the",
"First",
"1k",
"Years",
"of",
"Greek",
"corpus",
"."
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/greek/tei.py#L24-L51 |
230,501 | cltk/cltk | cltk/corpus/greek/tei.py | onekgreek_tei_xml_to_text_capitains | def onekgreek_tei_xml_to_text_capitains():
"""Use MyCapitains program to convert TEI to plaintext."""
file = os.path.expanduser(
'~/cltk_data/greek/text/greek_text_first1kgreek/data/tlg0627/tlg021/tlg0627.tlg021.1st1K-grc1.xml')
xml_dir = os.path.expanduser('~/cltk_data/greek/text/greek_text_first1kgreek/data/*/*/*.xml')
xml_paths = glob.glob(xml_dir)
if not len(xml_paths):
logger.error('1K Greek corpus not installed. Use CorpusInstaller to get `First1KGreek`.')
raise FileNotFoundError
xml_paths = [path for path in xml_paths if '__cts__' not in path]
# new dir
new_dir = os.path.expanduser('~/cltk_data/greek/text/greek_text_first1kgreek_plaintext/')
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
for xml_path in xml_paths:
_, xml_name = os.path.split(xml_path)
xml_name = xml_name.rstrip('.xml')
xml_name += '.txt'
plain_text = ''
with open(xml_path) as file_open:
text = CapitainsCtsText(resource=file_open)
for ref in text.getReffs(level=len(text.citation)):
psg = text.getTextualNode(subreference=ref, simple=True)
text_line = psg.export(Mimetypes.PLAINTEXT, exclude=["tei:note"])
plain_text += text_line
new_plaintext_path = os.path.join(new_dir, xml_name)
with open(new_plaintext_path, 'w') as file_open:
file_open.write(plain_text) | python | def onekgreek_tei_xml_to_text_capitains():
file = os.path.expanduser(
'~/cltk_data/greek/text/greek_text_first1kgreek/data/tlg0627/tlg021/tlg0627.tlg021.1st1K-grc1.xml')
xml_dir = os.path.expanduser('~/cltk_data/greek/text/greek_text_first1kgreek/data/*/*/*.xml')
xml_paths = glob.glob(xml_dir)
if not len(xml_paths):
logger.error('1K Greek corpus not installed. Use CorpusInstaller to get `First1KGreek`.')
raise FileNotFoundError
xml_paths = [path for path in xml_paths if '__cts__' not in path]
# new dir
new_dir = os.path.expanduser('~/cltk_data/greek/text/greek_text_first1kgreek_plaintext/')
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
for xml_path in xml_paths:
_, xml_name = os.path.split(xml_path)
xml_name = xml_name.rstrip('.xml')
xml_name += '.txt'
plain_text = ''
with open(xml_path) as file_open:
text = CapitainsCtsText(resource=file_open)
for ref in text.getReffs(level=len(text.citation)):
psg = text.getTextualNode(subreference=ref, simple=True)
text_line = psg.export(Mimetypes.PLAINTEXT, exclude=["tei:note"])
plain_text += text_line
new_plaintext_path = os.path.join(new_dir, xml_name)
with open(new_plaintext_path, 'w') as file_open:
file_open.write(plain_text) | [
"def",
"onekgreek_tei_xml_to_text_capitains",
"(",
")",
":",
"file",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/cltk_data/greek/text/greek_text_first1kgreek/data/tlg0627/tlg021/tlg0627.tlg021.1st1K-grc1.xml'",
")",
"xml_dir",
"=",
"os",
".",
"path",
".",
"expanduse... | Use MyCapitains program to convert TEI to plaintext. | [
"Use",
"MyCapitains",
"program",
"to",
"convert",
"TEI",
"to",
"plaintext",
"."
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/greek/tei.py#L54-L85 |
230,502 | cltk/cltk | cltk/semantics/latin/lookup.py | Lemmata.load_replacement_patterns | def load_replacement_patterns(self):
"""Check for availability of the specified dictionary."""
filename = self.dictionary + '.py'
models = self.language + '_models_cltk'
rel_path = os.path.join('~/cltk_data',
self.language,
'model',
models,
'semantics',
filename)
path = os.path.expanduser(rel_path)
logger.info('Loading lemmata or synonyms. This may take a minute.')
loader = importlib.machinery.SourceFileLoader(filename, path)
module = types.ModuleType(loader.name)
loader.exec_module(module)
return module.DICTIONARY | python | def load_replacement_patterns(self):
filename = self.dictionary + '.py'
models = self.language + '_models_cltk'
rel_path = os.path.join('~/cltk_data',
self.language,
'model',
models,
'semantics',
filename)
path = os.path.expanduser(rel_path)
logger.info('Loading lemmata or synonyms. This may take a minute.')
loader = importlib.machinery.SourceFileLoader(filename, path)
module = types.ModuleType(loader.name)
loader.exec_module(module)
return module.DICTIONARY | [
"def",
"load_replacement_patterns",
"(",
"self",
")",
":",
"filename",
"=",
"self",
".",
"dictionary",
"+",
"'.py'",
"models",
"=",
"self",
".",
"language",
"+",
"'_models_cltk'",
"rel_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'~/cltk_data'",
",",
... | Check for availability of the specified dictionary. | [
"Check",
"for",
"availability",
"of",
"the",
"specified",
"dictionary",
"."
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/semantics/latin/lookup.py#L25-L40 |
230,503 | cltk/cltk | cltk/semantics/latin/lookup.py | Lemmata.lookup | def lookup(self, tokens):
"""Return a list of possible lemmata and their probabilities for each token"""
lemmatized_tokens = []
if type(tokens) == list:
for token in tokens:
# look for token in lemma dict keys
if token.lower() in self.lemmata.keys():
# `lemmas` is a list of possible lemmata. Probability values must be assigned.
# `lemmalist` is a list of the form [(LEMMA, PROBABILITY), (LEMMA, PROBABILITY)]
# `lemmaobj` is a tuple with the form (LEMMA, LIST)
lemmas = self.lemmata[token.lower()]
lemmalist = []
for lemma in lemmas:
lemmalist.append((lemma, 1/len(lemmas)))
lemmaobj = (token, lemmalist)
else:
# if token not found in lemma-headword list, return the token itself
lemmalist = []
lemmalist.append((token, 1))
lemmaobj = (token, lemmalist)
lemmatized_tokens.append(lemmaobj)
if type(tokens) == str:
if tokens.lower() in self.lemmata.keys():
# `lemmas` is a list of possible lemmata. Probability values must be assigned.
# `lemmalist` is a list of the form [(LEMMA, PROBABILITY), (LEMMA, PROBABILITY)]
# `lemmaobj` is a tuple with the form (LEMMA, LIST)
lemmas = self.lemmata[tokens.lower()]
lemmalist = []
for lemma in lemmas:
lemmalist.append((lemma, 1/len(lemmas)))
lemmaobj = (tokens, lemmalist)
else:
# if token not found in lemma-headword list, return the token itself
lemmalist = []
lemmalist.append((tokens, 1))
lemmaobj = (tokens, lemmalist)
lemmatized_tokens.append(lemmaobj)
return lemmatized_tokens | python | def lookup(self, tokens):
lemmatized_tokens = []
if type(tokens) == list:
for token in tokens:
# look for token in lemma dict keys
if token.lower() in self.lemmata.keys():
# `lemmas` is a list of possible lemmata. Probability values must be assigned.
# `lemmalist` is a list of the form [(LEMMA, PROBABILITY), (LEMMA, PROBABILITY)]
# `lemmaobj` is a tuple with the form (LEMMA, LIST)
lemmas = self.lemmata[token.lower()]
lemmalist = []
for lemma in lemmas:
lemmalist.append((lemma, 1/len(lemmas)))
lemmaobj = (token, lemmalist)
else:
# if token not found in lemma-headword list, return the token itself
lemmalist = []
lemmalist.append((token, 1))
lemmaobj = (token, lemmalist)
lemmatized_tokens.append(lemmaobj)
if type(tokens) == str:
if tokens.lower() in self.lemmata.keys():
# `lemmas` is a list of possible lemmata. Probability values must be assigned.
# `lemmalist` is a list of the form [(LEMMA, PROBABILITY), (LEMMA, PROBABILITY)]
# `lemmaobj` is a tuple with the form (LEMMA, LIST)
lemmas = self.lemmata[tokens.lower()]
lemmalist = []
for lemma in lemmas:
lemmalist.append((lemma, 1/len(lemmas)))
lemmaobj = (tokens, lemmalist)
else:
# if token not found in lemma-headword list, return the token itself
lemmalist = []
lemmalist.append((tokens, 1))
lemmaobj = (tokens, lemmalist)
lemmatized_tokens.append(lemmaobj)
return lemmatized_tokens | [
"def",
"lookup",
"(",
"self",
",",
"tokens",
")",
":",
"lemmatized_tokens",
"=",
"[",
"]",
"if",
"type",
"(",
"tokens",
")",
"==",
"list",
":",
"for",
"token",
"in",
"tokens",
":",
"# look for token in lemma dict keys",
"if",
"token",
".",
"lower",
"(",
... | Return a list of possible lemmata and their probabilities for each token | [
"Return",
"a",
"list",
"of",
"possible",
"lemmata",
"and",
"their",
"probabilities",
"for",
"each",
"token"
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/semantics/latin/lookup.py#L42-L79 |
230,504 | cltk/cltk | cltk/semantics/latin/lookup.py | Lemmata.isolate | def isolate(obj):
"""Feed a standard semantic object in and receive a simple list of
lemmata
"""
answers = []
for token in obj:
lemmata = token[1]
for pair in lemmata:
answers.append(pair[0])
return answers | python | def isolate(obj):
answers = []
for token in obj:
lemmata = token[1]
for pair in lemmata:
answers.append(pair[0])
return answers | [
"def",
"isolate",
"(",
"obj",
")",
":",
"answers",
"=",
"[",
"]",
"for",
"token",
"in",
"obj",
":",
"lemmata",
"=",
"token",
"[",
"1",
"]",
"for",
"pair",
"in",
"lemmata",
":",
"answers",
".",
"append",
"(",
"pair",
"[",
"0",
"]",
")",
"return",
... | Feed a standard semantic object in and receive a simple list of
lemmata | [
"Feed",
"a",
"standard",
"semantic",
"object",
"in",
"and",
"receive",
"a",
"simple",
"list",
"of",
"lemmata"
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/semantics/latin/lookup.py#L82-L91 |
230,505 | cltk/cltk | cltk/phonology/syllabify.py | Syllabifier.set_hierarchy | def set_hierarchy(self, hierarchy):
"""
Sets an alternative sonority hierarchy, note that you will also need
to specify the vowelset with the set_vowels, in order for the module
to correctly identify each nucleus.
The order of the phonemes defined is by decreased consonantality
Example:
>>> s = Syllabifier()
>>> s.set_hierarchy([['i', 'u'], ['e'], ['a'], ['r'], ['m', 'n'], ['f']])
>>> s.set_vowels(['i', 'u', 'e', 'a'])
>>> s.syllabify('feminarum')
['fe', 'mi', 'na', 'rum']
"""
self.hierarchy = dict([(k, i) for i, j in enumerate(hierarchy) for k in j]) | python | def set_hierarchy(self, hierarchy):
self.hierarchy = dict([(k, i) for i, j in enumerate(hierarchy) for k in j]) | [
"def",
"set_hierarchy",
"(",
"self",
",",
"hierarchy",
")",
":",
"self",
".",
"hierarchy",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"i",
")",
"for",
"i",
",",
"j",
"in",
"enumerate",
"(",
"hierarchy",
")",
"for",
"k",
"in",
"j",
"]",
")"
] | Sets an alternative sonority hierarchy, note that you will also need
to specify the vowelset with the set_vowels, in order for the module
to correctly identify each nucleus.
The order of the phonemes defined is by decreased consonantality
Example:
>>> s = Syllabifier()
>>> s.set_hierarchy([['i', 'u'], ['e'], ['a'], ['r'], ['m', 'n'], ['f']])
>>> s.set_vowels(['i', 'u', 'e', 'a'])
>>> s.syllabify('feminarum')
['fe', 'mi', 'na', 'rum'] | [
"Sets",
"an",
"alternative",
"sonority",
"hierarchy",
"note",
"that",
"you",
"will",
"also",
"need",
"to",
"specify",
"the",
"vowelset",
"with",
"the",
"set_vowels",
"in",
"order",
"for",
"the",
"module",
"to",
"correctly",
"identify",
"each",
"nucleus",
"."
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/phonology/syllabify.py#L150-L168 |
230,506 | cltk/cltk | cltk/phonology/syllabify.py | Syllabifier.syllabify_ssp | def syllabify_ssp(self, word):
"""
Syllabifies a word according to the Sonority Sequencing Principle
:param word: Word to be syllabified
:return: List consisting of syllables
Example:
First you need to define the matters of articulation
>>> high_vowels = ['a']
>>> mid_vowels = ['e']
>>> low_vowels = ['i', 'u']
>>> flaps = ['r']
>>> nasals = ['m', 'n']
>>> fricatives = ['f']
>>> s = Syllabifier(high_vowels=high_vowels, mid_vowels=mid_vowels, low_vowels=low_vowels, flaps=flaps, nasals=nasals, fricatives=fricatives)
>>> s.syllabify("feminarum")
['fe', 'mi', 'na', 'rum']
Not specifying your alphabet results in an error:
>>> s.syllabify("foemina")
Traceback (most recent call last):
...
cltk.exceptions.InputError
Additionally, you can utilize the language parameter:
>>> s = Syllabifier(language='middle_high_german')
>>> s.syllabify('lobebæren')
['lo', 'be', 'bæ', 'ren']
>>> s = Syllabifier(language='middle_english')
>>> s.syllabify("huntyng")
['hun', 'tyng']
>>> s = Syllabifier(language='old_english')
>>> s.syllabify("arcebiscop")
['ar', 'ce', 'bis', 'cop']
The break_geminants parameter ensures a breakpoint is placed between geminants:
>>> geminant_s = Syllabifier(break_geminants=True)
>>> hierarchy = [["a", "á", "æ", "e", "é", "i", "í", "o", "ǫ", "ø", "ö", "œ", "ó", "u", "ú", "y", "ý"], ["j"], ["m"], ["n"], ["p", "b", "d", "g", "t", "k"], ["c", "f", "s", "h", "v", "x", "þ", "ð"], ["r"], ["l"]]
>>> geminant_s.set_hierarchy(hierarchy)
>>> geminant_s.set_vowels(hierarchy[0])
>>> geminant_s.syllabify("ennitungl")
['en', 'ni', 'tungl']
"""
# List indicating the syllable indices
syllables = []
find_nucleus = True
i = 0
try:
# Replace each letter occurence with its corresponding number
# indicating its position in the sonority hierarchy
encoded = list(map(lambda x: self.hierarchy[x], word))
except KeyError:
LOG.error(
"The given string contains invalid characters. "
"Make sure to define the mater of articulation for each phoneme.")
raise InputError
while i < len(word) - 1:
# Search for nucleus
while word[i] not in self.vowels and i < len(word) - 1 and find_nucleus:
i += 1
if find_nucleus is True:
i += 1
if i >= len(word) - 1:
break
else:
# If the break_geminants parameter is set to True, prioritize geminants
if self.break_geminants and word[i-1] == word[i]:
syllables.append(i-1)
find_nucleus = True
# If a cluster of three phonemes with the same values exist, break syllable
elif encoded[i - 1] == encoded[i] == encoded[i + 1]:
syllables.append(i)
find_nucleus = True
elif encoded[i] > encoded[i - 1] and encoded[i] > encoded[i + 1]:
syllables.append(i)
find_nucleus = True
elif encoded[i] < encoded[i - 1] and encoded[i] < encoded[i + 1]:
syllables.append(i)
find_nucleus = True
else:
find_nucleus = False
i += 1
for n, k in enumerate(syllables):
word = word[:k + n + 1] + "." + word[k + n + 1:]
word = word.split('.')
# Check if last syllable has a nucleus
if sum([x in self.vowels for x in word[-1]]) == 0:
word[-2] += word[-1]
word = word[:-1]
return self.onset_maximization(word) | python | def syllabify_ssp(self, word):
# List indicating the syllable indices
syllables = []
find_nucleus = True
i = 0
try:
# Replace each letter occurence with its corresponding number
# indicating its position in the sonority hierarchy
encoded = list(map(lambda x: self.hierarchy[x], word))
except KeyError:
LOG.error(
"The given string contains invalid characters. "
"Make sure to define the mater of articulation for each phoneme.")
raise InputError
while i < len(word) - 1:
# Search for nucleus
while word[i] not in self.vowels and i < len(word) - 1 and find_nucleus:
i += 1
if find_nucleus is True:
i += 1
if i >= len(word) - 1:
break
else:
# If the break_geminants parameter is set to True, prioritize geminants
if self.break_geminants and word[i-1] == word[i]:
syllables.append(i-1)
find_nucleus = True
# If a cluster of three phonemes with the same values exist, break syllable
elif encoded[i - 1] == encoded[i] == encoded[i + 1]:
syllables.append(i)
find_nucleus = True
elif encoded[i] > encoded[i - 1] and encoded[i] > encoded[i + 1]:
syllables.append(i)
find_nucleus = True
elif encoded[i] < encoded[i - 1] and encoded[i] < encoded[i + 1]:
syllables.append(i)
find_nucleus = True
else:
find_nucleus = False
i += 1
for n, k in enumerate(syllables):
word = word[:k + n + 1] + "." + word[k + n + 1:]
word = word.split('.')
# Check if last syllable has a nucleus
if sum([x in self.vowels for x in word[-1]]) == 0:
word[-2] += word[-1]
word = word[:-1]
return self.onset_maximization(word) | [
"def",
"syllabify_ssp",
"(",
"self",
",",
"word",
")",
":",
"# List indicating the syllable indices",
"syllables",
"=",
"[",
"]",
"find_nucleus",
"=",
"True",
"i",
"=",
"0",
"try",
":",
"# Replace each letter occurence with its corresponding number",
"# indicating its pos... | Syllabifies a word according to the Sonority Sequencing Principle
:param word: Word to be syllabified
:return: List consisting of syllables
Example:
First you need to define the matters of articulation
>>> high_vowels = ['a']
>>> mid_vowels = ['e']
>>> low_vowels = ['i', 'u']
>>> flaps = ['r']
>>> nasals = ['m', 'n']
>>> fricatives = ['f']
>>> s = Syllabifier(high_vowels=high_vowels, mid_vowels=mid_vowels, low_vowels=low_vowels, flaps=flaps, nasals=nasals, fricatives=fricatives)
>>> s.syllabify("feminarum")
['fe', 'mi', 'na', 'rum']
Not specifying your alphabet results in an error:
>>> s.syllabify("foemina")
Traceback (most recent call last):
...
cltk.exceptions.InputError
Additionally, you can utilize the language parameter:
>>> s = Syllabifier(language='middle_high_german')
>>> s.syllabify('lobebæren')
['lo', 'be', 'bæ', 'ren']
>>> s = Syllabifier(language='middle_english')
>>> s.syllabify("huntyng")
['hun', 'tyng']
>>> s = Syllabifier(language='old_english')
>>> s.syllabify("arcebiscop")
['ar', 'ce', 'bis', 'cop']
The break_geminants parameter ensures a breakpoint is placed between geminants:
>>> geminant_s = Syllabifier(break_geminants=True)
>>> hierarchy = [["a", "á", "æ", "e", "é", "i", "í", "o", "ǫ", "ø", "ö", "œ", "ó", "u", "ú", "y", "ý"], ["j"], ["m"], ["n"], ["p", "b", "d", "g", "t", "k"], ["c", "f", "s", "h", "v", "x", "þ", "ð"], ["r"], ["l"]]
>>> geminant_s.set_hierarchy(hierarchy)
>>> geminant_s.set_vowels(hierarchy[0])
>>> geminant_s.syllabify("ennitungl")
['en', 'ni', 'tungl'] | [
"Syllabifies",
"a",
"word",
"according",
"to",
"the",
"Sonority",
"Sequencing",
"Principle"
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/phonology/syllabify.py#L188-L318 |
230,507 | cltk/cltk | cltk/prosody/latin/pentameter_scanner.py | PentameterScanner.make_spondaic | def make_spondaic(self, scansion: str) -> str:
"""
If a pentameter line has 12 syllables, then it must start with double spondees.
:param scansion: a string of scansion patterns
:return: a scansion pattern string starting with two spondees
>>> print(PentameterScanner().make_spondaic("U U U U U U U U U U U U"))
- - - - - - U U - U U U
"""
mark_list = string_utils.mark_list(scansion)
vals = list(scansion.replace(" ", ""))
new_vals = self.SPONDAIC_PENTAMETER[:-1] + vals[-1]
corrected = "".join(new_vals)
new_line = list(" " * len(scansion))
for idx, car in enumerate(corrected):
new_line[mark_list[idx]] = car
return "".join(new_line) | python | def make_spondaic(self, scansion: str) -> str:
mark_list = string_utils.mark_list(scansion)
vals = list(scansion.replace(" ", ""))
new_vals = self.SPONDAIC_PENTAMETER[:-1] + vals[-1]
corrected = "".join(new_vals)
new_line = list(" " * len(scansion))
for idx, car in enumerate(corrected):
new_line[mark_list[idx]] = car
return "".join(new_line) | [
"def",
"make_spondaic",
"(",
"self",
",",
"scansion",
":",
"str",
")",
"->",
"str",
":",
"mark_list",
"=",
"string_utils",
".",
"mark_list",
"(",
"scansion",
")",
"vals",
"=",
"list",
"(",
"scansion",
".",
"replace",
"(",
"\" \"",
",",
"\"\"",
")",
")"... | If a pentameter line has 12 syllables, then it must start with double spondees.
:param scansion: a string of scansion patterns
:return: a scansion pattern string starting with two spondees
>>> print(PentameterScanner().make_spondaic("U U U U U U U U U U U U"))
- - - - - - U U - U U U | [
"If",
"a",
"pentameter",
"line",
"has",
"12",
"syllables",
"then",
"it",
"must",
"start",
"with",
"double",
"spondees",
"."
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/pentameter_scanner.py#L169-L186 |
230,508 | cltk/cltk | cltk/prosody/latin/pentameter_scanner.py | PentameterScanner.correct_penultimate_dactyl_chain | def correct_penultimate_dactyl_chain(self, scansion: str) -> str:
"""
For pentameter the last two feet of the verse are predictable dactyls,
and do not regularly allow substitutions.
:param scansion: scansion line thus far
:return: corrected line of scansion
>>> print(PentameterScanner().correct_penultimate_dactyl_chain(
... "U U U U U U U U U U U U U U"))
U U U U U U U - U U - U U U
"""
mark_list = string_utils.mark_list(scansion)
vals = list(scansion.replace(" ", ""))
n_vals = vals[:-7] + [self.constants.DACTYL + self.constants.DACTYL] + [vals[-1]]
corrected = "".join(n_vals)
new_line = list(" " * len(scansion))
for idx, car in enumerate(corrected):
new_line[mark_list[idx]] = car
return "".join(new_line) | python | def correct_penultimate_dactyl_chain(self, scansion: str) -> str:
mark_list = string_utils.mark_list(scansion)
vals = list(scansion.replace(" ", ""))
n_vals = vals[:-7] + [self.constants.DACTYL + self.constants.DACTYL] + [vals[-1]]
corrected = "".join(n_vals)
new_line = list(" " * len(scansion))
for idx, car in enumerate(corrected):
new_line[mark_list[idx]] = car
return "".join(new_line) | [
"def",
"correct_penultimate_dactyl_chain",
"(",
"self",
",",
"scansion",
":",
"str",
")",
"->",
"str",
":",
"mark_list",
"=",
"string_utils",
".",
"mark_list",
"(",
"scansion",
")",
"vals",
"=",
"list",
"(",
"scansion",
".",
"replace",
"(",
"\" \"",
",",
"... | For pentameter the last two feet of the verse are predictable dactyls,
and do not regularly allow substitutions.
:param scansion: scansion line thus far
:return: corrected line of scansion
>>> print(PentameterScanner().correct_penultimate_dactyl_chain(
... "U U U U U U U U U U U U U U"))
U U U U U U U - U U - U U U | [
"For",
"pentameter",
"the",
"last",
"two",
"feet",
"of",
"the",
"verse",
"are",
"predictable",
"dactyls",
"and",
"do",
"not",
"regularly",
"allow",
"substitutions",
"."
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/pentameter_scanner.py#L207-L226 |
230,509 | cltk/cltk | cltk/utils/contributors.py | eval_str_to_list | def eval_str_to_list(input_str: str) -> List[str]:
"""Turn str into str or tuple."""
inner_cast = ast.literal_eval(input_str) # type: List[str]
if isinstance(inner_cast, list):
return inner_cast
else:
raise ValueError | python | def eval_str_to_list(input_str: str) -> List[str]:
inner_cast = ast.literal_eval(input_str) # type: List[str]
if isinstance(inner_cast, list):
return inner_cast
else:
raise ValueError | [
"def",
"eval_str_to_list",
"(",
"input_str",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"inner_cast",
"=",
"ast",
".",
"literal_eval",
"(",
"input_str",
")",
"# type: List[str]",
"if",
"isinstance",
"(",
"inner_cast",
",",
"list",
")",
":",
"retu... | Turn str into str or tuple. | [
"Turn",
"str",
"into",
"str",
"or",
"tuple",
"."
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/utils/contributors.py#L23-L29 |
230,510 | cltk/cltk | cltk/utils/contributors.py | get_authors | def get_authors(filepath: str) -> List[str]:
"""Open file and check for author info."""
str_oneline = r'(^__author__ = )(\[.*?\])' # type" str
comp_oneline = re.compile(str_oneline, re.MULTILINE) # type: Pattern[str]
with open(filepath) as file_open:
file_read = file_open.read() # type: str
match = comp_oneline.findall(file_read)
if match:
inner_list_as_str = match[0][1] # type: str
inner_list = eval_str_to_list(inner_list_as_str) # type: List[str]
return inner_list
return list() | python | def get_authors(filepath: str) -> List[str]:
str_oneline = r'(^__author__ = )(\[.*?\])' # type" str
comp_oneline = re.compile(str_oneline, re.MULTILINE) # type: Pattern[str]
with open(filepath) as file_open:
file_read = file_open.read() # type: str
match = comp_oneline.findall(file_read)
if match:
inner_list_as_str = match[0][1] # type: str
inner_list = eval_str_to_list(inner_list_as_str) # type: List[str]
return inner_list
return list() | [
"def",
"get_authors",
"(",
"filepath",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"str_oneline",
"=",
"r'(^__author__ = )(\\[.*?\\])'",
"# type\" str",
"comp_oneline",
"=",
"re",
".",
"compile",
"(",
"str_oneline",
",",
"re",
".",
"MULTILINE",
")",
... | Open file and check for author info. | [
"Open",
"file",
"and",
"check",
"for",
"author",
"info",
"."
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/utils/contributors.py#L32-L43 |
230,511 | cltk/cltk | cltk/utils/contributors.py | scantree | def scantree(path: str) -> Generator:
"""Recursively yield DirEntry objects for given directory."""
for entry in os.scandir(path):
if entry.is_dir(follow_symlinks=False):
yield from scantree(entry.path)
else:
if entry.name.endswith('.py'):
yield entry | python | def scantree(path: str) -> Generator:
for entry in os.scandir(path):
if entry.is_dir(follow_symlinks=False):
yield from scantree(entry.path)
else:
if entry.name.endswith('.py'):
yield entry | [
"def",
"scantree",
"(",
"path",
":",
"str",
")",
"->",
"Generator",
":",
"for",
"entry",
"in",
"os",
".",
"scandir",
"(",
"path",
")",
":",
"if",
"entry",
".",
"is_dir",
"(",
"follow_symlinks",
"=",
"False",
")",
":",
"yield",
"from",
"scantree",
"("... | Recursively yield DirEntry objects for given directory. | [
"Recursively",
"yield",
"DirEntry",
"objects",
"for",
"given",
"directory",
"."
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/utils/contributors.py#L46-L53 |
230,512 | cltk/cltk | cltk/utils/contributors.py | write_contribs | def write_contribs(def_dict_list: Dict[str, List[str]]) -> None:
"""Write to file, in current dir, 'contributors.md'."""
file_str = '' # type: str
note = '# Contributors\nCLTK Core authors, ordered alphabetically by first name\n\n' # type: str # pylint: disable=line-too-long
file_str += note
for contrib in def_dict_list:
file_str += '## ' + contrib + '\n'
for module in def_dict_list[contrib]:
file_str += '* ' + module + '\n'
file_str += '\n'
file_name = 'contributors.md' # type: str
with open(file_name, 'w') as file_open: # type: IO
file_open.write(file_str)
logger.info('Wrote contribs file at "%s".', file_name) | python | def write_contribs(def_dict_list: Dict[str, List[str]]) -> None:
file_str = '' # type: str
note = '# Contributors\nCLTK Core authors, ordered alphabetically by first name\n\n' # type: str # pylint: disable=line-too-long
file_str += note
for contrib in def_dict_list:
file_str += '## ' + contrib + '\n'
for module in def_dict_list[contrib]:
file_str += '* ' + module + '\n'
file_str += '\n'
file_name = 'contributors.md' # type: str
with open(file_name, 'w') as file_open: # type: IO
file_open.write(file_str)
logger.info('Wrote contribs file at "%s".', file_name) | [
"def",
"write_contribs",
"(",
"def_dict_list",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
")",
"->",
"None",
":",
"file_str",
"=",
"''",
"# type: str",
"note",
"=",
"'# Contributors\\nCLTK Core authors, ordered alphabetically by first name\\n\\n'",
... | Write to file, in current dir, 'contributors.md'. | [
"Write",
"to",
"file",
"in",
"current",
"dir",
"contributors",
".",
"md",
"."
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/utils/contributors.py#L56-L69 |
230,513 | cltk/cltk | cltk/utils/contributors.py | find_write_contribs | def find_write_contribs() -> None:
"""Look for files, find authors, sort, write file."""
map_file_auth = {} # type: Dict[str, List[str]]
for filename in scantree('cltk'):
filepath = filename.path # type: str
authors_list = get_authors(filepath) # type: List[str]
if authors_list:
map_file_auth[filepath] = authors_list
map_auth_file = defaultdict(list) # type: Dict[str, List[str]]
for file, authors_file in map_file_auth.items():
for author in authors_file:
map_auth_file[author].append(file)
# now sort the str contents of the list value
map_auth_file = sort_def_dict(map_auth_file)
map_auth_file_sorted = sorted(map_auth_file.items()) # type: List[Tuple[str, List[str]]]
map_auth_file = OrderedDict(map_auth_file_sorted)
write_contribs(map_auth_file) | python | def find_write_contribs() -> None:
map_file_auth = {} # type: Dict[str, List[str]]
for filename in scantree('cltk'):
filepath = filename.path # type: str
authors_list = get_authors(filepath) # type: List[str]
if authors_list:
map_file_auth[filepath] = authors_list
map_auth_file = defaultdict(list) # type: Dict[str, List[str]]
for file, authors_file in map_file_auth.items():
for author in authors_file:
map_auth_file[author].append(file)
# now sort the str contents of the list value
map_auth_file = sort_def_dict(map_auth_file)
map_auth_file_sorted = sorted(map_auth_file.items()) # type: List[Tuple[str, List[str]]]
map_auth_file = OrderedDict(map_auth_file_sorted)
write_contribs(map_auth_file) | [
"def",
"find_write_contribs",
"(",
")",
"->",
"None",
":",
"map_file_auth",
"=",
"{",
"}",
"# type: Dict[str, List[str]]",
"for",
"filename",
"in",
"scantree",
"(",
"'cltk'",
")",
":",
"filepath",
"=",
"filename",
".",
"path",
"# type: str",
"authors_list",
"=",... | Look for files, find authors, sort, write file. | [
"Look",
"for",
"files",
"find",
"authors",
"sort",
"write",
"file",
"."
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/utils/contributors.py#L79-L97 |
230,514 | cltk/cltk | cltk/prosody/old_norse/verse.py | Metre.syllabify | def syllabify(self, hierarchy):
"""
Syllables may play a role in verse classification.
"""
if len(self.long_lines) == 0:
logger.error("No text was imported")
self.syllabified_text = []
else:
syllabifier = Syllabifier(language="old_norse", break_geminants=True)
syllabifier.set_hierarchy(hierarchy)
syllabified_text = []
for i, long_line in enumerate(self.long_lines):
syllabified_text.append([])
for short_line in long_line:
assert isinstance(short_line, ShortLine) or isinstance(short_line, LongLine)
short_line.syllabify(syllabifier)
syllabified_text[i].append(short_line.syllabified)
self.syllabified_text = syllabified_text | python | def syllabify(self, hierarchy):
if len(self.long_lines) == 0:
logger.error("No text was imported")
self.syllabified_text = []
else:
syllabifier = Syllabifier(language="old_norse", break_geminants=True)
syllabifier.set_hierarchy(hierarchy)
syllabified_text = []
for i, long_line in enumerate(self.long_lines):
syllabified_text.append([])
for short_line in long_line:
assert isinstance(short_line, ShortLine) or isinstance(short_line, LongLine)
short_line.syllabify(syllabifier)
syllabified_text[i].append(short_line.syllabified)
self.syllabified_text = syllabified_text | [
"def",
"syllabify",
"(",
"self",
",",
"hierarchy",
")",
":",
"if",
"len",
"(",
"self",
".",
"long_lines",
")",
"==",
"0",
":",
"logger",
".",
"error",
"(",
"\"No text was imported\"",
")",
"self",
".",
"syllabified_text",
"=",
"[",
"]",
"else",
":",
"s... | Syllables may play a role in verse classification. | [
"Syllables",
"may",
"play",
"a",
"role",
"in",
"verse",
"classification",
"."
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/old_norse/verse.py#L274-L291 |
230,515 | cltk/cltk | cltk/prosody/old_norse/verse.py | Metre.to_phonetics | def to_phonetics(self):
"""
Transcribing words in verse helps find alliteration.
"""
if len(self.long_lines) == 0:
logger.error("No text was imported")
self.syllabified_text = []
else:
transcriber = Transcriber(DIPHTHONGS_IPA, DIPHTHONGS_IPA_class, IPA_class, old_norse_rules)
transcribed_text = []
phonological_features_text = []
for i, long_line in enumerate(self.long_lines):
transcribed_text.append([])
phonological_features_text.append([])
for short_line in long_line:
assert isinstance(short_line, ShortLine) or isinstance(short_line, LongLine)
short_line.to_phonetics(transcriber)
transcribed_text[i].append(short_line.transcribed)
phonological_features_text[i].append(short_line.phonological_features_text)
self.transcribed_text = transcribed_text
self.phonological_features_text = phonological_features_text | python | def to_phonetics(self):
if len(self.long_lines) == 0:
logger.error("No text was imported")
self.syllabified_text = []
else:
transcriber = Transcriber(DIPHTHONGS_IPA, DIPHTHONGS_IPA_class, IPA_class, old_norse_rules)
transcribed_text = []
phonological_features_text = []
for i, long_line in enumerate(self.long_lines):
transcribed_text.append([])
phonological_features_text.append([])
for short_line in long_line:
assert isinstance(short_line, ShortLine) or isinstance(short_line, LongLine)
short_line.to_phonetics(transcriber)
transcribed_text[i].append(short_line.transcribed)
phonological_features_text[i].append(short_line.phonological_features_text)
self.transcribed_text = transcribed_text
self.phonological_features_text = phonological_features_text | [
"def",
"to_phonetics",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"long_lines",
")",
"==",
"0",
":",
"logger",
".",
"error",
"(",
"\"No text was imported\"",
")",
"self",
".",
"syllabified_text",
"=",
"[",
"]",
"else",
":",
"transcriber",
"=",... | Transcribing words in verse helps find alliteration. | [
"Transcribing",
"words",
"in",
"verse",
"helps",
"find",
"alliteration",
"."
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/old_norse/verse.py#L293-L314 |
230,516 | cltk/cltk | cltk/prosody/old_norse/verse.py | PoeticWord.parse_word_with | def parse_word_with(self, poetry_tools: PoetryTools):
"""
Compute the phonetic transcription of the word with IPA representation
Compute the syllables of the word
Compute the length of each syllable
Compute if a syllable is stress of noe
Compute the POS category the word is in
:param poetry_tools: instance of PoetryTools
:return:
"""
phonemes = poetry_tools.tr.text_to_phonemes(self.text)
self.syl = poetry_tools.syllabifier.syllabify_phonemes(phonemes)
for i, syllable in enumerate(self.syl):
self.ipa_transcription.append([])
syl_len = measure_old_norse_syllable(syllable).value
syl_stress = 1 if i == 0 else 0
self.length.append(syl_len)
self.stress.append(syl_stress)
for c in syllable:
self.ipa_transcription[i].append(c.ipar) | python | def parse_word_with(self, poetry_tools: PoetryTools):
phonemes = poetry_tools.tr.text_to_phonemes(self.text)
self.syl = poetry_tools.syllabifier.syllabify_phonemes(phonemes)
for i, syllable in enumerate(self.syl):
self.ipa_transcription.append([])
syl_len = measure_old_norse_syllable(syllable).value
syl_stress = 1 if i == 0 else 0
self.length.append(syl_len)
self.stress.append(syl_stress)
for c in syllable:
self.ipa_transcription[i].append(c.ipar) | [
"def",
"parse_word_with",
"(",
"self",
",",
"poetry_tools",
":",
"PoetryTools",
")",
":",
"phonemes",
"=",
"poetry_tools",
".",
"tr",
".",
"text_to_phonemes",
"(",
"self",
".",
"text",
")",
"self",
".",
"syl",
"=",
"poetry_tools",
".",
"syllabifier",
".",
... | Compute the phonetic transcription of the word with IPA representation
Compute the syllables of the word
Compute the length of each syllable
Compute if a syllable is stress of noe
Compute the POS category the word is in
:param poetry_tools: instance of PoetryTools
:return: | [
"Compute",
"the",
"phonetic",
"transcription",
"of",
"the",
"word",
"with",
"IPA",
"representation",
"Compute",
"the",
"syllables",
"of",
"the",
"word",
"Compute",
"the",
"length",
"of",
"each",
"syllable",
"Compute",
"if",
"a",
"syllable",
"is",
"stress",
"of... | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/old_norse/verse.py#L627-L648 |
230,517 | cltk/cltk | cltk/tag/treebanks.py | set_path | def set_path(dicts, keys, v):
""" Helper function for modifying nested dictionaries
:param dicts: dict: the given dictionary
:param keys: list str: path to added value
:param v: str: value to be added
Example:
>>> d = dict()
>>> set_path(d, ['a', 'b', 'c'], 'd')
>>> d
{'a': {'b': {'c': ['d']}}}
In case of duplicate paths, the additional value will
be added to the leaf node rather than simply replace it:
>>> set_path(d, ['a', 'b', 'c'], 'e')
>>> d
{'a': {'b': {'c': ['d', 'e']}}}
"""
for key in keys[:-1]:
dicts = dicts.setdefault(key, dict())
dicts = dicts.setdefault(keys[-1], list())
dicts.append(v) | python | def set_path(dicts, keys, v):
for key in keys[:-1]:
dicts = dicts.setdefault(key, dict())
dicts = dicts.setdefault(keys[-1], list())
dicts.append(v) | [
"def",
"set_path",
"(",
"dicts",
",",
"keys",
",",
"v",
")",
":",
"for",
"key",
"in",
"keys",
"[",
":",
"-",
"1",
"]",
":",
"dicts",
"=",
"dicts",
".",
"setdefault",
"(",
"key",
",",
"dict",
"(",
")",
")",
"dicts",
"=",
"dicts",
".",
"setdefaul... | Helper function for modifying nested dictionaries
:param dicts: dict: the given dictionary
:param keys: list str: path to added value
:param v: str: value to be added
Example:
>>> d = dict()
>>> set_path(d, ['a', 'b', 'c'], 'd')
>>> d
{'a': {'b': {'c': ['d']}}}
In case of duplicate paths, the additional value will
be added to the leaf node rather than simply replace it:
>>> set_path(d, ['a', 'b', 'c'], 'e')
>>> d
{'a': {'b': {'c': ['d', 'e']}}} | [
"Helper",
"function",
"for",
"modifying",
"nested",
"dictionaries"
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/tag/treebanks.py#L5-L31 |
230,518 | cltk/cltk | cltk/tag/treebanks.py | get_paths | def get_paths(src):
""" Generates root-to-leaf paths, given a treebank in string format. Note that
get_path is an iterator and does not return all the paths simultaneously.
:param src: str: treebank
Examples:
>>> st = "((IP-MAT-SPE (' ') (INTJ Yes) (, ,) (' ') (IP-MAT-PRN (NP-SBJ (PRO he)) (VBD seyde)) (, ,) (' ') (NP-SBJ (PRO I)) (MD shall) (VB promyse) (NP-OB2 (PRO you)) (IP-INF (TO to) (VB fullfylle) (NP-OB1 (PRO$ youre) (N desyre))) (. .) (' '))"
Get the sixth generated path:
>>> list(get_paths(st))[5]
['IP-MAT-SPE', 'IP-MAT-PRN', 'VBD', 'seyde']
"""
st = list()
tmp = ''
for let in src:
if let == '(':
if tmp != '':
st.append(tmp)
tmp = ''
elif let == ')':
if tmp != '':
st.append(tmp)
yield st
st = st[:-1 - (tmp != '')]
tmp = ''
elif let == ' ':
if tmp != '':
st.append(tmp)
tmp = ''
else:
tmp += let | python | def get_paths(src):
st = list()
tmp = ''
for let in src:
if let == '(':
if tmp != '':
st.append(tmp)
tmp = ''
elif let == ')':
if tmp != '':
st.append(tmp)
yield st
st = st[:-1 - (tmp != '')]
tmp = ''
elif let == ' ':
if tmp != '':
st.append(tmp)
tmp = ''
else:
tmp += let | [
"def",
"get_paths",
"(",
"src",
")",
":",
"st",
"=",
"list",
"(",
")",
"tmp",
"=",
"''",
"for",
"let",
"in",
"src",
":",
"if",
"let",
"==",
"'('",
":",
"if",
"tmp",
"!=",
"''",
":",
"st",
".",
"append",
"(",
"tmp",
")",
"tmp",
"=",
"''",
"e... | Generates root-to-leaf paths, given a treebank in string format. Note that
get_path is an iterator and does not return all the paths simultaneously.
:param src: str: treebank
Examples:
>>> st = "((IP-MAT-SPE (' ') (INTJ Yes) (, ,) (' ') (IP-MAT-PRN (NP-SBJ (PRO he)) (VBD seyde)) (, ,) (' ') (NP-SBJ (PRO I)) (MD shall) (VB promyse) (NP-OB2 (PRO you)) (IP-INF (TO to) (VB fullfylle) (NP-OB1 (PRO$ youre) (N desyre))) (. .) (' '))"
Get the sixth generated path:
>>> list(get_paths(st))[5]
['IP-MAT-SPE', 'IP-MAT-PRN', 'VBD', 'seyde'] | [
"Generates",
"root",
"-",
"to",
"-",
"leaf",
"paths",
"given",
"a",
"treebank",
"in",
"string",
"format",
".",
"Note",
"that",
"get_path",
"is",
"an",
"iterator",
"and",
"does",
"not",
"return",
"all",
"the",
"paths",
"simultaneously",
"."
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/tag/treebanks.py#L34-L66 |
230,519 | cltk/cltk | cltk/phonology/old_english/phonology.py | Transliterate.transliterate | def transliterate(self, text, mode='Latin'):
"""
Transliterates Anglo-Saxon runes into latin and vice versa.
Sources:
http://www.arild-hauge.com/eanglor.htm
https://en.wikipedia.org/wiki/Anglo-Saxon_runes
:param text: str: The text to be transcribed
:param mode: Specifies transliteration mode, options:
Latin (default): Transliterates Anglo-Saxon runes into the latin
alphabet, using the Dickins system
Anglo-Saxon/Anglo-Frisian : Transliterates Latin text into Anglo-Saxon runes
Examples:
>>> Transliterate().transliterate("Hƿæt Ƿe Gardena in geardagum", "Anglo-Saxon")
'ᚻᚹᚫᛏ ᚹᛖ ᚷᚪᚱᛞᛖᚾᚪ ᛁᚾ ᚷᛠᚱᛞᚪᚷᚢᛗ'
>>> Transliterate().transliterate("ᚩᚠᛏ ᛋᚳᚣᛚᛞ ᛋᚳᛖᚠᛁᛝ ᛋᚳᛠᚦᛖᚾᚪ ᚦᚱᛠᛏᚢᛗ", "Latin")
'oft scyld scefin sceathena threatum'
"""
if mode == 'Latin':
return Transliterate.__transliterate_helper(text, L_Transliteration)
elif mode in ['Anglo-Saxon', 'Anglo-Frisian']:
return Transliterate.__transliterate_helper(text, R_Transliteration)
else:
LOG.error("The specified mode is currently not supported")
raise InputError("The specified mode is currently not supported") | python | def transliterate(self, text, mode='Latin'):
if mode == 'Latin':
return Transliterate.__transliterate_helper(text, L_Transliteration)
elif mode in ['Anglo-Saxon', 'Anglo-Frisian']:
return Transliterate.__transliterate_helper(text, R_Transliteration)
else:
LOG.error("The specified mode is currently not supported")
raise InputError("The specified mode is currently not supported") | [
"def",
"transliterate",
"(",
"self",
",",
"text",
",",
"mode",
"=",
"'Latin'",
")",
":",
"if",
"mode",
"==",
"'Latin'",
":",
"return",
"Transliterate",
".",
"__transliterate_helper",
"(",
"text",
",",
"L_Transliteration",
")",
"elif",
"mode",
"in",
"[",
"'... | Transliterates Anglo-Saxon runes into latin and vice versa.
Sources:
http://www.arild-hauge.com/eanglor.htm
https://en.wikipedia.org/wiki/Anglo-Saxon_runes
:param text: str: The text to be transcribed
:param mode: Specifies transliteration mode, options:
Latin (default): Transliterates Anglo-Saxon runes into the latin
alphabet, using the Dickins system
Anglo-Saxon/Anglo-Frisian : Transliterates Latin text into Anglo-Saxon runes
Examples:
>>> Transliterate().transliterate("Hƿæt Ƿe Gardena in geardagum", "Anglo-Saxon")
'ᚻᚹᚫᛏ ᚹᛖ ᚷᚪᚱᛞᛖᚾᚪ ᛁᚾ ᚷᛠᚱᛞᚪᚷᚢᛗ'
>>> Transliterate().transliterate("ᚩᚠᛏ ᛋᚳᚣᛚᛞ ᛋᚳᛖᚠᛁᛝ ᛋᚳᛠᚦᛖᚾᚪ ᚦᚱᛠᛏᚢᛗ", "Latin")
'oft scyld scefin sceathena threatum' | [
"Transliterates",
"Anglo",
"-",
"Saxon",
"runes",
"into",
"latin",
"and",
"vice",
"versa",
"."
] | ed9c025b7ec43c949481173251b70e05e4dffd27 | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/phonology/old_english/phonology.py#L157-L188 |
230,520 | StanfordVL/robosuite | robosuite/environments/sawyer_nut_assembly.py | SawyerNutAssembly.clear_objects | def clear_objects(self, obj):
"""
Clears objects with name @obj out of the task space. This is useful
for supporting task modes with single types of objects, as in
@self.single_object_mode without changing the model definition.
"""
for obj_name, obj_mjcf in self.mujoco_objects.items():
if obj_name == obj:
continue
else:
sim_state = self.sim.get_state()
# print(self.sim.model.get_joint_qpos_addr(obj_name))
sim_state.qpos[self.sim.model.get_joint_qpos_addr(obj_name)[0]] = 10
self.sim.set_state(sim_state)
self.sim.forward() | python | def clear_objects(self, obj):
for obj_name, obj_mjcf in self.mujoco_objects.items():
if obj_name == obj:
continue
else:
sim_state = self.sim.get_state()
# print(self.sim.model.get_joint_qpos_addr(obj_name))
sim_state.qpos[self.sim.model.get_joint_qpos_addr(obj_name)[0]] = 10
self.sim.set_state(sim_state)
self.sim.forward() | [
"def",
"clear_objects",
"(",
"self",
",",
"obj",
")",
":",
"for",
"obj_name",
",",
"obj_mjcf",
"in",
"self",
".",
"mujoco_objects",
".",
"items",
"(",
")",
":",
"if",
"obj_name",
"==",
"obj",
":",
"continue",
"else",
":",
"sim_state",
"=",
"self",
".",... | Clears objects with name @obj out of the task space. This is useful
for supporting task modes with single types of objects, as in
@self.single_object_mode without changing the model definition. | [
"Clears",
"objects",
"with",
"name"
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/sawyer_nut_assembly.py#L212-L226 |
230,521 | StanfordVL/robosuite | robosuite/environments/sawyer_nut_assembly.py | SawyerNutAssembly._check_contact | def _check_contact(self):
"""
Returns True if gripper is in contact with an object.
"""
collision = False
for contact in self.sim.data.contact[: self.sim.data.ncon]:
if (
self.sim.model.geom_id2name(contact.geom1) in self.finger_names
or self.sim.model.geom_id2name(contact.geom2) in self.finger_names
):
collision = True
break
return collision | python | def _check_contact(self):
collision = False
for contact in self.sim.data.contact[: self.sim.data.ncon]:
if (
self.sim.model.geom_id2name(contact.geom1) in self.finger_names
or self.sim.model.geom_id2name(contact.geom2) in self.finger_names
):
collision = True
break
return collision | [
"def",
"_check_contact",
"(",
"self",
")",
":",
"collision",
"=",
"False",
"for",
"contact",
"in",
"self",
".",
"sim",
".",
"data",
".",
"contact",
"[",
":",
"self",
".",
"sim",
".",
"data",
".",
"ncon",
"]",
":",
"if",
"(",
"self",
".",
"sim",
"... | Returns True if gripper is in contact with an object. | [
"Returns",
"True",
"if",
"gripper",
"is",
"in",
"contact",
"with",
"an",
"object",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/sawyer_nut_assembly.py#L466-L478 |
230,522 | StanfordVL/robosuite | robosuite/environments/sawyer_nut_assembly.py | SawyerNutAssembly._check_success | def _check_success(self):
"""
Returns True if task has been completed.
"""
# remember objects that are on the correct pegs
gripper_site_pos = self.sim.data.site_xpos[self.eef_site_id]
for i in range(len(self.ob_inits)):
obj_str = str(self.item_names[i]) + "0"
obj_pos = self.sim.data.body_xpos[self.obj_body_id[obj_str]]
dist = np.linalg.norm(gripper_site_pos - obj_pos)
r_reach = 1 - np.tanh(10.0 * dist)
self.objects_on_pegs[i] = int(self.on_peg(obj_pos, i) and r_reach < 0.6)
if self.single_object_mode > 0:
return np.sum(self.objects_on_pegs) > 0 # need one object on peg
# returns True if all objects are on correct pegs
return np.sum(self.objects_on_pegs) == len(self.ob_inits) | python | def _check_success(self):
# remember objects that are on the correct pegs
gripper_site_pos = self.sim.data.site_xpos[self.eef_site_id]
for i in range(len(self.ob_inits)):
obj_str = str(self.item_names[i]) + "0"
obj_pos = self.sim.data.body_xpos[self.obj_body_id[obj_str]]
dist = np.linalg.norm(gripper_site_pos - obj_pos)
r_reach = 1 - np.tanh(10.0 * dist)
self.objects_on_pegs[i] = int(self.on_peg(obj_pos, i) and r_reach < 0.6)
if self.single_object_mode > 0:
return np.sum(self.objects_on_pegs) > 0 # need one object on peg
# returns True if all objects are on correct pegs
return np.sum(self.objects_on_pegs) == len(self.ob_inits) | [
"def",
"_check_success",
"(",
"self",
")",
":",
"# remember objects that are on the correct pegs",
"gripper_site_pos",
"=",
"self",
".",
"sim",
".",
"data",
".",
"site_xpos",
"[",
"self",
".",
"eef_site_id",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"se... | Returns True if task has been completed. | [
"Returns",
"True",
"if",
"task",
"has",
"been",
"completed",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/sawyer_nut_assembly.py#L480-L498 |
230,523 | StanfordVL/robosuite | robosuite/environments/sawyer_stack.py | SawyerStack.staged_rewards | def staged_rewards(self):
"""
Helper function to return staged rewards based on current physical states.
Returns:
r_reach (float): reward for reaching and grasping
r_lift (float): reward for lifting and aligning
r_stack (float): reward for stacking
"""
# reaching is successful when the gripper site is close to
# the center of the cube
cubeA_pos = self.sim.data.body_xpos[self.cubeA_body_id]
cubeB_pos = self.sim.data.body_xpos[self.cubeB_body_id]
gripper_site_pos = self.sim.data.site_xpos[self.eef_site_id]
dist = np.linalg.norm(gripper_site_pos - cubeA_pos)
r_reach = (1 - np.tanh(10.0 * dist)) * 0.25
# collision checking
touch_left_finger = False
touch_right_finger = False
touch_cubeA_cubeB = False
for i in range(self.sim.data.ncon):
c = self.sim.data.contact[i]
if c.geom1 in self.l_finger_geom_ids and c.geom2 == self.cubeA_geom_id:
touch_left_finger = True
if c.geom1 == self.cubeA_geom_id and c.geom2 in self.l_finger_geom_ids:
touch_left_finger = True
if c.geom1 in self.r_finger_geom_ids and c.geom2 == self.cubeA_geom_id:
touch_right_finger = True
if c.geom1 == self.cubeA_geom_id and c.geom2 in self.r_finger_geom_ids:
touch_right_finger = True
if c.geom1 == self.cubeA_geom_id and c.geom2 == self.cubeB_geom_id:
touch_cubeA_cubeB = True
if c.geom1 == self.cubeB_geom_id and c.geom2 == self.cubeA_geom_id:
touch_cubeA_cubeB = True
# additional grasping reward
if touch_left_finger and touch_right_finger:
r_reach += 0.25
# lifting is successful when the cube is above the table top
# by a margin
cubeA_height = cubeA_pos[2]
table_height = self.table_full_size[2]
cubeA_lifted = cubeA_height > table_height + 0.04
r_lift = 1.0 if cubeA_lifted else 0.0
# Aligning is successful when cubeA is right above cubeB
if cubeA_lifted:
horiz_dist = np.linalg.norm(
np.array(cubeA_pos[:2]) - np.array(cubeB_pos[:2])
)
r_lift += 0.5 * (1 - np.tanh(horiz_dist))
# stacking is successful when the block is lifted and
# the gripper is not holding the object
r_stack = 0
not_touching = not touch_left_finger and not touch_right_finger
if not_touching and r_lift > 0 and touch_cubeA_cubeB:
r_stack = 2.0
return (r_reach, r_lift, r_stack) | python | def staged_rewards(self):
# reaching is successful when the gripper site is close to
# the center of the cube
cubeA_pos = self.sim.data.body_xpos[self.cubeA_body_id]
cubeB_pos = self.sim.data.body_xpos[self.cubeB_body_id]
gripper_site_pos = self.sim.data.site_xpos[self.eef_site_id]
dist = np.linalg.norm(gripper_site_pos - cubeA_pos)
r_reach = (1 - np.tanh(10.0 * dist)) * 0.25
# collision checking
touch_left_finger = False
touch_right_finger = False
touch_cubeA_cubeB = False
for i in range(self.sim.data.ncon):
c = self.sim.data.contact[i]
if c.geom1 in self.l_finger_geom_ids and c.geom2 == self.cubeA_geom_id:
touch_left_finger = True
if c.geom1 == self.cubeA_geom_id and c.geom2 in self.l_finger_geom_ids:
touch_left_finger = True
if c.geom1 in self.r_finger_geom_ids and c.geom2 == self.cubeA_geom_id:
touch_right_finger = True
if c.geom1 == self.cubeA_geom_id and c.geom2 in self.r_finger_geom_ids:
touch_right_finger = True
if c.geom1 == self.cubeA_geom_id and c.geom2 == self.cubeB_geom_id:
touch_cubeA_cubeB = True
if c.geom1 == self.cubeB_geom_id and c.geom2 == self.cubeA_geom_id:
touch_cubeA_cubeB = True
# additional grasping reward
if touch_left_finger and touch_right_finger:
r_reach += 0.25
# lifting is successful when the cube is above the table top
# by a margin
cubeA_height = cubeA_pos[2]
table_height = self.table_full_size[2]
cubeA_lifted = cubeA_height > table_height + 0.04
r_lift = 1.0 if cubeA_lifted else 0.0
# Aligning is successful when cubeA is right above cubeB
if cubeA_lifted:
horiz_dist = np.linalg.norm(
np.array(cubeA_pos[:2]) - np.array(cubeB_pos[:2])
)
r_lift += 0.5 * (1 - np.tanh(horiz_dist))
# stacking is successful when the block is lifted and
# the gripper is not holding the object
r_stack = 0
not_touching = not touch_left_finger and not touch_right_finger
if not_touching and r_lift > 0 and touch_cubeA_cubeB:
r_stack = 2.0
return (r_reach, r_lift, r_stack) | [
"def",
"staged_rewards",
"(",
"self",
")",
":",
"# reaching is successful when the gripper site is close to",
"# the center of the cube",
"cubeA_pos",
"=",
"self",
".",
"sim",
".",
"data",
".",
"body_xpos",
"[",
"self",
".",
"cubeA_body_id",
"]",
"cubeB_pos",
"=",
"se... | Helper function to return staged rewards based on current physical states.
Returns:
r_reach (float): reward for reaching and grasping
r_lift (float): reward for lifting and aligning
r_stack (float): reward for stacking | [
"Helper",
"function",
"to",
"return",
"staged",
"rewards",
"based",
"on",
"current",
"physical",
"states",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/sawyer_stack.py#L256-L318 |
230,524 | StanfordVL/robosuite | robosuite/models/tasks/nut_assembly_task.py | NutAssemblyTask.merge_objects | def merge_objects(self, mujoco_objects):
"""Adds physical objects to the MJCF model."""
self.mujoco_objects = mujoco_objects
self.objects = {} # xml manifestation
self.max_horizontal_radius = 0
for obj_name, obj_mjcf in mujoco_objects.items():
self.merge_asset(obj_mjcf)
# Load object
obj = obj_mjcf.get_collision(name=obj_name, site=True)
obj.append(new_joint(name=obj_name, type="free", damping="0.0005"))
self.objects[obj_name] = obj
self.worldbody.append(obj)
self.max_horizontal_radius = max(
self.max_horizontal_radius, obj_mjcf.get_horizontal_radius()
) | python | def merge_objects(self, mujoco_objects):
self.mujoco_objects = mujoco_objects
self.objects = {} # xml manifestation
self.max_horizontal_radius = 0
for obj_name, obj_mjcf in mujoco_objects.items():
self.merge_asset(obj_mjcf)
# Load object
obj = obj_mjcf.get_collision(name=obj_name, site=True)
obj.append(new_joint(name=obj_name, type="free", damping="0.0005"))
self.objects[obj_name] = obj
self.worldbody.append(obj)
self.max_horizontal_radius = max(
self.max_horizontal_radius, obj_mjcf.get_horizontal_radius()
) | [
"def",
"merge_objects",
"(",
"self",
",",
"mujoco_objects",
")",
":",
"self",
".",
"mujoco_objects",
"=",
"mujoco_objects",
"self",
".",
"objects",
"=",
"{",
"}",
"# xml manifestation",
"self",
".",
"max_horizontal_radius",
"=",
"0",
"for",
"obj_name",
",",
"o... | Adds physical objects to the MJCF model. | [
"Adds",
"physical",
"objects",
"to",
"the",
"MJCF",
"model",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/tasks/nut_assembly_task.py#L49-L64 |
230,525 | StanfordVL/robosuite | robosuite/models/grippers/gripper.py | Gripper.hide_visualization | def hide_visualization(self):
"""
Hides all visualization geoms and sites.
This should be called before rendering to agents
"""
for site_name in self.visualization_sites:
site = self.worldbody.find(".//site[@name='{}']".format(site_name))
site.set("rgba", "0 0 0 0")
for geom_name in self.visualization_geoms:
geom = self.worldbody.find(".//geom[@name='{}']".format(geom_name))
geom.set("rgba", "0 0 0 0") | python | def hide_visualization(self):
for site_name in self.visualization_sites:
site = self.worldbody.find(".//site[@name='{}']".format(site_name))
site.set("rgba", "0 0 0 0")
for geom_name in self.visualization_geoms:
geom = self.worldbody.find(".//geom[@name='{}']".format(geom_name))
geom.set("rgba", "0 0 0 0") | [
"def",
"hide_visualization",
"(",
"self",
")",
":",
"for",
"site_name",
"in",
"self",
".",
"visualization_sites",
":",
"site",
"=",
"self",
".",
"worldbody",
".",
"find",
"(",
"\".//site[@name='{}']\"",
".",
"format",
"(",
"site_name",
")",
")",
"site",
".",... | Hides all visualization geoms and sites.
This should be called before rendering to agents | [
"Hides",
"all",
"visualization",
"geoms",
"and",
"sites",
".",
"This",
"should",
"be",
"called",
"before",
"rendering",
"to",
"agents"
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/grippers/gripper.py#L81-L91 |
230,526 | StanfordVL/robosuite | robosuite/environments/baxter_lift.py | BaxterLift._load_model | def _load_model(self):
"""
Loads the arena and pot object.
"""
super()._load_model()
self.mujoco_robot.set_base_xpos([0, 0, 0])
# load model for table top workspace
self.mujoco_arena = TableArena(
table_full_size=self.table_full_size, table_friction=self.table_friction
)
if self.use_indicator_object:
self.mujoco_arena.add_pos_indicator()
# The sawyer robot has a pedestal, we want to align it with the table
self.mujoco_arena.set_origin([0.45 + self.table_full_size[0] / 2, 0, 0])
# task includes arena, robot, and objects of interest
self.model = TableTopTask(
self.mujoco_arena,
self.mujoco_robot,
self.mujoco_objects,
self.object_initializer,
)
self.model.place_objects() | python | def _load_model(self):
super()._load_model()
self.mujoco_robot.set_base_xpos([0, 0, 0])
# load model for table top workspace
self.mujoco_arena = TableArena(
table_full_size=self.table_full_size, table_friction=self.table_friction
)
if self.use_indicator_object:
self.mujoco_arena.add_pos_indicator()
# The sawyer robot has a pedestal, we want to align it with the table
self.mujoco_arena.set_origin([0.45 + self.table_full_size[0] / 2, 0, 0])
# task includes arena, robot, and objects of interest
self.model = TableTopTask(
self.mujoco_arena,
self.mujoco_robot,
self.mujoco_objects,
self.object_initializer,
)
self.model.place_objects() | [
"def",
"_load_model",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"_load_model",
"(",
")",
"self",
".",
"mujoco_robot",
".",
"set_base_xpos",
"(",
"[",
"0",
",",
"0",
",",
"0",
"]",
")",
"# load model for table top workspace",
"self",
".",
"mujoco_arena... | Loads the arena and pot object. | [
"Loads",
"the",
"arena",
"and",
"pot",
"object",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/baxter_lift.py#L73-L97 |
230,527 | StanfordVL/robosuite | robosuite/environments/baxter_lift.py | BaxterLift._pot_quat | def _pot_quat(self):
"""Returns the orientation of the pot."""
return T.convert_quat(self.sim.data.body_xquat[self.cube_body_id], to="xyzw") | python | def _pot_quat(self):
return T.convert_quat(self.sim.data.body_xquat[self.cube_body_id], to="xyzw") | [
"def",
"_pot_quat",
"(",
"self",
")",
":",
"return",
"T",
".",
"convert_quat",
"(",
"self",
".",
"sim",
".",
"data",
".",
"body_xquat",
"[",
"self",
".",
"cube_body_id",
"]",
",",
"to",
"=",
"\"xyzw\"",
")"
] | Returns the orientation of the pot. | [
"Returns",
"the",
"orientation",
"of",
"the",
"pot",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/baxter_lift.py#L199-L201 |
230,528 | StanfordVL/robosuite | robosuite/environments/baxter_lift.py | BaxterLift._check_success | def _check_success(self):
"""
Returns True if task is successfully completed
"""
# cube is higher than the table top above a margin
cube_height = self.sim.data.body_xpos[self.cube_body_id][2]
table_height = self.table_full_size[2]
return cube_height > table_height + 0.10 | python | def _check_success(self):
# cube is higher than the table top above a margin
cube_height = self.sim.data.body_xpos[self.cube_body_id][2]
table_height = self.table_full_size[2]
return cube_height > table_height + 0.10 | [
"def",
"_check_success",
"(",
"self",
")",
":",
"# cube is higher than the table top above a margin",
"cube_height",
"=",
"self",
".",
"sim",
".",
"data",
".",
"body_xpos",
"[",
"self",
".",
"cube_body_id",
"]",
"[",
"2",
"]",
"table_height",
"=",
"self",
".",
... | Returns True if task is successfully completed | [
"Returns",
"True",
"if",
"task",
"is",
"successfully",
"completed"
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/baxter_lift.py#L294-L301 |
230,529 | StanfordVL/robosuite | robosuite/wrappers/data_collection_wrapper.py | DataCollectionWrapper._start_new_episode | def _start_new_episode(self):
"""
Bookkeeping to do at the start of each new episode.
"""
# flush any data left over from the previous episode if any interactions have happened
if self.has_interaction:
self._flush()
# timesteps in current episode
self.t = 0
self.has_interaction = False | python | def _start_new_episode(self):
# flush any data left over from the previous episode if any interactions have happened
if self.has_interaction:
self._flush()
# timesteps in current episode
self.t = 0
self.has_interaction = False | [
"def",
"_start_new_episode",
"(",
"self",
")",
":",
"# flush any data left over from the previous episode if any interactions have happened",
"if",
"self",
".",
"has_interaction",
":",
"self",
".",
"_flush",
"(",
")",
"# timesteps in current episode",
"self",
".",
"t",
"=",... | Bookkeeping to do at the start of each new episode. | [
"Bookkeeping",
"to",
"do",
"at",
"the",
"start",
"of",
"each",
"new",
"episode",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/wrappers/data_collection_wrapper.py#L50-L61 |
230,530 | StanfordVL/robosuite | robosuite/wrappers/data_collection_wrapper.py | DataCollectionWrapper._flush | def _flush(self):
"""
Method to flush internal state to disk.
"""
t1, t2 = str(time.time()).split(".")
state_path = os.path.join(self.ep_directory, "state_{}_{}.npz".format(t1, t2))
if hasattr(self.env, "unwrapped"):
env_name = self.env.unwrapped.__class__.__name__
else:
env_name = self.env.__class__.__name__
np.savez(
state_path,
states=np.array(self.states),
action_infos=self.action_infos,
env=env_name,
)
self.states = []
self.action_infos = [] | python | def _flush(self):
t1, t2 = str(time.time()).split(".")
state_path = os.path.join(self.ep_directory, "state_{}_{}.npz".format(t1, t2))
if hasattr(self.env, "unwrapped"):
env_name = self.env.unwrapped.__class__.__name__
else:
env_name = self.env.__class__.__name__
np.savez(
state_path,
states=np.array(self.states),
action_infos=self.action_infos,
env=env_name,
)
self.states = []
self.action_infos = [] | [
"def",
"_flush",
"(",
"self",
")",
":",
"t1",
",",
"t2",
"=",
"str",
"(",
"time",
".",
"time",
"(",
")",
")",
".",
"split",
"(",
"\".\"",
")",
"state_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"ep_directory",
",",
"\"state_{}_{... | Method to flush internal state to disk. | [
"Method",
"to",
"flush",
"internal",
"state",
"to",
"disk",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/wrappers/data_collection_wrapper.py#L84-L101 |
230,531 | StanfordVL/robosuite | robosuite/models/base.py | MujocoXML.resolve_asset_dependency | def resolve_asset_dependency(self):
"""
Converts every file dependency into absolute path so when we merge we don't break things.
"""
for node in self.asset.findall("./*[@file]"):
file = node.get("file")
abs_path = os.path.abspath(self.folder)
abs_path = os.path.join(abs_path, file)
node.set("file", abs_path) | python | def resolve_asset_dependency(self):
for node in self.asset.findall("./*[@file]"):
file = node.get("file")
abs_path = os.path.abspath(self.folder)
abs_path = os.path.join(abs_path, file)
node.set("file", abs_path) | [
"def",
"resolve_asset_dependency",
"(",
"self",
")",
":",
"for",
"node",
"in",
"self",
".",
"asset",
".",
"findall",
"(",
"\"./*[@file]\"",
")",
":",
"file",
"=",
"node",
".",
"get",
"(",
"\"file\"",
")",
"abs_path",
"=",
"os",
".",
"path",
".",
"abspa... | Converts every file dependency into absolute path so when we merge we don't break things. | [
"Converts",
"every",
"file",
"dependency",
"into",
"absolute",
"path",
"so",
"when",
"we",
"merge",
"we",
"don",
"t",
"break",
"things",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/base.py#L37-L46 |
230,532 | StanfordVL/robosuite | robosuite/models/base.py | MujocoXML.create_default_element | def create_default_element(self, name):
"""
Creates a <@name/> tag under root if there is none.
"""
found = self.root.find(name)
if found is not None:
return found
ele = ET.Element(name)
self.root.append(ele)
return ele | python | def create_default_element(self, name):
found = self.root.find(name)
if found is not None:
return found
ele = ET.Element(name)
self.root.append(ele)
return ele | [
"def",
"create_default_element",
"(",
"self",
",",
"name",
")",
":",
"found",
"=",
"self",
".",
"root",
".",
"find",
"(",
"name",
")",
"if",
"found",
"is",
"not",
"None",
":",
"return",
"found",
"ele",
"=",
"ET",
".",
"Element",
"(",
"name",
")",
"... | Creates a <@name/> tag under root if there is none. | [
"Creates",
"a",
"<"
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/base.py#L48-L58 |
230,533 | StanfordVL/robosuite | robosuite/models/base.py | MujocoXML.merge | def merge(self, other, merge_body=True):
"""
Default merge method.
Args:
other: another MujocoXML instance
raises XML error if @other is not a MujocoXML instance.
merges <worldbody/>, <actuator/> and <asset/> of @other into @self
merge_body: True if merging child bodies of @other. Defaults to True.
"""
if not isinstance(other, MujocoXML):
raise XMLError("{} is not a MujocoXML instance.".format(type(other)))
if merge_body:
for body in other.worldbody:
self.worldbody.append(body)
self.merge_asset(other)
for one_actuator in other.actuator:
self.actuator.append(one_actuator)
for one_equality in other.equality:
self.equality.append(one_equality)
for one_contact in other.contact:
self.contact.append(one_contact)
for one_default in other.default:
self.default.append(one_default) | python | def merge(self, other, merge_body=True):
if not isinstance(other, MujocoXML):
raise XMLError("{} is not a MujocoXML instance.".format(type(other)))
if merge_body:
for body in other.worldbody:
self.worldbody.append(body)
self.merge_asset(other)
for one_actuator in other.actuator:
self.actuator.append(one_actuator)
for one_equality in other.equality:
self.equality.append(one_equality)
for one_contact in other.contact:
self.contact.append(one_contact)
for one_default in other.default:
self.default.append(one_default) | [
"def",
"merge",
"(",
"self",
",",
"other",
",",
"merge_body",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"MujocoXML",
")",
":",
"raise",
"XMLError",
"(",
"\"{} is not a MujocoXML instance.\"",
".",
"format",
"(",
"type",
"(",
"oth... | Default merge method.
Args:
other: another MujocoXML instance
raises XML error if @other is not a MujocoXML instance.
merges <worldbody/>, <actuator/> and <asset/> of @other into @self
merge_body: True if merging child bodies of @other. Defaults to True. | [
"Default",
"merge",
"method",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/base.py#L60-L83 |
230,534 | StanfordVL/robosuite | robosuite/models/base.py | MujocoXML.get_model | def get_model(self, mode="mujoco_py"):
"""
Returns a MjModel instance from the current xml tree.
"""
available_modes = ["mujoco_py"]
with io.StringIO() as string:
string.write(ET.tostring(self.root, encoding="unicode"))
if mode == "mujoco_py":
from mujoco_py import load_model_from_xml
model = load_model_from_xml(string.getvalue())
return model
raise ValueError(
"Unkown model mode: {}. Available options are: {}".format(
mode, ",".join(available_modes)
)
) | python | def get_model(self, mode="mujoco_py"):
available_modes = ["mujoco_py"]
with io.StringIO() as string:
string.write(ET.tostring(self.root, encoding="unicode"))
if mode == "mujoco_py":
from mujoco_py import load_model_from_xml
model = load_model_from_xml(string.getvalue())
return model
raise ValueError(
"Unkown model mode: {}. Available options are: {}".format(
mode, ",".join(available_modes)
)
) | [
"def",
"get_model",
"(",
"self",
",",
"mode",
"=",
"\"mujoco_py\"",
")",
":",
"available_modes",
"=",
"[",
"\"mujoco_py\"",
"]",
"with",
"io",
".",
"StringIO",
"(",
")",
"as",
"string",
":",
"string",
".",
"write",
"(",
"ET",
".",
"tostring",
"(",
"sel... | Returns a MjModel instance from the current xml tree. | [
"Returns",
"a",
"MjModel",
"instance",
"from",
"the",
"current",
"xml",
"tree",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/base.py#L86-L103 |
230,535 | StanfordVL/robosuite | robosuite/models/base.py | MujocoXML.get_xml | def get_xml(self):
"""
Returns a string of the MJCF XML file.
"""
with io.StringIO() as string:
string.write(ET.tostring(self.root, encoding="unicode"))
return string.getvalue() | python | def get_xml(self):
with io.StringIO() as string:
string.write(ET.tostring(self.root, encoding="unicode"))
return string.getvalue() | [
"def",
"get_xml",
"(",
"self",
")",
":",
"with",
"io",
".",
"StringIO",
"(",
")",
"as",
"string",
":",
"string",
".",
"write",
"(",
"ET",
".",
"tostring",
"(",
"self",
".",
"root",
",",
"encoding",
"=",
"\"unicode\"",
")",
")",
"return",
"string",
... | Returns a string of the MJCF XML file. | [
"Returns",
"a",
"string",
"of",
"the",
"MJCF",
"XML",
"file",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/base.py#L105-L111 |
230,536 | StanfordVL/robosuite | robosuite/models/base.py | MujocoXML.save_model | def save_model(self, fname, pretty=False):
"""
Saves the xml to file.
Args:
fname: output file location
pretty: attempts!! to pretty print the output
"""
with open(fname, "w") as f:
xml_str = ET.tostring(self.root, encoding="unicode")
if pretty:
# TODO: get a better pretty print library
parsed_xml = xml.dom.minidom.parseString(xml_str)
xml_str = parsed_xml.toprettyxml(newl="")
f.write(xml_str) | python | def save_model(self, fname, pretty=False):
with open(fname, "w") as f:
xml_str = ET.tostring(self.root, encoding="unicode")
if pretty:
# TODO: get a better pretty print library
parsed_xml = xml.dom.minidom.parseString(xml_str)
xml_str = parsed_xml.toprettyxml(newl="")
f.write(xml_str) | [
"def",
"save_model",
"(",
"self",
",",
"fname",
",",
"pretty",
"=",
"False",
")",
":",
"with",
"open",
"(",
"fname",
",",
"\"w\"",
")",
"as",
"f",
":",
"xml_str",
"=",
"ET",
".",
"tostring",
"(",
"self",
".",
"root",
",",
"encoding",
"=",
"\"unicod... | Saves the xml to file.
Args:
fname: output file location
pretty: attempts!! to pretty print the output | [
"Saves",
"the",
"xml",
"to",
"file",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/base.py#L113-L127 |
230,537 | StanfordVL/robosuite | robosuite/models/base.py | MujocoXML.merge_asset | def merge_asset(self, other):
"""
Useful for merging other files in a custom logic.
"""
for asset in other.asset:
asset_name = asset.get("name")
asset_type = asset.tag
# Avoids duplication
pattern = "./{}[@name='{}']".format(asset_type, asset_name)
if self.asset.find(pattern) is None:
self.asset.append(asset) | python | def merge_asset(self, other):
for asset in other.asset:
asset_name = asset.get("name")
asset_type = asset.tag
# Avoids duplication
pattern = "./{}[@name='{}']".format(asset_type, asset_name)
if self.asset.find(pattern) is None:
self.asset.append(asset) | [
"def",
"merge_asset",
"(",
"self",
",",
"other",
")",
":",
"for",
"asset",
"in",
"other",
".",
"asset",
":",
"asset_name",
"=",
"asset",
".",
"get",
"(",
"\"name\"",
")",
"asset_type",
"=",
"asset",
".",
"tag",
"# Avoids duplication",
"pattern",
"=",
"\"... | Useful for merging other files in a custom logic. | [
"Useful",
"for",
"merging",
"other",
"files",
"in",
"a",
"custom",
"logic",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/base.py#L129-L139 |
230,538 | StanfordVL/robosuite | robosuite/wrappers/gym_wrapper.py | GymWrapper._flatten_obs | def _flatten_obs(self, obs_dict, verbose=False):
"""
Filters keys of interest out and concatenate the information.
Args:
obs_dict: ordered dictionary of observations
"""
ob_lst = []
for key in obs_dict:
if key in self.keys:
if verbose:
print("adding key: {}".format(key))
ob_lst.append(obs_dict[key])
return np.concatenate(ob_lst) | python | def _flatten_obs(self, obs_dict, verbose=False):
ob_lst = []
for key in obs_dict:
if key in self.keys:
if verbose:
print("adding key: {}".format(key))
ob_lst.append(obs_dict[key])
return np.concatenate(ob_lst) | [
"def",
"_flatten_obs",
"(",
"self",
",",
"obs_dict",
",",
"verbose",
"=",
"False",
")",
":",
"ob_lst",
"=",
"[",
"]",
"for",
"key",
"in",
"obs_dict",
":",
"if",
"key",
"in",
"self",
".",
"keys",
":",
"if",
"verbose",
":",
"print",
"(",
"\"adding key:... | Filters keys of interest out and concatenate the information.
Args:
obs_dict: ordered dictionary of observations | [
"Filters",
"keys",
"of",
"interest",
"out",
"and",
"concatenate",
"the",
"information",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/wrappers/gym_wrapper.py#L41-L54 |
230,539 | StanfordVL/robosuite | robosuite/models/tasks/pick_place_task.py | PickPlaceTask.merge_visual | def merge_visual(self, mujoco_objects):
"""Adds visual objects to the MJCF model."""
self.visual_obj_mjcf = []
for obj_name, obj_mjcf in mujoco_objects.items():
self.merge_asset(obj_mjcf)
# Load object
obj = obj_mjcf.get_visual(name=obj_name, site=False)
self.visual_obj_mjcf.append(obj)
self.worldbody.append(obj) | python | def merge_visual(self, mujoco_objects):
self.visual_obj_mjcf = []
for obj_name, obj_mjcf in mujoco_objects.items():
self.merge_asset(obj_mjcf)
# Load object
obj = obj_mjcf.get_visual(name=obj_name, site=False)
self.visual_obj_mjcf.append(obj)
self.worldbody.append(obj) | [
"def",
"merge_visual",
"(",
"self",
",",
"mujoco_objects",
")",
":",
"self",
".",
"visual_obj_mjcf",
"=",
"[",
"]",
"for",
"obj_name",
",",
"obj_mjcf",
"in",
"mujoco_objects",
".",
"items",
"(",
")",
":",
"self",
".",
"merge_asset",
"(",
"obj_mjcf",
")",
... | Adds visual objects to the MJCF model. | [
"Adds",
"visual",
"objects",
"to",
"the",
"MJCF",
"model",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/tasks/pick_place_task.py#L71-L79 |
230,540 | StanfordVL/robosuite | robosuite/models/tasks/pick_place_task.py | PickPlaceTask.place_visual | def place_visual(self):
"""Places visual objects randomly until no collisions or max iterations hit."""
index = 0
bin_pos = string_to_array(self.bin2_body.get("pos"))
bin_size = self.bin_size
for _, obj_mjcf in self.visual_objects:
bin_x_low = bin_pos[0]
bin_y_low = bin_pos[1]
if index == 0 or index == 2:
bin_x_low -= bin_size[0] / 2
if index < 2:
bin_y_low -= bin_size[1] / 2
bin_x_high = bin_x_low + bin_size[0] / 2
bin_y_high = bin_y_low + bin_size[1] / 2
bottom_offset = obj_mjcf.get_bottom_offset()
bin_range = [bin_x_low + bin_x_high, bin_y_low + bin_y_high, 2 * bin_pos[2]]
bin_center = np.array(bin_range) / 2.0
pos = bin_center - bottom_offset
self.visual_obj_mjcf[index].set("pos", array_to_string(pos))
index += 1 | python | def place_visual(self):
index = 0
bin_pos = string_to_array(self.bin2_body.get("pos"))
bin_size = self.bin_size
for _, obj_mjcf in self.visual_objects:
bin_x_low = bin_pos[0]
bin_y_low = bin_pos[1]
if index == 0 or index == 2:
bin_x_low -= bin_size[0] / 2
if index < 2:
bin_y_low -= bin_size[1] / 2
bin_x_high = bin_x_low + bin_size[0] / 2
bin_y_high = bin_y_low + bin_size[1] / 2
bottom_offset = obj_mjcf.get_bottom_offset()
bin_range = [bin_x_low + bin_x_high, bin_y_low + bin_y_high, 2 * bin_pos[2]]
bin_center = np.array(bin_range) / 2.0
pos = bin_center - bottom_offset
self.visual_obj_mjcf[index].set("pos", array_to_string(pos))
index += 1 | [
"def",
"place_visual",
"(",
"self",
")",
":",
"index",
"=",
"0",
"bin_pos",
"=",
"string_to_array",
"(",
"self",
".",
"bin2_body",
".",
"get",
"(",
"\"pos\"",
")",
")",
"bin_size",
"=",
"self",
".",
"bin_size",
"for",
"_",
",",
"obj_mjcf",
"in",
"self"... | Places visual objects randomly until no collisions or max iterations hit. | [
"Places",
"visual",
"objects",
"randomly",
"until",
"no",
"collisions",
"or",
"max",
"iterations",
"hit",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/tasks/pick_place_task.py#L130-L154 |
230,541 | StanfordVL/robosuite | robosuite/environments/sawyer_lift.py | SawyerLift._load_model | def _load_model(self):
"""
Loads an xml model, puts it in self.model
"""
super()._load_model()
self.mujoco_robot.set_base_xpos([0, 0, 0])
# load model for table top workspace
self.mujoco_arena = TableArena(
table_full_size=self.table_full_size, table_friction=self.table_friction
)
if self.use_indicator_object:
self.mujoco_arena.add_pos_indicator()
# The sawyer robot has a pedestal, we want to align it with the table
self.mujoco_arena.set_origin([0.16 + self.table_full_size[0] / 2, 0, 0])
# initialize objects of interest
cube = BoxObject(
size_min=[0.020, 0.020, 0.020], # [0.015, 0.015, 0.015],
size_max=[0.022, 0.022, 0.022], # [0.018, 0.018, 0.018])
rgba=[1, 0, 0, 1],
)
self.mujoco_objects = OrderedDict([("cube", cube)])
# task includes arena, robot, and objects of interest
self.model = TableTopTask(
self.mujoco_arena,
self.mujoco_robot,
self.mujoco_objects,
initializer=self.placement_initializer,
)
self.model.place_objects() | python | def _load_model(self):
super()._load_model()
self.mujoco_robot.set_base_xpos([0, 0, 0])
# load model for table top workspace
self.mujoco_arena = TableArena(
table_full_size=self.table_full_size, table_friction=self.table_friction
)
if self.use_indicator_object:
self.mujoco_arena.add_pos_indicator()
# The sawyer robot has a pedestal, we want to align it with the table
self.mujoco_arena.set_origin([0.16 + self.table_full_size[0] / 2, 0, 0])
# initialize objects of interest
cube = BoxObject(
size_min=[0.020, 0.020, 0.020], # [0.015, 0.015, 0.015],
size_max=[0.022, 0.022, 0.022], # [0.018, 0.018, 0.018])
rgba=[1, 0, 0, 1],
)
self.mujoco_objects = OrderedDict([("cube", cube)])
# task includes arena, robot, and objects of interest
self.model = TableTopTask(
self.mujoco_arena,
self.mujoco_robot,
self.mujoco_objects,
initializer=self.placement_initializer,
)
self.model.place_objects() | [
"def",
"_load_model",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"_load_model",
"(",
")",
"self",
".",
"mujoco_robot",
".",
"set_base_xpos",
"(",
"[",
"0",
",",
"0",
",",
"0",
"]",
")",
"# load model for table top workspace",
"self",
".",
"mujoco_arena... | Loads an xml model, puts it in self.model | [
"Loads",
"an",
"xml",
"model",
"puts",
"it",
"in",
"self",
".",
"model"
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/sawyer_lift.py#L138-L170 |
230,542 | StanfordVL/robosuite | robosuite/utils/mujoco_py_renderer.py | MujocoPyRenderer.set_camera | def set_camera(self, camera_id):
"""
Set the camera view to the specified camera ID.
"""
self.viewer.cam.fixedcamid = camera_id
self.viewer.cam.type = const.CAMERA_FIXED | python | def set_camera(self, camera_id):
self.viewer.cam.fixedcamid = camera_id
self.viewer.cam.type = const.CAMERA_FIXED | [
"def",
"set_camera",
"(",
"self",
",",
"camera_id",
")",
":",
"self",
".",
"viewer",
".",
"cam",
".",
"fixedcamid",
"=",
"camera_id",
"self",
".",
"viewer",
".",
"cam",
".",
"type",
"=",
"const",
".",
"CAMERA_FIXED"
] | Set the camera view to the specified camera ID. | [
"Set",
"the",
"camera",
"view",
"to",
"the",
"specified",
"camera",
"ID",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/utils/mujoco_py_renderer.py#L45-L50 |
230,543 | StanfordVL/robosuite | robosuite/utils/mujoco_py_renderer.py | MujocoPyRenderer.add_keypress_callback | def add_keypress_callback(self, key, fn):
"""
Allows for custom callback functions for the viewer. Called on key down.
Parameter 'any' will ensure that the callback is called on any key down,
and block default mujoco viewer callbacks from executing, except for
the ESC callback to close the viewer.
"""
self.viewer.keypress[key].append(fn) | python | def add_keypress_callback(self, key, fn):
self.viewer.keypress[key].append(fn) | [
"def",
"add_keypress_callback",
"(",
"self",
",",
"key",
",",
"fn",
")",
":",
"self",
".",
"viewer",
".",
"keypress",
"[",
"key",
"]",
".",
"append",
"(",
"fn",
")"
] | Allows for custom callback functions for the viewer. Called on key down.
Parameter 'any' will ensure that the callback is called on any key down,
and block default mujoco viewer callbacks from executing, except for
the ESC callback to close the viewer. | [
"Allows",
"for",
"custom",
"callback",
"functions",
"for",
"the",
"viewer",
".",
"Called",
"on",
"key",
"down",
".",
"Parameter",
"any",
"will",
"ensure",
"that",
"the",
"callback",
"is",
"called",
"on",
"any",
"key",
"down",
"and",
"block",
"default",
"mu... | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/utils/mujoco_py_renderer.py#L63-L70 |
230,544 | StanfordVL/robosuite | robosuite/utils/mujoco_py_renderer.py | MujocoPyRenderer.add_keyup_callback | def add_keyup_callback(self, key, fn):
"""
Allows for custom callback functions for the viewer. Called on key up.
Parameter 'any' will ensure that the callback is called on any key up,
and block default mujoco viewer callbacks from executing, except for
the ESC callback to close the viewer.
"""
self.viewer.keyup[key].append(fn) | python | def add_keyup_callback(self, key, fn):
self.viewer.keyup[key].append(fn) | [
"def",
"add_keyup_callback",
"(",
"self",
",",
"key",
",",
"fn",
")",
":",
"self",
".",
"viewer",
".",
"keyup",
"[",
"key",
"]",
".",
"append",
"(",
"fn",
")"
] | Allows for custom callback functions for the viewer. Called on key up.
Parameter 'any' will ensure that the callback is called on any key up,
and block default mujoco viewer callbacks from executing, except for
the ESC callback to close the viewer. | [
"Allows",
"for",
"custom",
"callback",
"functions",
"for",
"the",
"viewer",
".",
"Called",
"on",
"key",
"up",
".",
"Parameter",
"any",
"will",
"ensure",
"that",
"the",
"callback",
"is",
"called",
"on",
"any",
"key",
"up",
"and",
"block",
"default",
"mujoco... | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/utils/mujoco_py_renderer.py#L72-L79 |
230,545 | StanfordVL/robosuite | robosuite/utils/mujoco_py_renderer.py | MujocoPyRenderer.add_keyrepeat_callback | def add_keyrepeat_callback(self, key, fn):
"""
Allows for custom callback functions for the viewer. Called on key repeat.
Parameter 'any' will ensure that the callback is called on any key repeat,
and block default mujoco viewer callbacks from executing, except for
the ESC callback to close the viewer.
"""
self.viewer.keyrepeat[key].append(fn) | python | def add_keyrepeat_callback(self, key, fn):
self.viewer.keyrepeat[key].append(fn) | [
"def",
"add_keyrepeat_callback",
"(",
"self",
",",
"key",
",",
"fn",
")",
":",
"self",
".",
"viewer",
".",
"keyrepeat",
"[",
"key",
"]",
".",
"append",
"(",
"fn",
")"
] | Allows for custom callback functions for the viewer. Called on key repeat.
Parameter 'any' will ensure that the callback is called on any key repeat,
and block default mujoco viewer callbacks from executing, except for
the ESC callback to close the viewer. | [
"Allows",
"for",
"custom",
"callback",
"functions",
"for",
"the",
"viewer",
".",
"Called",
"on",
"key",
"repeat",
".",
"Parameter",
"any",
"will",
"ensure",
"that",
"the",
"callback",
"is",
"called",
"on",
"any",
"key",
"repeat",
"and",
"block",
"default",
... | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/utils/mujoco_py_renderer.py#L81-L88 |
230,546 | StanfordVL/robosuite | robosuite/wrappers/demo_sampler_wrapper.py | DemoSamplerWrapper.reset | def reset(self):
"""
Logic for sampling a state from the demonstration and resetting
the simulation to that state.
"""
state = self.sample()
if state is None:
# None indicates that a normal env reset should occur
return self.env.reset()
else:
if self.need_xml:
# reset the simulation from the model if necessary
state, xml = state
self.env.reset_from_xml_string(xml)
if isinstance(state, tuple):
state = state[0]
# force simulator state to one from the demo
self.sim.set_state_from_flattened(state)
self.sim.forward()
return self.env._get_observation() | python | def reset(self):
state = self.sample()
if state is None:
# None indicates that a normal env reset should occur
return self.env.reset()
else:
if self.need_xml:
# reset the simulation from the model if necessary
state, xml = state
self.env.reset_from_xml_string(xml)
if isinstance(state, tuple):
state = state[0]
# force simulator state to one from the demo
self.sim.set_state_from_flattened(state)
self.sim.forward()
return self.env._get_observation() | [
"def",
"reset",
"(",
"self",
")",
":",
"state",
"=",
"self",
".",
"sample",
"(",
")",
"if",
"state",
"is",
"None",
":",
"# None indicates that a normal env reset should occur",
"return",
"self",
".",
"env",
".",
"reset",
"(",
")",
"else",
":",
"if",
"self"... | Logic for sampling a state from the demonstration and resetting
the simulation to that state. | [
"Logic",
"for",
"sampling",
"a",
"state",
"from",
"the",
"demonstration",
"and",
"resetting",
"the",
"simulation",
"to",
"that",
"state",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/wrappers/demo_sampler_wrapper.py#L143-L165 |
230,547 | StanfordVL/robosuite | robosuite/wrappers/demo_sampler_wrapper.py | DemoSamplerWrapper.sample | def sample(self):
"""
This is the core sampling method. Samples a state from a
demonstration, in accordance with the configuration.
"""
# chooses a sampling scheme randomly based on the mixing ratios
seed = random.uniform(0, 1)
ratio = np.cumsum(self.scheme_ratios)
ratio = ratio > seed
for i, v in enumerate(ratio):
if v:
break
sample_method = getattr(self, self.sample_method_dict[self.sampling_schemes[i]])
return sample_method() | python | def sample(self):
# chooses a sampling scheme randomly based on the mixing ratios
seed = random.uniform(0, 1)
ratio = np.cumsum(self.scheme_ratios)
ratio = ratio > seed
for i, v in enumerate(ratio):
if v:
break
sample_method = getattr(self, self.sample_method_dict[self.sampling_schemes[i]])
return sample_method() | [
"def",
"sample",
"(",
"self",
")",
":",
"# chooses a sampling scheme randomly based on the mixing ratios",
"seed",
"=",
"random",
".",
"uniform",
"(",
"0",
",",
"1",
")",
"ratio",
"=",
"np",
".",
"cumsum",
"(",
"self",
".",
"scheme_ratios",
")",
"ratio",
"=",
... | This is the core sampling method. Samples a state from a
demonstration, in accordance with the configuration. | [
"This",
"is",
"the",
"core",
"sampling",
"method",
".",
"Samples",
"a",
"state",
"from",
"a",
"demonstration",
"in",
"accordance",
"with",
"the",
"configuration",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/wrappers/demo_sampler_wrapper.py#L167-L182 |
230,548 | StanfordVL/robosuite | robosuite/wrappers/demo_sampler_wrapper.py | DemoSamplerWrapper._xml_for_episode_index | def _xml_for_episode_index(self, ep_ind):
"""
Helper method to retrieve the corresponding model xml string
for the passed episode index.
"""
# read the model xml, using the metadata stored in the attribute for this episode
model_file = self.demo_file["data/{}".format(ep_ind)].attrs["model_file"]
model_path = os.path.join(self.demo_path, "models", model_file)
with open(model_path, "r") as model_f:
model_xml = model_f.read()
return model_xml | python | def _xml_for_episode_index(self, ep_ind):
# read the model xml, using the metadata stored in the attribute for this episode
model_file = self.demo_file["data/{}".format(ep_ind)].attrs["model_file"]
model_path = os.path.join(self.demo_path, "models", model_file)
with open(model_path, "r") as model_f:
model_xml = model_f.read()
return model_xml | [
"def",
"_xml_for_episode_index",
"(",
"self",
",",
"ep_ind",
")",
":",
"# read the model xml, using the metadata stored in the attribute for this episode",
"model_file",
"=",
"self",
".",
"demo_file",
"[",
"\"data/{}\"",
".",
"format",
"(",
"ep_ind",
")",
"]",
".",
"att... | Helper method to retrieve the corresponding model xml string
for the passed episode index. | [
"Helper",
"method",
"to",
"retrieve",
"the",
"corresponding",
"model",
"xml",
"string",
"for",
"the",
"passed",
"episode",
"index",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/wrappers/demo_sampler_wrapper.py#L280-L291 |
230,549 | StanfordVL/robosuite | robosuite/devices/spacemouse.py | to_int16 | def to_int16(y1, y2):
"""Convert two 8 bit bytes to a signed 16 bit integer."""
x = (y1) | (y2 << 8)
if x >= 32768:
x = -(65536 - x)
return x | python | def to_int16(y1, y2):
x = (y1) | (y2 << 8)
if x >= 32768:
x = -(65536 - x)
return x | [
"def",
"to_int16",
"(",
"y1",
",",
"y2",
")",
":",
"x",
"=",
"(",
"y1",
")",
"|",
"(",
"y2",
"<<",
"8",
")",
"if",
"x",
">=",
"32768",
":",
"x",
"=",
"-",
"(",
"65536",
"-",
"x",
")",
"return",
"x"
] | Convert two 8 bit bytes to a signed 16 bit integer. | [
"Convert",
"two",
"8",
"bit",
"bytes",
"to",
"a",
"signed",
"16",
"bit",
"integer",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/devices/spacemouse.py#L45-L50 |
230,550 | StanfordVL/robosuite | robosuite/devices/spacemouse.py | scale_to_control | def scale_to_control(x, axis_scale=350., min_v=-1.0, max_v=1.0):
"""Normalize raw HID readings to target range."""
x = x / axis_scale
x = min(max(x, min_v), max_v)
return x | python | def scale_to_control(x, axis_scale=350., min_v=-1.0, max_v=1.0):
x = x / axis_scale
x = min(max(x, min_v), max_v)
return x | [
"def",
"scale_to_control",
"(",
"x",
",",
"axis_scale",
"=",
"350.",
",",
"min_v",
"=",
"-",
"1.0",
",",
"max_v",
"=",
"1.0",
")",
":",
"x",
"=",
"x",
"/",
"axis_scale",
"x",
"=",
"min",
"(",
"max",
"(",
"x",
",",
"min_v",
")",
",",
"max_v",
")... | Normalize raw HID readings to target range. | [
"Normalize",
"raw",
"HID",
"readings",
"to",
"target",
"range",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/devices/spacemouse.py#L53-L57 |
230,551 | StanfordVL/robosuite | robosuite/devices/spacemouse.py | SpaceMouse.get_controller_state | def get_controller_state(self):
"""Returns the current state of the 3d mouse, a dictionary of pos, orn, grasp, and reset."""
dpos = self.control[:3] * 0.005
roll, pitch, yaw = self.control[3:] * 0.005
self.grasp = self.control_gripper
# convert RPY to an absolute orientation
drot1 = rotation_matrix(angle=-pitch, direction=[1., 0, 0], point=None)[:3, :3]
drot2 = rotation_matrix(angle=roll, direction=[0, 1., 0], point=None)[:3, :3]
drot3 = rotation_matrix(angle=yaw, direction=[0, 0, 1.], point=None)[:3, :3]
self.rotation = self.rotation.dot(drot1.dot(drot2.dot(drot3)))
return dict(
dpos=dpos, rotation=self.rotation, grasp=self.grasp, reset=self._reset_state
) | python | def get_controller_state(self):
dpos = self.control[:3] * 0.005
roll, pitch, yaw = self.control[3:] * 0.005
self.grasp = self.control_gripper
# convert RPY to an absolute orientation
drot1 = rotation_matrix(angle=-pitch, direction=[1., 0, 0], point=None)[:3, :3]
drot2 = rotation_matrix(angle=roll, direction=[0, 1., 0], point=None)[:3, :3]
drot3 = rotation_matrix(angle=yaw, direction=[0, 0, 1.], point=None)[:3, :3]
self.rotation = self.rotation.dot(drot1.dot(drot2.dot(drot3)))
return dict(
dpos=dpos, rotation=self.rotation, grasp=self.grasp, reset=self._reset_state
) | [
"def",
"get_controller_state",
"(",
"self",
")",
":",
"dpos",
"=",
"self",
".",
"control",
"[",
":",
"3",
"]",
"*",
"0.005",
"roll",
",",
"pitch",
",",
"yaw",
"=",
"self",
".",
"control",
"[",
"3",
":",
"]",
"*",
"0.005",
"self",
".",
"grasp",
"=... | Returns the current state of the 3d mouse, a dictionary of pos, orn, grasp, and reset. | [
"Returns",
"the",
"current",
"state",
"of",
"the",
"3d",
"mouse",
"a",
"dictionary",
"of",
"pos",
"orn",
"grasp",
"and",
"reset",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/devices/spacemouse.py#L138-L153 |
230,552 | StanfordVL/robosuite | robosuite/devices/spacemouse.py | SpaceMouse.run | def run(self):
"""Listener method that keeps pulling new messages."""
t_last_click = -1
while True:
d = self.device.read(13)
if d is not None and self._enabled:
if d[0] == 1: ## readings from 6-DoF sensor
self.y = convert(d[1], d[2])
self.x = convert(d[3], d[4])
self.z = convert(d[5], d[6]) * -1.0
self.roll = convert(d[7], d[8])
self.pitch = convert(d[9], d[10])
self.yaw = convert(d[11], d[12])
self._control = [
self.x,
self.y,
self.z,
self.roll,
self.pitch,
self.yaw,
]
elif d[0] == 3: ## readings from the side buttons
# press left button
if d[1] == 1:
t_click = time.time()
elapsed_time = t_click - t_last_click
t_last_click = t_click
self.single_click_and_hold = True
# release left button
if d[1] == 0:
self.single_click_and_hold = False
# right button is for reset
if d[1] == 2:
self._reset_state = 1
self._enabled = False
self._reset_internal_state() | python | def run(self):
t_last_click = -1
while True:
d = self.device.read(13)
if d is not None and self._enabled:
if d[0] == 1: ## readings from 6-DoF sensor
self.y = convert(d[1], d[2])
self.x = convert(d[3], d[4])
self.z = convert(d[5], d[6]) * -1.0
self.roll = convert(d[7], d[8])
self.pitch = convert(d[9], d[10])
self.yaw = convert(d[11], d[12])
self._control = [
self.x,
self.y,
self.z,
self.roll,
self.pitch,
self.yaw,
]
elif d[0] == 3: ## readings from the side buttons
# press left button
if d[1] == 1:
t_click = time.time()
elapsed_time = t_click - t_last_click
t_last_click = t_click
self.single_click_and_hold = True
# release left button
if d[1] == 0:
self.single_click_and_hold = False
# right button is for reset
if d[1] == 2:
self._reset_state = 1
self._enabled = False
self._reset_internal_state() | [
"def",
"run",
"(",
"self",
")",
":",
"t_last_click",
"=",
"-",
"1",
"while",
"True",
":",
"d",
"=",
"self",
".",
"device",
".",
"read",
"(",
"13",
")",
"if",
"d",
"is",
"not",
"None",
"and",
"self",
".",
"_enabled",
":",
"if",
"d",
"[",
"0",
... | Listener method that keeps pulling new messages. | [
"Listener",
"method",
"that",
"keeps",
"pulling",
"new",
"messages",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/devices/spacemouse.py#L155-L199 |
230,553 | StanfordVL/robosuite | robosuite/models/robots/robot.py | Robot.add_gripper | def add_gripper(self, arm_name, gripper):
"""
Mounts gripper to arm.
Throws error if robot already has a gripper or gripper type is incorrect.
Args:
arm_name (str): name of arm mount
gripper (MujocoGripper instance): gripper MJCF model
"""
if arm_name in self.grippers:
raise ValueError("Attempts to add multiple grippers to one body")
arm_subtree = self.worldbody.find(".//body[@name='{}']".format(arm_name))
for actuator in gripper.actuator:
if actuator.get("name") is None:
raise XMLError("Actuator has no name")
if not actuator.get("name").startswith("gripper"):
raise XMLError(
"Actuator name {} does not have prefix 'gripper'".format(
actuator.get("name")
)
)
for body in gripper.worldbody:
arm_subtree.append(body)
self.merge(gripper, merge_body=False)
self.grippers[arm_name] = gripper | python | def add_gripper(self, arm_name, gripper):
if arm_name in self.grippers:
raise ValueError("Attempts to add multiple grippers to one body")
arm_subtree = self.worldbody.find(".//body[@name='{}']".format(arm_name))
for actuator in gripper.actuator:
if actuator.get("name") is None:
raise XMLError("Actuator has no name")
if not actuator.get("name").startswith("gripper"):
raise XMLError(
"Actuator name {} does not have prefix 'gripper'".format(
actuator.get("name")
)
)
for body in gripper.worldbody:
arm_subtree.append(body)
self.merge(gripper, merge_body=False)
self.grippers[arm_name] = gripper | [
"def",
"add_gripper",
"(",
"self",
",",
"arm_name",
",",
"gripper",
")",
":",
"if",
"arm_name",
"in",
"self",
".",
"grippers",
":",
"raise",
"ValueError",
"(",
"\"Attempts to add multiple grippers to one body\"",
")",
"arm_subtree",
"=",
"self",
".",
"worldbody",
... | Mounts gripper to arm.
Throws error if robot already has a gripper or gripper type is incorrect.
Args:
arm_name (str): name of arm mount
gripper (MujocoGripper instance): gripper MJCF model | [
"Mounts",
"gripper",
"to",
"arm",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/robots/robot.py#L16-L47 |
230,554 | StanfordVL/robosuite | robosuite/models/arenas/arena.py | Arena.set_origin | def set_origin(self, offset):
"""Applies a constant offset to all objects."""
offset = np.array(offset)
for node in self.worldbody.findall("./*[@pos]"):
cur_pos = string_to_array(node.get("pos"))
new_pos = cur_pos + offset
node.set("pos", array_to_string(new_pos)) | python | def set_origin(self, offset):
offset = np.array(offset)
for node in self.worldbody.findall("./*[@pos]"):
cur_pos = string_to_array(node.get("pos"))
new_pos = cur_pos + offset
node.set("pos", array_to_string(new_pos)) | [
"def",
"set_origin",
"(",
"self",
",",
"offset",
")",
":",
"offset",
"=",
"np",
".",
"array",
"(",
"offset",
")",
"for",
"node",
"in",
"self",
".",
"worldbody",
".",
"findall",
"(",
"\"./*[@pos]\"",
")",
":",
"cur_pos",
"=",
"string_to_array",
"(",
"no... | Applies a constant offset to all objects. | [
"Applies",
"a",
"constant",
"offset",
"to",
"all",
"objects",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/arenas/arena.py#L11-L17 |
230,555 | StanfordVL/robosuite | robosuite/models/arenas/arena.py | Arena.add_pos_indicator | def add_pos_indicator(self):
"""Adds a new position indicator."""
body = new_body(name="pos_indicator")
body.append(
new_geom(
"sphere",
[0.03],
rgba=[1, 0, 0, 0.5],
group=1,
contype="0",
conaffinity="0",
)
)
body.append(new_joint(type="free", name="pos_indicator"))
self.worldbody.append(body) | python | def add_pos_indicator(self):
body = new_body(name="pos_indicator")
body.append(
new_geom(
"sphere",
[0.03],
rgba=[1, 0, 0, 0.5],
group=1,
contype="0",
conaffinity="0",
)
)
body.append(new_joint(type="free", name="pos_indicator"))
self.worldbody.append(body) | [
"def",
"add_pos_indicator",
"(",
"self",
")",
":",
"body",
"=",
"new_body",
"(",
"name",
"=",
"\"pos_indicator\"",
")",
"body",
".",
"append",
"(",
"new_geom",
"(",
"\"sphere\"",
",",
"[",
"0.03",
"]",
",",
"rgba",
"=",
"[",
"1",
",",
"0",
",",
"0",
... | Adds a new position indicator. | [
"Adds",
"a",
"new",
"position",
"indicator",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/arenas/arena.py#L19-L33 |
230,556 | StanfordVL/robosuite | robosuite/models/arenas/table_arena.py | TableArena.table_top_abs | def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height | python | def table_top_abs(self):
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height | [
"def",
"table_top_abs",
"(",
"self",
")",
":",
"table_height",
"=",
"np",
".",
"array",
"(",
"[",
"0",
",",
"0",
",",
"self",
".",
"table_full_size",
"[",
"2",
"]",
"]",
")",
"return",
"string_to_array",
"(",
"self",
".",
"floor",
".",
"get",
"(",
... | Returns the absolute position of table top | [
"Returns",
"the",
"absolute",
"position",
"of",
"table",
"top"
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/arenas/table_arena.py#L47-L50 |
230,557 | StanfordVL/robosuite | robosuite/environments/baxter.py | BaxterEnv._reset_internal | def _reset_internal(self):
"""Resets the pose of the arm and grippers."""
super()._reset_internal()
self.sim.data.qpos[self._ref_joint_pos_indexes] = self.mujoco_robot.init_qpos
if self.has_gripper_right:
self.sim.data.qpos[
self._ref_joint_gripper_right_actuator_indexes
] = self.gripper_right.init_qpos
if self.has_gripper_left:
self.sim.data.qpos[
self._ref_joint_gripper_left_actuator_indexes
] = self.gripper_left.init_qpos | python | def _reset_internal(self):
super()._reset_internal()
self.sim.data.qpos[self._ref_joint_pos_indexes] = self.mujoco_robot.init_qpos
if self.has_gripper_right:
self.sim.data.qpos[
self._ref_joint_gripper_right_actuator_indexes
] = self.gripper_right.init_qpos
if self.has_gripper_left:
self.sim.data.qpos[
self._ref_joint_gripper_left_actuator_indexes
] = self.gripper_left.init_qpos | [
"def",
"_reset_internal",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"_reset_internal",
"(",
")",
"self",
".",
"sim",
".",
"data",
".",
"qpos",
"[",
"self",
".",
"_ref_joint_pos_indexes",
"]",
"=",
"self",
".",
"mujoco_robot",
".",
"init_qpos",
"if",... | Resets the pose of the arm and grippers. | [
"Resets",
"the",
"pose",
"of",
"the",
"arm",
"and",
"grippers",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/baxter.py#L92-L105 |
230,558 | StanfordVL/robosuite | robosuite/environments/baxter.py | BaxterEnv._get_reference | def _get_reference(self):
"""Sets up references for robots, grippers, and objects."""
super()._get_reference()
# indices for joints in qpos, qvel
self.robot_joints = list(self.mujoco_robot.joints)
self._ref_joint_pos_indexes = [
self.sim.model.get_joint_qpos_addr(x) for x in self.robot_joints
]
self._ref_joint_vel_indexes = [
self.sim.model.get_joint_qvel_addr(x) for x in self.robot_joints
]
if self.use_indicator_object:
ind_qpos = self.sim.model.get_joint_qpos_addr("pos_indicator")
self._ref_indicator_pos_low, self._ref_indicator_pos_high = ind_qpos
ind_qvel = self.sim.model.get_joint_qvel_addr("pos_indicator")
self._ref_indicator_vel_low, self._ref_indicator_vel_high = ind_qvel
self.indicator_id = self.sim.model.body_name2id("pos_indicator")
# indices for grippers in qpos, qvel
if self.has_gripper_left:
self.gripper_left_joints = list(self.gripper_left.joints)
self._ref_gripper_left_joint_pos_indexes = [
self.sim.model.get_joint_qpos_addr(x) for x in self.gripper_left_joints
]
self._ref_gripper_left_joint_vel_indexes = [
self.sim.model.get_joint_qvel_addr(x) for x in self.gripper_left_joints
]
self.left_eef_site_id = self.sim.model.site_name2id("l_g_grip_site")
if self.has_gripper_right:
self.gripper_right_joints = list(self.gripper_right.joints)
self._ref_gripper_right_joint_pos_indexes = [
self.sim.model.get_joint_qpos_addr(x) for x in self.gripper_right_joints
]
self._ref_gripper_right_joint_vel_indexes = [
self.sim.model.get_joint_qvel_addr(x) for x in self.gripper_right_joints
]
self.right_eef_site_id = self.sim.model.site_name2id("grip_site")
# indices for joint pos actuation, joint vel actuation, gripper actuation
self._ref_joint_pos_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("pos")
]
self._ref_joint_vel_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("vel")
]
if self.has_gripper_left:
self._ref_joint_gripper_left_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("gripper_l")
]
if self.has_gripper_right:
self._ref_joint_gripper_right_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("gripper_r")
]
if self.has_gripper_right:
# IDs of sites for gripper visualization
self.eef_site_id = self.sim.model.site_name2id("grip_site")
self.eef_cylinder_id = self.sim.model.site_name2id("grip_site_cylinder") | python | def _get_reference(self):
super()._get_reference()
# indices for joints in qpos, qvel
self.robot_joints = list(self.mujoco_robot.joints)
self._ref_joint_pos_indexes = [
self.sim.model.get_joint_qpos_addr(x) for x in self.robot_joints
]
self._ref_joint_vel_indexes = [
self.sim.model.get_joint_qvel_addr(x) for x in self.robot_joints
]
if self.use_indicator_object:
ind_qpos = self.sim.model.get_joint_qpos_addr("pos_indicator")
self._ref_indicator_pos_low, self._ref_indicator_pos_high = ind_qpos
ind_qvel = self.sim.model.get_joint_qvel_addr("pos_indicator")
self._ref_indicator_vel_low, self._ref_indicator_vel_high = ind_qvel
self.indicator_id = self.sim.model.body_name2id("pos_indicator")
# indices for grippers in qpos, qvel
if self.has_gripper_left:
self.gripper_left_joints = list(self.gripper_left.joints)
self._ref_gripper_left_joint_pos_indexes = [
self.sim.model.get_joint_qpos_addr(x) for x in self.gripper_left_joints
]
self._ref_gripper_left_joint_vel_indexes = [
self.sim.model.get_joint_qvel_addr(x) for x in self.gripper_left_joints
]
self.left_eef_site_id = self.sim.model.site_name2id("l_g_grip_site")
if self.has_gripper_right:
self.gripper_right_joints = list(self.gripper_right.joints)
self._ref_gripper_right_joint_pos_indexes = [
self.sim.model.get_joint_qpos_addr(x) for x in self.gripper_right_joints
]
self._ref_gripper_right_joint_vel_indexes = [
self.sim.model.get_joint_qvel_addr(x) for x in self.gripper_right_joints
]
self.right_eef_site_id = self.sim.model.site_name2id("grip_site")
# indices for joint pos actuation, joint vel actuation, gripper actuation
self._ref_joint_pos_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("pos")
]
self._ref_joint_vel_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("vel")
]
if self.has_gripper_left:
self._ref_joint_gripper_left_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("gripper_l")
]
if self.has_gripper_right:
self._ref_joint_gripper_right_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("gripper_r")
]
if self.has_gripper_right:
# IDs of sites for gripper visualization
self.eef_site_id = self.sim.model.site_name2id("grip_site")
self.eef_cylinder_id = self.sim.model.site_name2id("grip_site_cylinder") | [
"def",
"_get_reference",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"_get_reference",
"(",
")",
"# indices for joints in qpos, qvel",
"self",
".",
"robot_joints",
"=",
"list",
"(",
"self",
".",
"mujoco_robot",
".",
"joints",
")",
"self",
".",
"_ref_joint_p... | Sets up references for robots, grippers, and objects. | [
"Sets",
"up",
"references",
"for",
"robots",
"grippers",
"and",
"objects",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/baxter.py#L107-L179 |
230,559 | StanfordVL/robosuite | robosuite/environments/baxter.py | BaxterEnv.move_indicator | def move_indicator(self, pos):
"""Moves the position of the indicator object to @pos."""
if self.use_indicator_object:
self.sim.data.qpos[
self._ref_indicator_pos_low : self._ref_indicator_pos_low + 3
] = pos | python | def move_indicator(self, pos):
if self.use_indicator_object:
self.sim.data.qpos[
self._ref_indicator_pos_low : self._ref_indicator_pos_low + 3
] = pos | [
"def",
"move_indicator",
"(",
"self",
",",
"pos",
")",
":",
"if",
"self",
".",
"use_indicator_object",
":",
"self",
".",
"sim",
".",
"data",
".",
"qpos",
"[",
"self",
".",
"_ref_indicator_pos_low",
":",
"self",
".",
"_ref_indicator_pos_low",
"+",
"3",
"]",... | Moves the position of the indicator object to @pos. | [
"Moves",
"the",
"position",
"of",
"the",
"indicator",
"object",
"to"
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/baxter.py#L181-L186 |
230,560 | StanfordVL/robosuite | robosuite/environments/baxter.py | BaxterEnv._post_action | def _post_action(self, action):
"""Optionally performs gripper visualization after the actions."""
ret = super()._post_action(action)
self._gripper_visualization()
return ret | python | def _post_action(self, action):
ret = super()._post_action(action)
self._gripper_visualization()
return ret | [
"def",
"_post_action",
"(",
"self",
",",
"action",
")",
":",
"ret",
"=",
"super",
"(",
")",
".",
"_post_action",
"(",
"action",
")",
"self",
".",
"_gripper_visualization",
"(",
")",
"return",
"ret"
] | Optionally performs gripper visualization after the actions. | [
"Optionally",
"performs",
"gripper",
"visualization",
"after",
"the",
"actions",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/baxter.py#L242-L246 |
230,561 | StanfordVL/robosuite | robosuite/environments/baxter.py | BaxterEnv.set_robot_joint_positions | def set_robot_joint_positions(self, jpos):
"""
Helper method to force robot joint positions to the passed values.
"""
self.sim.data.qpos[self._ref_joint_pos_indexes] = jpos
self.sim.forward() | python | def set_robot_joint_positions(self, jpos):
self.sim.data.qpos[self._ref_joint_pos_indexes] = jpos
self.sim.forward() | [
"def",
"set_robot_joint_positions",
"(",
"self",
",",
"jpos",
")",
":",
"self",
".",
"sim",
".",
"data",
".",
"qpos",
"[",
"self",
".",
"_ref_joint_pos_indexes",
"]",
"=",
"jpos",
"self",
".",
"sim",
".",
"forward",
"(",
")"
] | Helper method to force robot joint positions to the passed values. | [
"Helper",
"method",
"to",
"force",
"robot",
"joint",
"positions",
"to",
"the",
"passed",
"values",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/baxter.py#L342-L347 |
230,562 | StanfordVL/robosuite | robosuite/models/robots/baxter_robot.py | Baxter.set_base_xpos | def set_base_xpos(self, pos):
"""Places the robot on position @pos."""
node = self.worldbody.find("./body[@name='base']")
node.set("pos", array_to_string(pos - self.bottom_offset)) | python | def set_base_xpos(self, pos):
node = self.worldbody.find("./body[@name='base']")
node.set("pos", array_to_string(pos - self.bottom_offset)) | [
"def",
"set_base_xpos",
"(",
"self",
",",
"pos",
")",
":",
"node",
"=",
"self",
".",
"worldbody",
".",
"find",
"(",
"\"./body[@name='base']\"",
")",
"node",
".",
"set",
"(",
"\"pos\"",
",",
"array_to_string",
"(",
"pos",
"-",
"self",
".",
"bottom_offset",
... | Places the robot on position @pos. | [
"Places",
"the",
"robot",
"on",
"position"
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/robots/baxter_robot.py#L15-L18 |
230,563 | StanfordVL/robosuite | robosuite/models/objects/generated_objects.py | _get_size | def _get_size(size,
size_max,
size_min,
default_max,
default_min):
"""
Helper method for providing a size,
or a range to randomize from
"""
if len(default_max) != len(default_min):
raise ValueError('default_max = {} and default_min = {}'
.format(str(default_max), str(default_min)) +
' have different lengths')
if size is not None:
if (size_max is not None) or (size_min is not None):
raise ValueError('size = {} overrides size_max = {}, size_min = {}'
.format(size, size_max, size_min))
else:
if size_max is None:
size_max = default_max
if size_min is None:
size_min = default_min
size = np.array([np.random.uniform(size_min[i], size_max[i])
for i in range(len(default_max))])
return size | python | def _get_size(size,
size_max,
size_min,
default_max,
default_min):
if len(default_max) != len(default_min):
raise ValueError('default_max = {} and default_min = {}'
.format(str(default_max), str(default_min)) +
' have different lengths')
if size is not None:
if (size_max is not None) or (size_min is not None):
raise ValueError('size = {} overrides size_max = {}, size_min = {}'
.format(size, size_max, size_min))
else:
if size_max is None:
size_max = default_max
if size_min is None:
size_min = default_min
size = np.array([np.random.uniform(size_min[i], size_max[i])
for i in range(len(default_max))])
return size | [
"def",
"_get_size",
"(",
"size",
",",
"size_max",
",",
"size_min",
",",
"default_max",
",",
"default_min",
")",
":",
"if",
"len",
"(",
"default_max",
")",
"!=",
"len",
"(",
"default_min",
")",
":",
"raise",
"ValueError",
"(",
"'default_max = {} and default_min... | Helper method for providing a size,
or a range to randomize from | [
"Helper",
"method",
"for",
"providing",
"a",
"size",
"or",
"a",
"range",
"to",
"randomize",
"from"
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/objects/generated_objects.py#L282-L306 |
230,564 | StanfordVL/robosuite | robosuite/models/objects/generated_objects.py | _get_randomized_range | def _get_randomized_range(val,
provided_range,
default_range):
"""
Helper to initialize by either value or a range
Returns a range to randomize from
"""
if val is None:
if provided_range is None:
return default_range
else:
return provided_range
else:
if provided_range is not None:
raise ValueError('Value {} overrides range {}'
.format(str(val), str(provided_range)))
return [val] | python | def _get_randomized_range(val,
provided_range,
default_range):
if val is None:
if provided_range is None:
return default_range
else:
return provided_range
else:
if provided_range is not None:
raise ValueError('Value {} overrides range {}'
.format(str(val), str(provided_range)))
return [val] | [
"def",
"_get_randomized_range",
"(",
"val",
",",
"provided_range",
",",
"default_range",
")",
":",
"if",
"val",
"is",
"None",
":",
"if",
"provided_range",
"is",
"None",
":",
"return",
"default_range",
"else",
":",
"return",
"provided_range",
"else",
":",
"if",... | Helper to initialize by either value or a range
Returns a range to randomize from | [
"Helper",
"to",
"initialize",
"by",
"either",
"value",
"or",
"a",
"range",
"Returns",
"a",
"range",
"to",
"randomize",
"from"
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/objects/generated_objects.py#L309-L325 |
230,565 | StanfordVL/robosuite | robosuite/models/grippers/gripper_factory.py | gripper_factory | def gripper_factory(name):
"""
Genreator for grippers
Creates a Gripper instance with the provided name.
Args:
name: the name of the gripper class
Returns:
gripper: Gripper instance
Raises:
XMLError: [description]
"""
if name == "TwoFingerGripper":
return TwoFingerGripper()
if name == "LeftTwoFingerGripper":
return LeftTwoFingerGripper()
if name == "PR2Gripper":
return PR2Gripper()
if name == "RobotiqGripper":
return RobotiqGripper()
if name == "PushingGripper":
return PushingGripper()
if name == "RobotiqThreeFingerGripper":
return RobotiqThreeFingerGripper()
raise ValueError("Unkown gripper name {}".format(name)) | python | def gripper_factory(name):
if name == "TwoFingerGripper":
return TwoFingerGripper()
if name == "LeftTwoFingerGripper":
return LeftTwoFingerGripper()
if name == "PR2Gripper":
return PR2Gripper()
if name == "RobotiqGripper":
return RobotiqGripper()
if name == "PushingGripper":
return PushingGripper()
if name == "RobotiqThreeFingerGripper":
return RobotiqThreeFingerGripper()
raise ValueError("Unkown gripper name {}".format(name)) | [
"def",
"gripper_factory",
"(",
"name",
")",
":",
"if",
"name",
"==",
"\"TwoFingerGripper\"",
":",
"return",
"TwoFingerGripper",
"(",
")",
"if",
"name",
"==",
"\"LeftTwoFingerGripper\"",
":",
"return",
"LeftTwoFingerGripper",
"(",
")",
"if",
"name",
"==",
"\"PR2G... | Genreator for grippers
Creates a Gripper instance with the provided name.
Args:
name: the name of the gripper class
Returns:
gripper: Gripper instance
Raises:
XMLError: [description] | [
"Genreator",
"for",
"grippers"
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/grippers/gripper_factory.py#L11-L38 |
230,566 | StanfordVL/robosuite | robosuite/devices/keyboard.py | Keyboard._display_controls | def _display_controls(self):
"""
Method to pretty print controls.
"""
def print_command(char, info):
char += " " * (10 - len(char))
print("{}\t{}".format(char, info))
print("")
print_command("Keys", "Command")
print_command("q", "reset simulation")
print_command("spacebar", "toggle gripper (open/close)")
print_command("w-a-s-d", "move arm horizontally in x-y plane")
print_command("r-f", "move arm vertically")
print_command("z-x", "rotate arm about x-axis")
print_command("t-g", "rotate arm about y-axis")
print_command("c-v", "rotate arm about z-axis")
print_command("ESC", "quit")
print("") | python | def _display_controls(self):
def print_command(char, info):
char += " " * (10 - len(char))
print("{}\t{}".format(char, info))
print("")
print_command("Keys", "Command")
print_command("q", "reset simulation")
print_command("spacebar", "toggle gripper (open/close)")
print_command("w-a-s-d", "move arm horizontally in x-y plane")
print_command("r-f", "move arm vertically")
print_command("z-x", "rotate arm about x-axis")
print_command("t-g", "rotate arm about y-axis")
print_command("c-v", "rotate arm about z-axis")
print_command("ESC", "quit")
print("") | [
"def",
"_display_controls",
"(",
"self",
")",
":",
"def",
"print_command",
"(",
"char",
",",
"info",
")",
":",
"char",
"+=",
"\" \"",
"*",
"(",
"10",
"-",
"len",
"(",
"char",
")",
")",
"print",
"(",
"\"{}\\t{}\"",
".",
"format",
"(",
"char",
",",
"... | Method to pretty print controls. | [
"Method",
"to",
"pretty",
"print",
"controls",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/devices/keyboard.py#L26-L45 |
230,567 | StanfordVL/robosuite | robosuite/devices/keyboard.py | Keyboard._reset_internal_state | def _reset_internal_state(self):
"""
Resets internal state of controller, except for the reset signal.
"""
self.rotation = np.array([[-1., 0., 0.], [0., 1., 0.], [0., 0., -1.]])
self.pos = np.zeros(3) # (x, y, z)
self.last_pos = np.zeros(3)
self.grasp = False | python | def _reset_internal_state(self):
self.rotation = np.array([[-1., 0., 0.], [0., 1., 0.], [0., 0., -1.]])
self.pos = np.zeros(3) # (x, y, z)
self.last_pos = np.zeros(3)
self.grasp = False | [
"def",
"_reset_internal_state",
"(",
"self",
")",
":",
"self",
".",
"rotation",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"-",
"1.",
",",
"0.",
",",
"0.",
"]",
",",
"[",
"0.",
",",
"1.",
",",
"0.",
"]",
",",
"[",
"0.",
",",
"0.",
",",
"-",
"1... | Resets internal state of controller, except for the reset signal. | [
"Resets",
"internal",
"state",
"of",
"controller",
"except",
"for",
"the",
"reset",
"signal",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/devices/keyboard.py#L47-L54 |
230,568 | StanfordVL/robosuite | robosuite/devices/keyboard.py | Keyboard.get_controller_state | def get_controller_state(self):
"""Returns the current state of the keyboard, a dictionary of pos, orn, grasp, and reset."""
dpos = self.pos - self.last_pos
self.last_pos = np.array(self.pos)
return dict(
dpos=dpos,
rotation=self.rotation,
grasp=int(self.grasp),
reset=self._reset_state,
) | python | def get_controller_state(self):
dpos = self.pos - self.last_pos
self.last_pos = np.array(self.pos)
return dict(
dpos=dpos,
rotation=self.rotation,
grasp=int(self.grasp),
reset=self._reset_state,
) | [
"def",
"get_controller_state",
"(",
"self",
")",
":",
"dpos",
"=",
"self",
".",
"pos",
"-",
"self",
".",
"last_pos",
"self",
".",
"last_pos",
"=",
"np",
".",
"array",
"(",
"self",
".",
"pos",
")",
"return",
"dict",
"(",
"dpos",
"=",
"dpos",
",",
"r... | Returns the current state of the keyboard, a dictionary of pos, orn, grasp, and reset. | [
"Returns",
"the",
"current",
"state",
"of",
"the",
"keyboard",
"a",
"dictionary",
"of",
"pos",
"orn",
"grasp",
"and",
"reset",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/devices/keyboard.py#L65-L74 |
230,569 | StanfordVL/robosuite | robosuite/devices/keyboard.py | Keyboard.on_press | def on_press(self, window, key, scancode, action, mods):
"""
Key handler for key presses.
"""
# controls for moving position
if key == glfw.KEY_W:
self.pos[0] -= self._pos_step # dec x
elif key == glfw.KEY_S:
self.pos[0] += self._pos_step # inc x
elif key == glfw.KEY_A:
self.pos[1] -= self._pos_step # dec y
elif key == glfw.KEY_D:
self.pos[1] += self._pos_step # inc y
elif key == glfw.KEY_F:
self.pos[2] -= self._pos_step # dec z
elif key == glfw.KEY_R:
self.pos[2] += self._pos_step # inc z
# controls for moving orientation
elif key == glfw.KEY_Z:
drot = rotation_matrix(angle=0.1, direction=[1., 0., 0.])[:3, :3]
self.rotation = self.rotation.dot(drot) # rotates x
elif key == glfw.KEY_X:
drot = rotation_matrix(angle=-0.1, direction=[1., 0., 0.])[:3, :3]
self.rotation = self.rotation.dot(drot) # rotates x
elif key == glfw.KEY_T:
drot = rotation_matrix(angle=0.1, direction=[0., 1., 0.])[:3, :3]
self.rotation = self.rotation.dot(drot) # rotates y
elif key == glfw.KEY_G:
drot = rotation_matrix(angle=-0.1, direction=[0., 1., 0.])[:3, :3]
self.rotation = self.rotation.dot(drot) # rotates y
elif key == glfw.KEY_C:
drot = rotation_matrix(angle=0.1, direction=[0., 0., 1.])[:3, :3]
self.rotation = self.rotation.dot(drot) # rotates z
elif key == glfw.KEY_V:
drot = rotation_matrix(angle=-0.1, direction=[0., 0., 1.])[:3, :3]
self.rotation = self.rotation.dot(drot) | python | def on_press(self, window, key, scancode, action, mods):
# controls for moving position
if key == glfw.KEY_W:
self.pos[0] -= self._pos_step # dec x
elif key == glfw.KEY_S:
self.pos[0] += self._pos_step # inc x
elif key == glfw.KEY_A:
self.pos[1] -= self._pos_step # dec y
elif key == glfw.KEY_D:
self.pos[1] += self._pos_step # inc y
elif key == glfw.KEY_F:
self.pos[2] -= self._pos_step # dec z
elif key == glfw.KEY_R:
self.pos[2] += self._pos_step # inc z
# controls for moving orientation
elif key == glfw.KEY_Z:
drot = rotation_matrix(angle=0.1, direction=[1., 0., 0.])[:3, :3]
self.rotation = self.rotation.dot(drot) # rotates x
elif key == glfw.KEY_X:
drot = rotation_matrix(angle=-0.1, direction=[1., 0., 0.])[:3, :3]
self.rotation = self.rotation.dot(drot) # rotates x
elif key == glfw.KEY_T:
drot = rotation_matrix(angle=0.1, direction=[0., 1., 0.])[:3, :3]
self.rotation = self.rotation.dot(drot) # rotates y
elif key == glfw.KEY_G:
drot = rotation_matrix(angle=-0.1, direction=[0., 1., 0.])[:3, :3]
self.rotation = self.rotation.dot(drot) # rotates y
elif key == glfw.KEY_C:
drot = rotation_matrix(angle=0.1, direction=[0., 0., 1.])[:3, :3]
self.rotation = self.rotation.dot(drot) # rotates z
elif key == glfw.KEY_V:
drot = rotation_matrix(angle=-0.1, direction=[0., 0., 1.])[:3, :3]
self.rotation = self.rotation.dot(drot) | [
"def",
"on_press",
"(",
"self",
",",
"window",
",",
"key",
",",
"scancode",
",",
"action",
",",
"mods",
")",
":",
"# controls for moving position",
"if",
"key",
"==",
"glfw",
".",
"KEY_W",
":",
"self",
".",
"pos",
"[",
"0",
"]",
"-=",
"self",
".",
"_... | Key handler for key presses. | [
"Key",
"handler",
"for",
"key",
"presses",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/devices/keyboard.py#L76-L113 |
230,570 | StanfordVL/robosuite | robosuite/devices/keyboard.py | Keyboard.on_release | def on_release(self, window, key, scancode, action, mods):
"""
Key handler for key releases.
"""
# controls for grasping
if key == glfw.KEY_SPACE:
self.grasp = not self.grasp # toggle gripper
# user-commanded reset
elif key == glfw.KEY_Q:
self._reset_state = 1
self._enabled = False
self._reset_internal_state() | python | def on_release(self, window, key, scancode, action, mods):
# controls for grasping
if key == glfw.KEY_SPACE:
self.grasp = not self.grasp # toggle gripper
# user-commanded reset
elif key == glfw.KEY_Q:
self._reset_state = 1
self._enabled = False
self._reset_internal_state() | [
"def",
"on_release",
"(",
"self",
",",
"window",
",",
"key",
",",
"scancode",
",",
"action",
",",
"mods",
")",
":",
"# controls for grasping",
"if",
"key",
"==",
"glfw",
".",
"KEY_SPACE",
":",
"self",
".",
"grasp",
"=",
"not",
"self",
".",
"grasp",
"# ... | Key handler for key releases. | [
"Key",
"handler",
"for",
"key",
"releases",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/devices/keyboard.py#L115-L128 |
230,571 | StanfordVL/robosuite | robosuite/utils/mjcf_utils.py | xml_path_completion | def xml_path_completion(xml_path):
"""
Takes in a local xml path and returns a full path.
if @xml_path is absolute, do nothing
if @xml_path is not absolute, load xml that is shipped by the package
"""
if xml_path.startswith("/"):
full_path = xml_path
else:
full_path = os.path.join(robosuite.models.assets_root, xml_path)
return full_path | python | def xml_path_completion(xml_path):
if xml_path.startswith("/"):
full_path = xml_path
else:
full_path = os.path.join(robosuite.models.assets_root, xml_path)
return full_path | [
"def",
"xml_path_completion",
"(",
"xml_path",
")",
":",
"if",
"xml_path",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"full_path",
"=",
"xml_path",
"else",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"robosuite",
".",
"models",
".",
"asse... | Takes in a local xml path and returns a full path.
if @xml_path is absolute, do nothing
if @xml_path is not absolute, load xml that is shipped by the package | [
"Takes",
"in",
"a",
"local",
"xml",
"path",
"and",
"returns",
"a",
"full",
"path",
".",
"if"
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/utils/mjcf_utils.py#L14-L24 |
230,572 | StanfordVL/robosuite | robosuite/utils/mjcf_utils.py | postprocess_model_xml | def postprocess_model_xml(xml_str):
"""
This function postprocesses the model.xml collected from a MuJoCo demonstration
in order to make sure that the STL files can be found.
"""
path = os.path.split(robosuite.__file__)[0]
path_split = path.split("/")
# replace mesh and texture file paths
tree = ET.fromstring(xml_str)
root = tree
asset = root.find("asset")
meshes = asset.findall("mesh")
textures = asset.findall("texture")
all_elements = meshes + textures
for elem in all_elements:
old_path = elem.get("file")
if old_path is None:
continue
old_path_split = old_path.split("/")
ind = max(
loc for loc, val in enumerate(old_path_split) if val == "robosuite"
) # last occurrence index
new_path_split = path_split + old_path_split[ind + 1 :]
new_path = "/".join(new_path_split)
elem.set("file", new_path)
return ET.tostring(root, encoding="utf8").decode("utf8") | python | def postprocess_model_xml(xml_str):
path = os.path.split(robosuite.__file__)[0]
path_split = path.split("/")
# replace mesh and texture file paths
tree = ET.fromstring(xml_str)
root = tree
asset = root.find("asset")
meshes = asset.findall("mesh")
textures = asset.findall("texture")
all_elements = meshes + textures
for elem in all_elements:
old_path = elem.get("file")
if old_path is None:
continue
old_path_split = old_path.split("/")
ind = max(
loc for loc, val in enumerate(old_path_split) if val == "robosuite"
) # last occurrence index
new_path_split = path_split + old_path_split[ind + 1 :]
new_path = "/".join(new_path_split)
elem.set("file", new_path)
return ET.tostring(root, encoding="utf8").decode("utf8") | [
"def",
"postprocess_model_xml",
"(",
"xml_str",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"split",
"(",
"robosuite",
".",
"__file__",
")",
"[",
"0",
"]",
"path_split",
"=",
"path",
".",
"split",
"(",
"\"/\"",
")",
"# replace mesh and texture file paths"... | This function postprocesses the model.xml collected from a MuJoCo demonstration
in order to make sure that the STL files can be found. | [
"This",
"function",
"postprocesses",
"the",
"model",
".",
"xml",
"collected",
"from",
"a",
"MuJoCo",
"demonstration",
"in",
"order",
"to",
"make",
"sure",
"that",
"the",
"STL",
"files",
"can",
"be",
"found",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/utils/mjcf_utils.py#L152-L181 |
230,573 | StanfordVL/robosuite | robosuite/controllers/baxter_ik_controller.py | BaxterIKController.sync_ik_robot | def sync_ik_robot(self, joint_positions, simulate=False, sync_last=True):
"""
Force the internal robot model to match the provided joint angles.
Args:
joint_positions (list): a list or flat numpy array of joint positions.
simulate (bool): If True, actually use physics simulation, else
write to physics state directly.
sync_last (bool): If False, don't sync the last joint angle. This
is useful for directly controlling the roll at the end effector.
"""
num_joints = len(joint_positions)
if not sync_last:
num_joints -= 1
for i in range(num_joints):
if simulate:
p.setJointMotorControl2(
self.ik_robot,
self.actual[i],
p.POSITION_CONTROL,
targetVelocity=0,
targetPosition=joint_positions[i],
force=500,
positionGain=0.5,
velocityGain=1.,
)
else:
# Note that we use self.actual[i], and not i
p.resetJointState(self.ik_robot, self.actual[i], joint_positions[i]) | python | def sync_ik_robot(self, joint_positions, simulate=False, sync_last=True):
num_joints = len(joint_positions)
if not sync_last:
num_joints -= 1
for i in range(num_joints):
if simulate:
p.setJointMotorControl2(
self.ik_robot,
self.actual[i],
p.POSITION_CONTROL,
targetVelocity=0,
targetPosition=joint_positions[i],
force=500,
positionGain=0.5,
velocityGain=1.,
)
else:
# Note that we use self.actual[i], and not i
p.resetJointState(self.ik_robot, self.actual[i], joint_positions[i]) | [
"def",
"sync_ik_robot",
"(",
"self",
",",
"joint_positions",
",",
"simulate",
"=",
"False",
",",
"sync_last",
"=",
"True",
")",
":",
"num_joints",
"=",
"len",
"(",
"joint_positions",
")",
"if",
"not",
"sync_last",
":",
"num_joints",
"-=",
"1",
"for",
"i",
... | Force the internal robot model to match the provided joint angles.
Args:
joint_positions (list): a list or flat numpy array of joint positions.
simulate (bool): If True, actually use physics simulation, else
write to physics state directly.
sync_last (bool): If False, don't sync the last joint angle. This
is useful for directly controlling the roll at the end effector. | [
"Force",
"the",
"internal",
"robot",
"model",
"to",
"match",
"the",
"provided",
"joint",
"angles",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/controllers/baxter_ik_controller.py#L159-L187 |
230,574 | StanfordVL/robosuite | robosuite/controllers/baxter_ik_controller.py | BaxterIKController.bullet_base_pose_to_world_pose | def bullet_base_pose_to_world_pose(self, pose_in_base):
"""
Convert a pose in the base frame to a pose in the world frame.
Args:
pose_in_base: a (pos, orn) tuple.
Returns:
pose_in world: a (pos, orn) tuple.
"""
pose_in_base = T.pose2mat(pose_in_base)
base_pos_in_world = np.array(p.getBasePositionAndOrientation(self.ik_robot)[0])
base_orn_in_world = np.array(p.getBasePositionAndOrientation(self.ik_robot)[1])
base_pose_in_world = T.pose2mat((base_pos_in_world, base_orn_in_world))
pose_in_world = T.pose_in_A_to_pose_in_B(
pose_A=pose_in_base, pose_A_in_B=base_pose_in_world
)
return T.mat2pose(pose_in_world) | python | def bullet_base_pose_to_world_pose(self, pose_in_base):
pose_in_base = T.pose2mat(pose_in_base)
base_pos_in_world = np.array(p.getBasePositionAndOrientation(self.ik_robot)[0])
base_orn_in_world = np.array(p.getBasePositionAndOrientation(self.ik_robot)[1])
base_pose_in_world = T.pose2mat((base_pos_in_world, base_orn_in_world))
pose_in_world = T.pose_in_A_to_pose_in_B(
pose_A=pose_in_base, pose_A_in_B=base_pose_in_world
)
return T.mat2pose(pose_in_world) | [
"def",
"bullet_base_pose_to_world_pose",
"(",
"self",
",",
"pose_in_base",
")",
":",
"pose_in_base",
"=",
"T",
".",
"pose2mat",
"(",
"pose_in_base",
")",
"base_pos_in_world",
"=",
"np",
".",
"array",
"(",
"p",
".",
"getBasePositionAndOrientation",
"(",
"self",
"... | Convert a pose in the base frame to a pose in the world frame.
Args:
pose_in_base: a (pos, orn) tuple.
Returns:
pose_in world: a (pos, orn) tuple. | [
"Convert",
"a",
"pose",
"in",
"the",
"base",
"frame",
"to",
"a",
"pose",
"in",
"the",
"world",
"frame",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/controllers/baxter_ik_controller.py#L271-L290 |
230,575 | StanfordVL/robosuite | robosuite/controllers/baxter_ik_controller.py | BaxterIKController.clip_joint_velocities | def clip_joint_velocities(self, velocities):
"""
Clips joint velocities into a valid range.
"""
for i in range(len(velocities)):
if velocities[i] >= 1.0:
velocities[i] = 1.0
elif velocities[i] <= -1.0:
velocities[i] = -1.0
return velocities | python | def clip_joint_velocities(self, velocities):
for i in range(len(velocities)):
if velocities[i] >= 1.0:
velocities[i] = 1.0
elif velocities[i] <= -1.0:
velocities[i] = -1.0
return velocities | [
"def",
"clip_joint_velocities",
"(",
"self",
",",
"velocities",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"velocities",
")",
")",
":",
"if",
"velocities",
"[",
"i",
"]",
">=",
"1.0",
":",
"velocities",
"[",
"i",
"]",
"=",
"1.0",
"elif",
... | Clips joint velocities into a valid range. | [
"Clips",
"joint",
"velocities",
"into",
"a",
"valid",
"range",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/controllers/baxter_ik_controller.py#L351-L360 |
230,576 | StanfordVL/robosuite | robosuite/environments/baxter_peg_in_hole.py | BaxterPegInHole._load_model | def _load_model(self):
"""
Loads the peg and the hole models.
"""
super()._load_model()
self.mujoco_robot.set_base_xpos([0, 0, 0])
# Add arena and robot
self.model = MujocoWorldBase()
self.arena = EmptyArena()
if self.use_indicator_object:
self.arena.add_pos_indicator()
self.model.merge(self.arena)
self.model.merge(self.mujoco_robot)
# Load hole object
self.hole_obj = self.hole.get_collision(name="hole", site=True)
self.hole_obj.set("quat", "0 0 0.707 0.707")
self.hole_obj.set("pos", "0.11 0 0.18")
self.model.merge_asset(self.hole)
self.model.worldbody.find(".//body[@name='left_hand']").append(self.hole_obj)
# Load cylinder object
self.cyl_obj = self.cylinder.get_collision(name="cylinder", site=True)
self.cyl_obj.set("pos", "0 0 0.15")
self.model.merge_asset(self.cylinder)
self.model.worldbody.find(".//body[@name='right_hand']").append(self.cyl_obj)
self.model.worldbody.find(".//geom[@name='cylinder']").set("rgba", "0 1 0 1") | python | def _load_model(self):
super()._load_model()
self.mujoco_robot.set_base_xpos([0, 0, 0])
# Add arena and robot
self.model = MujocoWorldBase()
self.arena = EmptyArena()
if self.use_indicator_object:
self.arena.add_pos_indicator()
self.model.merge(self.arena)
self.model.merge(self.mujoco_robot)
# Load hole object
self.hole_obj = self.hole.get_collision(name="hole", site=True)
self.hole_obj.set("quat", "0 0 0.707 0.707")
self.hole_obj.set("pos", "0.11 0 0.18")
self.model.merge_asset(self.hole)
self.model.worldbody.find(".//body[@name='left_hand']").append(self.hole_obj)
# Load cylinder object
self.cyl_obj = self.cylinder.get_collision(name="cylinder", site=True)
self.cyl_obj.set("pos", "0 0 0.15")
self.model.merge_asset(self.cylinder)
self.model.worldbody.find(".//body[@name='right_hand']").append(self.cyl_obj)
self.model.worldbody.find(".//geom[@name='cylinder']").set("rgba", "0 1 0 1") | [
"def",
"_load_model",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"_load_model",
"(",
")",
"self",
".",
"mujoco_robot",
".",
"set_base_xpos",
"(",
"[",
"0",
",",
"0",
",",
"0",
"]",
")",
"# Add arena and robot",
"self",
".",
"model",
"=",
"MujocoWor... | Loads the peg and the hole models. | [
"Loads",
"the",
"peg",
"and",
"the",
"hole",
"models",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/baxter_peg_in_hole.py#L60-L87 |
230,577 | StanfordVL/robosuite | robosuite/environments/baxter_peg_in_hole.py | BaxterPegInHole._compute_orientation | def _compute_orientation(self):
"""
Helper function to return the relative positions between the hole and the peg.
In particular, the intersection of the line defined by the peg and the plane
defined by the hole is computed; the parallel distance, perpendicular distance,
and angle are returned.
"""
cyl_mat = self.sim.data.body_xmat[self.cyl_body_id]
cyl_mat.shape = (3, 3)
cyl_pos = self.sim.data.body_xpos[self.cyl_body_id]
hole_pos = self.sim.data.body_xpos[self.hole_body_id]
hole_mat = self.sim.data.body_xmat[self.hole_body_id]
hole_mat.shape = (3, 3)
v = cyl_mat @ np.array([0, 0, 1])
v = v / np.linalg.norm(v)
center = hole_pos + hole_mat @ np.array([0.1, 0, 0])
t = (center - cyl_pos) @ v / (np.linalg.norm(v) ** 2)
d = np.linalg.norm(np.cross(v, cyl_pos - center)) / np.linalg.norm(v)
hole_normal = hole_mat @ np.array([0, 0, 1])
return (
t,
d,
abs(
np.dot(hole_normal, v) / np.linalg.norm(hole_normal) / np.linalg.norm(v)
),
) | python | def _compute_orientation(self):
cyl_mat = self.sim.data.body_xmat[self.cyl_body_id]
cyl_mat.shape = (3, 3)
cyl_pos = self.sim.data.body_xpos[self.cyl_body_id]
hole_pos = self.sim.data.body_xpos[self.hole_body_id]
hole_mat = self.sim.data.body_xmat[self.hole_body_id]
hole_mat.shape = (3, 3)
v = cyl_mat @ np.array([0, 0, 1])
v = v / np.linalg.norm(v)
center = hole_pos + hole_mat @ np.array([0.1, 0, 0])
t = (center - cyl_pos) @ v / (np.linalg.norm(v) ** 2)
d = np.linalg.norm(np.cross(v, cyl_pos - center)) / np.linalg.norm(v)
hole_normal = hole_mat @ np.array([0, 0, 1])
return (
t,
d,
abs(
np.dot(hole_normal, v) / np.linalg.norm(hole_normal) / np.linalg.norm(v)
),
) | [
"def",
"_compute_orientation",
"(",
"self",
")",
":",
"cyl_mat",
"=",
"self",
".",
"sim",
".",
"data",
".",
"body_xmat",
"[",
"self",
".",
"cyl_body_id",
"]",
"cyl_mat",
".",
"shape",
"=",
"(",
"3",
",",
"3",
")",
"cyl_pos",
"=",
"self",
".",
"sim",
... | Helper function to return the relative positions between the hole and the peg.
In particular, the intersection of the line defined by the peg and the plane
defined by the hole is computed; the parallel distance, perpendicular distance,
and angle are returned. | [
"Helper",
"function",
"to",
"return",
"the",
"relative",
"positions",
"between",
"the",
"hole",
"and",
"the",
"peg",
".",
"In",
"particular",
"the",
"intersection",
"of",
"the",
"line",
"defined",
"by",
"the",
"peg",
"and",
"the",
"plane",
"defined",
"by",
... | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/baxter_peg_in_hole.py#L105-L134 |
230,578 | StanfordVL/robosuite | robosuite/environments/baxter_peg_in_hole.py | BaxterPegInHole._check_success | def _check_success(self):
"""
Returns True if task is successfully completed.
"""
t, d, cos = self._compute_orientation()
return d < 0.06 and t >= -0.12 and t <= 0.14 and cos > 0.95 | python | def _check_success(self):
t, d, cos = self._compute_orientation()
return d < 0.06 and t >= -0.12 and t <= 0.14 and cos > 0.95 | [
"def",
"_check_success",
"(",
"self",
")",
":",
"t",
",",
"d",
",",
"cos",
"=",
"self",
".",
"_compute_orientation",
"(",
")",
"return",
"d",
"<",
"0.06",
"and",
"t",
">=",
"-",
"0.12",
"and",
"t",
"<=",
"0.14",
"and",
"cos",
">",
"0.95"
] | Returns True if task is successfully completed. | [
"Returns",
"True",
"if",
"task",
"is",
"successfully",
"completed",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/baxter_peg_in_hole.py#L277-L283 |
230,579 | StanfordVL/robosuite | robosuite/utils/transform_utils.py | mat2euler | def mat2euler(rmat, axes="sxyz"):
"""
Converts given rotation matrix to euler angles in radian.
Args:
rmat: 3x3 rotation matrix
axes: One of 24 axis sequences as string or encoded tuple
Returns:
converted euler angles in radian vec3 float
"""
try:
firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]
except (AttributeError, KeyError):
firstaxis, parity, repetition, frame = axes
i = firstaxis
j = _NEXT_AXIS[i + parity]
k = _NEXT_AXIS[i - parity + 1]
M = np.array(rmat, dtype=np.float32, copy=False)[:3, :3]
if repetition:
sy = math.sqrt(M[i, j] * M[i, j] + M[i, k] * M[i, k])
if sy > EPS:
ax = math.atan2(M[i, j], M[i, k])
ay = math.atan2(sy, M[i, i])
az = math.atan2(M[j, i], -M[k, i])
else:
ax = math.atan2(-M[j, k], M[j, j])
ay = math.atan2(sy, M[i, i])
az = 0.0
else:
cy = math.sqrt(M[i, i] * M[i, i] + M[j, i] * M[j, i])
if cy > EPS:
ax = math.atan2(M[k, j], M[k, k])
ay = math.atan2(-M[k, i], cy)
az = math.atan2(M[j, i], M[i, i])
else:
ax = math.atan2(-M[j, k], M[j, j])
ay = math.atan2(-M[k, i], cy)
az = 0.0
if parity:
ax, ay, az = -ax, -ay, -az
if frame:
ax, az = az, ax
return vec((ax, ay, az)) | python | def mat2euler(rmat, axes="sxyz"):
try:
firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]
except (AttributeError, KeyError):
firstaxis, parity, repetition, frame = axes
i = firstaxis
j = _NEXT_AXIS[i + parity]
k = _NEXT_AXIS[i - parity + 1]
M = np.array(rmat, dtype=np.float32, copy=False)[:3, :3]
if repetition:
sy = math.sqrt(M[i, j] * M[i, j] + M[i, k] * M[i, k])
if sy > EPS:
ax = math.atan2(M[i, j], M[i, k])
ay = math.atan2(sy, M[i, i])
az = math.atan2(M[j, i], -M[k, i])
else:
ax = math.atan2(-M[j, k], M[j, j])
ay = math.atan2(sy, M[i, i])
az = 0.0
else:
cy = math.sqrt(M[i, i] * M[i, i] + M[j, i] * M[j, i])
if cy > EPS:
ax = math.atan2(M[k, j], M[k, k])
ay = math.atan2(-M[k, i], cy)
az = math.atan2(M[j, i], M[i, i])
else:
ax = math.atan2(-M[j, k], M[j, j])
ay = math.atan2(-M[k, i], cy)
az = 0.0
if parity:
ax, ay, az = -ax, -ay, -az
if frame:
ax, az = az, ax
return vec((ax, ay, az)) | [
"def",
"mat2euler",
"(",
"rmat",
",",
"axes",
"=",
"\"sxyz\"",
")",
":",
"try",
":",
"firstaxis",
",",
"parity",
",",
"repetition",
",",
"frame",
"=",
"_AXES2TUPLE",
"[",
"axes",
".",
"lower",
"(",
")",
"]",
"except",
"(",
"AttributeError",
",",
"KeyEr... | Converts given rotation matrix to euler angles in radian.
Args:
rmat: 3x3 rotation matrix
axes: One of 24 axis sequences as string or encoded tuple
Returns:
converted euler angles in radian vec3 float | [
"Converts",
"given",
"rotation",
"matrix",
"to",
"euler",
"angles",
"in",
"radian",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/utils/transform_utils.py#L278-L324 |
230,580 | StanfordVL/robosuite | robosuite/utils/transform_utils.py | pose2mat | def pose2mat(pose):
"""
Converts pose to homogeneous matrix.
Args:
pose: a (pos, orn) tuple where pos is vec3 float cartesian, and
orn is vec4 float quaternion.
Returns:
4x4 homogeneous matrix
"""
homo_pose_mat = np.zeros((4, 4), dtype=np.float32)
homo_pose_mat[:3, :3] = quat2mat(pose[1])
homo_pose_mat[:3, 3] = np.array(pose[0], dtype=np.float32)
homo_pose_mat[3, 3] = 1.
return homo_pose_mat | python | def pose2mat(pose):
homo_pose_mat = np.zeros((4, 4), dtype=np.float32)
homo_pose_mat[:3, :3] = quat2mat(pose[1])
homo_pose_mat[:3, 3] = np.array(pose[0], dtype=np.float32)
homo_pose_mat[3, 3] = 1.
return homo_pose_mat | [
"def",
"pose2mat",
"(",
"pose",
")",
":",
"homo_pose_mat",
"=",
"np",
".",
"zeros",
"(",
"(",
"4",
",",
"4",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"homo_pose_mat",
"[",
":",
"3",
",",
":",
"3",
"]",
"=",
"quat2mat",
"(",
"pose",
"[... | Converts pose to homogeneous matrix.
Args:
pose: a (pos, orn) tuple where pos is vec3 float cartesian, and
orn is vec4 float quaternion.
Returns:
4x4 homogeneous matrix | [
"Converts",
"pose",
"to",
"homogeneous",
"matrix",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/utils/transform_utils.py#L327-L342 |
230,581 | StanfordVL/robosuite | robosuite/utils/transform_utils.py | pose_inv | def pose_inv(pose):
"""
Computes the inverse of a homogenous matrix corresponding to the pose of some
frame B in frame A. The inverse is the pose of frame A in frame B.
Args:
pose: numpy array of shape (4,4) for the pose to inverse
Returns:
numpy array of shape (4,4) for the inverse pose
"""
# Note, the inverse of a pose matrix is the following
# [R t; 0 1]^-1 = [R.T -R.T*t; 0 1]
# Intuitively, this makes sense.
# The original pose matrix translates by t, then rotates by R.
# We just invert the rotation by applying R-1 = R.T, and also translate back.
# Since we apply translation first before rotation, we need to translate by
# -t in the original frame, which is -R-1*t in the new frame, and then rotate back by
# R-1 to align the axis again.
pose_inv = np.zeros((4, 4))
pose_inv[:3, :3] = pose[:3, :3].T
pose_inv[:3, 3] = -pose_inv[:3, :3].dot(pose[:3, 3])
pose_inv[3, 3] = 1.0
return pose_inv | python | def pose_inv(pose):
# Note, the inverse of a pose matrix is the following
# [R t; 0 1]^-1 = [R.T -R.T*t; 0 1]
# Intuitively, this makes sense.
# The original pose matrix translates by t, then rotates by R.
# We just invert the rotation by applying R-1 = R.T, and also translate back.
# Since we apply translation first before rotation, we need to translate by
# -t in the original frame, which is -R-1*t in the new frame, and then rotate back by
# R-1 to align the axis again.
pose_inv = np.zeros((4, 4))
pose_inv[:3, :3] = pose[:3, :3].T
pose_inv[:3, 3] = -pose_inv[:3, :3].dot(pose[:3, 3])
pose_inv[3, 3] = 1.0
return pose_inv | [
"def",
"pose_inv",
"(",
"pose",
")",
":",
"# Note, the inverse of a pose matrix is the following",
"# [R t; 0 1]^-1 = [R.T -R.T*t; 0 1]",
"# Intuitively, this makes sense.",
"# The original pose matrix translates by t, then rotates by R.",
"# We just invert the rotation by applying R-1 = R.T, an... | Computes the inverse of a homogenous matrix corresponding to the pose of some
frame B in frame A. The inverse is the pose of frame A in frame B.
Args:
pose: numpy array of shape (4,4) for the pose to inverse
Returns:
numpy array of shape (4,4) for the inverse pose | [
"Computes",
"the",
"inverse",
"of",
"a",
"homogenous",
"matrix",
"corresponding",
"to",
"the",
"pose",
"of",
"some",
"frame",
"B",
"in",
"frame",
"A",
".",
"The",
"inverse",
"is",
"the",
"pose",
"of",
"frame",
"A",
"in",
"frame",
"B",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/utils/transform_utils.py#L391-L417 |
230,582 | StanfordVL/robosuite | robosuite/utils/transform_utils.py | _skew_symmetric_translation | def _skew_symmetric_translation(pos_A_in_B):
"""
Helper function to get a skew symmetric translation matrix for converting quantities
between frames.
"""
return np.array(
[
0.,
-pos_A_in_B[2],
pos_A_in_B[1],
pos_A_in_B[2],
0.,
-pos_A_in_B[0],
-pos_A_in_B[1],
pos_A_in_B[0],
0.,
]
).reshape((3, 3)) | python | def _skew_symmetric_translation(pos_A_in_B):
return np.array(
[
0.,
-pos_A_in_B[2],
pos_A_in_B[1],
pos_A_in_B[2],
0.,
-pos_A_in_B[0],
-pos_A_in_B[1],
pos_A_in_B[0],
0.,
]
).reshape((3, 3)) | [
"def",
"_skew_symmetric_translation",
"(",
"pos_A_in_B",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"0.",
",",
"-",
"pos_A_in_B",
"[",
"2",
"]",
",",
"pos_A_in_B",
"[",
"1",
"]",
",",
"pos_A_in_B",
"[",
"2",
"]",
",",
"0.",
",",
"-",
"pos_A_in... | Helper function to get a skew symmetric translation matrix for converting quantities
between frames. | [
"Helper",
"function",
"to",
"get",
"a",
"skew",
"symmetric",
"translation",
"matrix",
"for",
"converting",
"quantities",
"between",
"frames",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/utils/transform_utils.py#L420-L437 |
230,583 | StanfordVL/robosuite | robosuite/utils/transform_utils.py | vel_in_A_to_vel_in_B | def vel_in_A_to_vel_in_B(vel_A, ang_vel_A, pose_A_in_B):
"""
Converts linear and angular velocity of a point in frame A to the equivalent in frame B.
Args:
vel_A: 3-dim iterable for linear velocity in A
ang_vel_A: 3-dim iterable for angular velocity in A
pose_A_in_B: numpy array of shape (4,4) corresponding to the pose of A in frame B
Returns:
vel_B, ang_vel_B: two numpy arrays of shape (3,) for the velocities in B
"""
pos_A_in_B = pose_A_in_B[:3, 3]
rot_A_in_B = pose_A_in_B[:3, :3]
skew_symm = _skew_symmetric_translation(pos_A_in_B)
vel_B = rot_A_in_B.dot(vel_A) + skew_symm.dot(rot_A_in_B.dot(ang_vel_A))
ang_vel_B = rot_A_in_B.dot(ang_vel_A)
return vel_B, ang_vel_B | python | def vel_in_A_to_vel_in_B(vel_A, ang_vel_A, pose_A_in_B):
pos_A_in_B = pose_A_in_B[:3, 3]
rot_A_in_B = pose_A_in_B[:3, :3]
skew_symm = _skew_symmetric_translation(pos_A_in_B)
vel_B = rot_A_in_B.dot(vel_A) + skew_symm.dot(rot_A_in_B.dot(ang_vel_A))
ang_vel_B = rot_A_in_B.dot(ang_vel_A)
return vel_B, ang_vel_B | [
"def",
"vel_in_A_to_vel_in_B",
"(",
"vel_A",
",",
"ang_vel_A",
",",
"pose_A_in_B",
")",
":",
"pos_A_in_B",
"=",
"pose_A_in_B",
"[",
":",
"3",
",",
"3",
"]",
"rot_A_in_B",
"=",
"pose_A_in_B",
"[",
":",
"3",
",",
":",
"3",
"]",
"skew_symm",
"=",
"_skew_sym... | Converts linear and angular velocity of a point in frame A to the equivalent in frame B.
Args:
vel_A: 3-dim iterable for linear velocity in A
ang_vel_A: 3-dim iterable for angular velocity in A
pose_A_in_B: numpy array of shape (4,4) corresponding to the pose of A in frame B
Returns:
vel_B, ang_vel_B: two numpy arrays of shape (3,) for the velocities in B | [
"Converts",
"linear",
"and",
"angular",
"velocity",
"of",
"a",
"point",
"in",
"frame",
"A",
"to",
"the",
"equivalent",
"in",
"frame",
"B",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/utils/transform_utils.py#L440-L457 |
230,584 | StanfordVL/robosuite | robosuite/utils/transform_utils.py | force_in_A_to_force_in_B | def force_in_A_to_force_in_B(force_A, torque_A, pose_A_in_B):
"""
Converts linear and rotational force at a point in frame A to the equivalent in frame B.
Args:
force_A: 3-dim iterable for linear force in A
torque_A: 3-dim iterable for rotational force (moment) in A
pose_A_in_B: numpy array of shape (4,4) corresponding to the pose of A in frame B
Returns:
force_B, torque_B: two numpy arrays of shape (3,) for the forces in B
"""
pos_A_in_B = pose_A_in_B[:3, 3]
rot_A_in_B = pose_A_in_B[:3, :3]
skew_symm = _skew_symmetric_translation(pos_A_in_B)
force_B = rot_A_in_B.T.dot(force_A)
torque_B = -rot_A_in_B.T.dot(skew_symm.dot(force_A)) + rot_A_in_B.T.dot(torque_A)
return force_B, torque_B | python | def force_in_A_to_force_in_B(force_A, torque_A, pose_A_in_B):
pos_A_in_B = pose_A_in_B[:3, 3]
rot_A_in_B = pose_A_in_B[:3, :3]
skew_symm = _skew_symmetric_translation(pos_A_in_B)
force_B = rot_A_in_B.T.dot(force_A)
torque_B = -rot_A_in_B.T.dot(skew_symm.dot(force_A)) + rot_A_in_B.T.dot(torque_A)
return force_B, torque_B | [
"def",
"force_in_A_to_force_in_B",
"(",
"force_A",
",",
"torque_A",
",",
"pose_A_in_B",
")",
":",
"pos_A_in_B",
"=",
"pose_A_in_B",
"[",
":",
"3",
",",
"3",
"]",
"rot_A_in_B",
"=",
"pose_A_in_B",
"[",
":",
"3",
",",
":",
"3",
"]",
"skew_symm",
"=",
"_ske... | Converts linear and rotational force at a point in frame A to the equivalent in frame B.
Args:
force_A: 3-dim iterable for linear force in A
torque_A: 3-dim iterable for rotational force (moment) in A
pose_A_in_B: numpy array of shape (4,4) corresponding to the pose of A in frame B
Returns:
force_B, torque_B: two numpy arrays of shape (3,) for the forces in B | [
"Converts",
"linear",
"and",
"rotational",
"force",
"at",
"a",
"point",
"in",
"frame",
"A",
"to",
"the",
"equivalent",
"in",
"frame",
"B",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/utils/transform_utils.py#L460-L477 |
230,585 | StanfordVL/robosuite | robosuite/utils/transform_utils.py | rotation_matrix | def rotation_matrix(angle, direction, point=None):
"""
Returns matrix to rotate about axis defined by point and direction.
Examples:
>>> angle = (random.random() - 0.5) * (2*math.pi)
>>> direc = numpy.random.random(3) - 0.5
>>> point = numpy.random.random(3) - 0.5
>>> R0 = rotation_matrix(angle, direc, point)
>>> R1 = rotation_matrix(angle-2*math.pi, direc, point)
>>> is_same_transform(R0, R1)
True
>>> R0 = rotation_matrix(angle, direc, point)
>>> R1 = rotation_matrix(-angle, -direc, point)
>>> is_same_transform(R0, R1)
True
>>> I = numpy.identity(4, numpy.float32)
>>> numpy.allclose(I, rotation_matrix(math.pi*2, direc))
True
>>> numpy.allclose(2., numpy.trace(rotation_matrix(math.pi/2,
... direc, point)))
True
"""
sina = math.sin(angle)
cosa = math.cos(angle)
direction = unit_vector(direction[:3])
# rotation matrix around unit vector
R = np.array(
((cosa, 0.0, 0.0), (0.0, cosa, 0.0), (0.0, 0.0, cosa)), dtype=np.float32
)
R += np.outer(direction, direction) * (1.0 - cosa)
direction *= sina
R += np.array(
(
(0.0, -direction[2], direction[1]),
(direction[2], 0.0, -direction[0]),
(-direction[1], direction[0], 0.0),
),
dtype=np.float32,
)
M = np.identity(4)
M[:3, :3] = R
if point is not None:
# rotation not around origin
point = np.array(point[:3], dtype=np.float32, copy=False)
M[:3, 3] = point - np.dot(R, point)
return M | python | def rotation_matrix(angle, direction, point=None):
sina = math.sin(angle)
cosa = math.cos(angle)
direction = unit_vector(direction[:3])
# rotation matrix around unit vector
R = np.array(
((cosa, 0.0, 0.0), (0.0, cosa, 0.0), (0.0, 0.0, cosa)), dtype=np.float32
)
R += np.outer(direction, direction) * (1.0 - cosa)
direction *= sina
R += np.array(
(
(0.0, -direction[2], direction[1]),
(direction[2], 0.0, -direction[0]),
(-direction[1], direction[0], 0.0),
),
dtype=np.float32,
)
M = np.identity(4)
M[:3, :3] = R
if point is not None:
# rotation not around origin
point = np.array(point[:3], dtype=np.float32, copy=False)
M[:3, 3] = point - np.dot(R, point)
return M | [
"def",
"rotation_matrix",
"(",
"angle",
",",
"direction",
",",
"point",
"=",
"None",
")",
":",
"sina",
"=",
"math",
".",
"sin",
"(",
"angle",
")",
"cosa",
"=",
"math",
".",
"cos",
"(",
"angle",
")",
"direction",
"=",
"unit_vector",
"(",
"direction",
... | Returns matrix to rotate about axis defined by point and direction.
Examples:
>>> angle = (random.random() - 0.5) * (2*math.pi)
>>> direc = numpy.random.random(3) - 0.5
>>> point = numpy.random.random(3) - 0.5
>>> R0 = rotation_matrix(angle, direc, point)
>>> R1 = rotation_matrix(angle-2*math.pi, direc, point)
>>> is_same_transform(R0, R1)
True
>>> R0 = rotation_matrix(angle, direc, point)
>>> R1 = rotation_matrix(-angle, -direc, point)
>>> is_same_transform(R0, R1)
True
>>> I = numpy.identity(4, numpy.float32)
>>> numpy.allclose(I, rotation_matrix(math.pi*2, direc))
True
>>> numpy.allclose(2., numpy.trace(rotation_matrix(math.pi/2,
... direc, point)))
True | [
"Returns",
"matrix",
"to",
"rotate",
"about",
"axis",
"defined",
"by",
"point",
"and",
"direction",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/utils/transform_utils.py#L480-L528 |
230,586 | StanfordVL/robosuite | robosuite/utils/transform_utils.py | make_pose | def make_pose(translation, rotation):
"""
Makes a homogenous pose matrix from a translation vector and a rotation matrix.
Args:
translation: a 3-dim iterable
rotation: a 3x3 matrix
Returns:
pose: a 4x4 homogenous matrix
"""
pose = np.zeros((4, 4))
pose[:3, :3] = rotation
pose[:3, 3] = translation
pose[3, 3] = 1.0
return pose | python | def make_pose(translation, rotation):
pose = np.zeros((4, 4))
pose[:3, :3] = rotation
pose[:3, 3] = translation
pose[3, 3] = 1.0
return pose | [
"def",
"make_pose",
"(",
"translation",
",",
"rotation",
")",
":",
"pose",
"=",
"np",
".",
"zeros",
"(",
"(",
"4",
",",
"4",
")",
")",
"pose",
"[",
":",
"3",
",",
":",
"3",
"]",
"=",
"rotation",
"pose",
"[",
":",
"3",
",",
"3",
"]",
"=",
"t... | Makes a homogenous pose matrix from a translation vector and a rotation matrix.
Args:
translation: a 3-dim iterable
rotation: a 3x3 matrix
Returns:
pose: a 4x4 homogenous matrix | [
"Makes",
"a",
"homogenous",
"pose",
"matrix",
"from",
"a",
"translation",
"vector",
"and",
"a",
"rotation",
"matrix",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/utils/transform_utils.py#L531-L546 |
230,587 | StanfordVL/robosuite | robosuite/utils/transform_utils.py | get_pose_error | def get_pose_error(target_pose, current_pose):
"""
Computes the error corresponding to target pose - current pose as a 6-dim vector.
The first 3 components correspond to translational error while the last 3 components
correspond to the rotational error.
Args:
target_pose: a 4x4 homogenous matrix for the target pose
current_pose: a 4x4 homogenous matrix for the current pose
Returns:
A 6-dim numpy array for the pose error.
"""
error = np.zeros(6)
# compute translational error
target_pos = target_pose[:3, 3]
current_pos = current_pose[:3, 3]
pos_err = target_pos - current_pos
# compute rotational error
r1 = current_pose[:3, 0]
r2 = current_pose[:3, 1]
r3 = current_pose[:3, 2]
r1d = target_pose[:3, 0]
r2d = target_pose[:3, 1]
r3d = target_pose[:3, 2]
rot_err = 0.5 * (np.cross(r1, r1d) + np.cross(r2, r2d) + np.cross(r3, r3d))
error[:3] = pos_err
error[3:] = rot_err
return error | python | def get_pose_error(target_pose, current_pose):
error = np.zeros(6)
# compute translational error
target_pos = target_pose[:3, 3]
current_pos = current_pose[:3, 3]
pos_err = target_pos - current_pos
# compute rotational error
r1 = current_pose[:3, 0]
r2 = current_pose[:3, 1]
r3 = current_pose[:3, 2]
r1d = target_pose[:3, 0]
r2d = target_pose[:3, 1]
r3d = target_pose[:3, 2]
rot_err = 0.5 * (np.cross(r1, r1d) + np.cross(r2, r2d) + np.cross(r3, r3d))
error[:3] = pos_err
error[3:] = rot_err
return error | [
"def",
"get_pose_error",
"(",
"target_pose",
",",
"current_pose",
")",
":",
"error",
"=",
"np",
".",
"zeros",
"(",
"6",
")",
"# compute translational error",
"target_pos",
"=",
"target_pose",
"[",
":",
"3",
",",
"3",
"]",
"current_pos",
"=",
"current_pose",
... | Computes the error corresponding to target pose - current pose as a 6-dim vector.
The first 3 components correspond to translational error while the last 3 components
correspond to the rotational error.
Args:
target_pose: a 4x4 homogenous matrix for the target pose
current_pose: a 4x4 homogenous matrix for the current pose
Returns:
A 6-dim numpy array for the pose error. | [
"Computes",
"the",
"error",
"corresponding",
"to",
"target",
"pose",
"-",
"current",
"pose",
"as",
"a",
"6",
"-",
"dim",
"vector",
".",
"The",
"first",
"3",
"components",
"correspond",
"to",
"translational",
"error",
"while",
"the",
"last",
"3",
"components"... | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/utils/transform_utils.py#L622-L653 |
230,588 | StanfordVL/robosuite | robosuite/environments/base.py | make | def make(env_name, *args, **kwargs):
"""Try to get the equivalent functionality of gym.make in a sloppy way."""
if env_name not in REGISTERED_ENVS:
raise Exception(
"Environment {} not found. Make sure it is a registered environment among: {}".format(
env_name, ", ".join(REGISTERED_ENVS)
)
)
return REGISTERED_ENVS[env_name](*args, **kwargs) | python | def make(env_name, *args, **kwargs):
if env_name not in REGISTERED_ENVS:
raise Exception(
"Environment {} not found. Make sure it is a registered environment among: {}".format(
env_name, ", ".join(REGISTERED_ENVS)
)
)
return REGISTERED_ENVS[env_name](*args, **kwargs) | [
"def",
"make",
"(",
"env_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"env_name",
"not",
"in",
"REGISTERED_ENVS",
":",
"raise",
"Exception",
"(",
"\"Environment {} not found. Make sure it is a registered environment among: {}\"",
".",
"format",
... | Try to get the equivalent functionality of gym.make in a sloppy way. | [
"Try",
"to",
"get",
"the",
"equivalent",
"functionality",
"of",
"gym",
".",
"make",
"in",
"a",
"sloppy",
"way",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/base.py#L14-L22 |
230,589 | StanfordVL/robosuite | robosuite/environments/base.py | MujocoEnv.initialize_time | def initialize_time(self, control_freq):
"""
Initializes the time constants used for simulation.
"""
self.cur_time = 0
self.model_timestep = self.sim.model.opt.timestep
if self.model_timestep <= 0:
raise XMLError("xml model defined non-positive time step")
self.control_freq = control_freq
if control_freq <= 0:
raise SimulationError(
"control frequency {} is invalid".format(control_freq)
)
self.control_timestep = 1. / control_freq | python | def initialize_time(self, control_freq):
self.cur_time = 0
self.model_timestep = self.sim.model.opt.timestep
if self.model_timestep <= 0:
raise XMLError("xml model defined non-positive time step")
self.control_freq = control_freq
if control_freq <= 0:
raise SimulationError(
"control frequency {} is invalid".format(control_freq)
)
self.control_timestep = 1. / control_freq | [
"def",
"initialize_time",
"(",
"self",
",",
"control_freq",
")",
":",
"self",
".",
"cur_time",
"=",
"0",
"self",
".",
"model_timestep",
"=",
"self",
".",
"sim",
".",
"model",
".",
"opt",
".",
"timestep",
"if",
"self",
".",
"model_timestep",
"<=",
"0",
... | Initializes the time constants used for simulation. | [
"Initializes",
"the",
"time",
"constants",
"used",
"for",
"simulation",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/base.py#L115-L128 |
230,590 | StanfordVL/robosuite | robosuite/environments/base.py | MujocoEnv.reset | def reset(self):
"""Resets simulation."""
# TODO(yukez): investigate black screen of death
# if there is an active viewer window, destroy it
self._destroy_viewer()
self._reset_internal()
self.sim.forward()
return self._get_observation() | python | def reset(self):
# TODO(yukez): investigate black screen of death
# if there is an active viewer window, destroy it
self._destroy_viewer()
self._reset_internal()
self.sim.forward()
return self._get_observation() | [
"def",
"reset",
"(",
"self",
")",
":",
"# TODO(yukez): investigate black screen of death",
"# if there is an active viewer window, destroy it",
"self",
".",
"_destroy_viewer",
"(",
")",
"self",
".",
"_reset_internal",
"(",
")",
"self",
".",
"sim",
".",
"forward",
"(",
... | Resets simulation. | [
"Resets",
"simulation",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/base.py#L142-L149 |
230,591 | StanfordVL/robosuite | robosuite/environments/base.py | MujocoEnv.step | def step(self, action):
"""Takes a step in simulation with control command @action."""
if self.done:
raise ValueError("executing action in terminated episode")
self.timestep += 1
self._pre_action(action)
end_time = self.cur_time + self.control_timestep
while self.cur_time < end_time:
self.sim.step()
self.cur_time += self.model_timestep
reward, done, info = self._post_action(action)
return self._get_observation(), reward, done, info | python | def step(self, action):
if self.done:
raise ValueError("executing action in terminated episode")
self.timestep += 1
self._pre_action(action)
end_time = self.cur_time + self.control_timestep
while self.cur_time < end_time:
self.sim.step()
self.cur_time += self.model_timestep
reward, done, info = self._post_action(action)
return self._get_observation(), reward, done, info | [
"def",
"step",
"(",
"self",
",",
"action",
")",
":",
"if",
"self",
".",
"done",
":",
"raise",
"ValueError",
"(",
"\"executing action in terminated episode\"",
")",
"self",
".",
"timestep",
"+=",
"1",
"self",
".",
"_pre_action",
"(",
"action",
")",
"end_time"... | Takes a step in simulation with control command @action. | [
"Takes",
"a",
"step",
"in",
"simulation",
"with",
"control",
"command"
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/base.py#L192-L204 |
230,592 | StanfordVL/robosuite | robosuite/environments/base.py | MujocoEnv._post_action | def _post_action(self, action):
"""Do any housekeeping after taking an action."""
reward = self.reward(action)
# done if number of elapsed timesteps is greater than horizon
self.done = (self.timestep >= self.horizon) and not self.ignore_done
return reward, self.done, {} | python | def _post_action(self, action):
reward = self.reward(action)
# done if number of elapsed timesteps is greater than horizon
self.done = (self.timestep >= self.horizon) and not self.ignore_done
return reward, self.done, {} | [
"def",
"_post_action",
"(",
"self",
",",
"action",
")",
":",
"reward",
"=",
"self",
".",
"reward",
"(",
"action",
")",
"# done if number of elapsed timesteps is greater than horizon",
"self",
".",
"done",
"=",
"(",
"self",
".",
"timestep",
">=",
"self",
".",
"... | Do any housekeeping after taking an action. | [
"Do",
"any",
"housekeeping",
"after",
"taking",
"an",
"action",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/base.py#L210-L216 |
230,593 | StanfordVL/robosuite | robosuite/environments/base.py | MujocoEnv.reset_from_xml_string | def reset_from_xml_string(self, xml_string):
"""Reloads the environment from an XML description of the environment."""
# if there is an active viewer window, destroy it
self.close()
# load model from xml
self.mjpy_model = load_model_from_xml(xml_string)
self.sim = MjSim(self.mjpy_model)
self.initialize_time(self.control_freq)
if self.has_renderer and self.viewer is None:
self.viewer = MujocoPyRenderer(self.sim)
self.viewer.viewer.vopt.geomgroup[0] = (
1 if self.render_collision_mesh else 0
)
self.viewer.viewer.vopt.geomgroup[1] = 1 if self.render_visual_mesh else 0
# hiding the overlay speeds up rendering significantly
self.viewer.viewer._hide_overlay = True
elif self.has_offscreen_renderer:
render_context = MjRenderContextOffscreen(self.sim)
render_context.vopt.geomgroup[0] = 1 if self.render_collision_mesh else 0
render_context.vopt.geomgroup[1] = 1 if self.render_visual_mesh else 0
self.sim.add_render_context(render_context)
self.sim_state_initial = self.sim.get_state()
self._get_reference()
self.cur_time = 0
self.timestep = 0
self.done = False
# necessary to refresh MjData
self.sim.forward() | python | def reset_from_xml_string(self, xml_string):
# if there is an active viewer window, destroy it
self.close()
# load model from xml
self.mjpy_model = load_model_from_xml(xml_string)
self.sim = MjSim(self.mjpy_model)
self.initialize_time(self.control_freq)
if self.has_renderer and self.viewer is None:
self.viewer = MujocoPyRenderer(self.sim)
self.viewer.viewer.vopt.geomgroup[0] = (
1 if self.render_collision_mesh else 0
)
self.viewer.viewer.vopt.geomgroup[1] = 1 if self.render_visual_mesh else 0
# hiding the overlay speeds up rendering significantly
self.viewer.viewer._hide_overlay = True
elif self.has_offscreen_renderer:
render_context = MjRenderContextOffscreen(self.sim)
render_context.vopt.geomgroup[0] = 1 if self.render_collision_mesh else 0
render_context.vopt.geomgroup[1] = 1 if self.render_visual_mesh else 0
self.sim.add_render_context(render_context)
self.sim_state_initial = self.sim.get_state()
self._get_reference()
self.cur_time = 0
self.timestep = 0
self.done = False
# necessary to refresh MjData
self.sim.forward() | [
"def",
"reset_from_xml_string",
"(",
"self",
",",
"xml_string",
")",
":",
"# if there is an active viewer window, destroy it",
"self",
".",
"close",
"(",
")",
"# load model from xml",
"self",
".",
"mjpy_model",
"=",
"load_model_from_xml",
"(",
"xml_string",
")",
"self",... | Reloads the environment from an XML description of the environment. | [
"Reloads",
"the",
"environment",
"from",
"an",
"XML",
"description",
"of",
"the",
"environment",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/base.py#L254-L288 |
230,594 | StanfordVL/robosuite | robosuite/environments/base.py | MujocoEnv.find_contacts | def find_contacts(self, geoms_1, geoms_2):
"""
Finds contact between two geom groups.
Args:
geoms_1: a list of geom names (string)
geoms_2: another list of geom names (string)
Returns:
iterator of all contacts between @geoms_1 and @geoms_2
"""
for contact in self.sim.data.contact[0 : self.sim.data.ncon]:
# check contact geom in geoms
c1_in_g1 = self.sim.model.geom_id2name(contact.geom1) in geoms_1
c2_in_g2 = self.sim.model.geom_id2name(contact.geom2) in geoms_2
# check contact geom in geoms (flipped)
c2_in_g1 = self.sim.model.geom_id2name(contact.geom2) in geoms_1
c1_in_g2 = self.sim.model.geom_id2name(contact.geom1) in geoms_2
if (c1_in_g1 and c2_in_g2) or (c1_in_g2 and c2_in_g1):
yield contact | python | def find_contacts(self, geoms_1, geoms_2):
for contact in self.sim.data.contact[0 : self.sim.data.ncon]:
# check contact geom in geoms
c1_in_g1 = self.sim.model.geom_id2name(contact.geom1) in geoms_1
c2_in_g2 = self.sim.model.geom_id2name(contact.geom2) in geoms_2
# check contact geom in geoms (flipped)
c2_in_g1 = self.sim.model.geom_id2name(contact.geom2) in geoms_1
c1_in_g2 = self.sim.model.geom_id2name(contact.geom1) in geoms_2
if (c1_in_g1 and c2_in_g2) or (c1_in_g2 and c2_in_g1):
yield contact | [
"def",
"find_contacts",
"(",
"self",
",",
"geoms_1",
",",
"geoms_2",
")",
":",
"for",
"contact",
"in",
"self",
".",
"sim",
".",
"data",
".",
"contact",
"[",
"0",
":",
"self",
".",
"sim",
".",
"data",
".",
"ncon",
"]",
":",
"# check contact geom in geom... | Finds contact between two geom groups.
Args:
geoms_1: a list of geom names (string)
geoms_2: another list of geom names (string)
Returns:
iterator of all contacts between @geoms_1 and @geoms_2 | [
"Finds",
"contact",
"between",
"two",
"geom",
"groups",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/base.py#L290-L309 |
230,595 | StanfordVL/robosuite | robosuite/environments/sawyer.py | SawyerEnv._reset_internal | def _reset_internal(self):
"""
Sets initial pose of arm and grippers.
"""
super()._reset_internal()
self.sim.data.qpos[self._ref_joint_pos_indexes] = self.mujoco_robot.init_qpos
if self.has_gripper:
self.sim.data.qpos[
self._ref_joint_gripper_actuator_indexes
] = self.gripper.init_qpos | python | def _reset_internal(self):
super()._reset_internal()
self.sim.data.qpos[self._ref_joint_pos_indexes] = self.mujoco_robot.init_qpos
if self.has_gripper:
self.sim.data.qpos[
self._ref_joint_gripper_actuator_indexes
] = self.gripper.init_qpos | [
"def",
"_reset_internal",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"_reset_internal",
"(",
")",
"self",
".",
"sim",
".",
"data",
".",
"qpos",
"[",
"self",
".",
"_ref_joint_pos_indexes",
"]",
"=",
"self",
".",
"mujoco_robot",
".",
"init_qpos",
"if",... | Sets initial pose of arm and grippers. | [
"Sets",
"initial",
"pose",
"of",
"arm",
"and",
"grippers",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/sawyer.py#L106-L116 |
230,596 | StanfordVL/robosuite | robosuite/environments/sawyer.py | SawyerEnv._get_reference | def _get_reference(self):
"""
Sets up necessary reference for robots, grippers, and objects.
"""
super()._get_reference()
# indices for joints in qpos, qvel
self.robot_joints = list(self.mujoco_robot.joints)
self._ref_joint_pos_indexes = [
self.sim.model.get_joint_qpos_addr(x) for x in self.robot_joints
]
self._ref_joint_vel_indexes = [
self.sim.model.get_joint_qvel_addr(x) for x in self.robot_joints
]
if self.use_indicator_object:
ind_qpos = self.sim.model.get_joint_qpos_addr("pos_indicator")
self._ref_indicator_pos_low, self._ref_indicator_pos_high = ind_qpos
ind_qvel = self.sim.model.get_joint_qvel_addr("pos_indicator")
self._ref_indicator_vel_low, self._ref_indicator_vel_high = ind_qvel
self.indicator_id = self.sim.model.body_name2id("pos_indicator")
# indices for grippers in qpos, qvel
if self.has_gripper:
self.gripper_joints = list(self.gripper.joints)
self._ref_gripper_joint_pos_indexes = [
self.sim.model.get_joint_qpos_addr(x) for x in self.gripper_joints
]
self._ref_gripper_joint_vel_indexes = [
self.sim.model.get_joint_qvel_addr(x) for x in self.gripper_joints
]
# indices for joint pos actuation, joint vel actuation, gripper actuation
self._ref_joint_pos_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("pos")
]
self._ref_joint_vel_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("vel")
]
if self.has_gripper:
self._ref_joint_gripper_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("gripper")
]
# IDs of sites for gripper visualization
self.eef_site_id = self.sim.model.site_name2id("grip_site")
self.eef_cylinder_id = self.sim.model.site_name2id("grip_site_cylinder") | python | def _get_reference(self):
super()._get_reference()
# indices for joints in qpos, qvel
self.robot_joints = list(self.mujoco_robot.joints)
self._ref_joint_pos_indexes = [
self.sim.model.get_joint_qpos_addr(x) for x in self.robot_joints
]
self._ref_joint_vel_indexes = [
self.sim.model.get_joint_qvel_addr(x) for x in self.robot_joints
]
if self.use_indicator_object:
ind_qpos = self.sim.model.get_joint_qpos_addr("pos_indicator")
self._ref_indicator_pos_low, self._ref_indicator_pos_high = ind_qpos
ind_qvel = self.sim.model.get_joint_qvel_addr("pos_indicator")
self._ref_indicator_vel_low, self._ref_indicator_vel_high = ind_qvel
self.indicator_id = self.sim.model.body_name2id("pos_indicator")
# indices for grippers in qpos, qvel
if self.has_gripper:
self.gripper_joints = list(self.gripper.joints)
self._ref_gripper_joint_pos_indexes = [
self.sim.model.get_joint_qpos_addr(x) for x in self.gripper_joints
]
self._ref_gripper_joint_vel_indexes = [
self.sim.model.get_joint_qvel_addr(x) for x in self.gripper_joints
]
# indices for joint pos actuation, joint vel actuation, gripper actuation
self._ref_joint_pos_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("pos")
]
self._ref_joint_vel_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("vel")
]
if self.has_gripper:
self._ref_joint_gripper_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("gripper")
]
# IDs of sites for gripper visualization
self.eef_site_id = self.sim.model.site_name2id("grip_site")
self.eef_cylinder_id = self.sim.model.site_name2id("grip_site_cylinder") | [
"def",
"_get_reference",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"_get_reference",
"(",
")",
"# indices for joints in qpos, qvel",
"self",
".",
"robot_joints",
"=",
"list",
"(",
"self",
".",
"mujoco_robot",
".",
"joints",
")",
"self",
".",
"_ref_joint_p... | Sets up necessary reference for robots, grippers, and objects. | [
"Sets",
"up",
"necessary",
"reference",
"for",
"robots",
"grippers",
"and",
"objects",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/sawyer.py#L118-L174 |
230,597 | StanfordVL/robosuite | robosuite/environments/sawyer.py | SawyerEnv._pre_action | def _pre_action(self, action):
"""
Overrides the superclass method to actuate the robot with the
passed joint velocities and gripper control.
Args:
action (numpy array): The control to apply to the robot. The first
@self.mujoco_robot.dof dimensions should be the desired
normalized joint velocities and if the robot has
a gripper, the next @self.gripper.dof dimensions should be
actuation controls for the gripper.
"""
# clip actions into valid range
assert len(action) == self.dof, "environment got invalid action dimension"
low, high = self.action_spec
action = np.clip(action, low, high)
if self.has_gripper:
arm_action = action[: self.mujoco_robot.dof]
gripper_action_in = action[
self.mujoco_robot.dof : self.mujoco_robot.dof + self.gripper.dof
]
gripper_action_actual = self.gripper.format_action(gripper_action_in)
action = np.concatenate([arm_action, gripper_action_actual])
# rescale normalized action to control ranges
ctrl_range = self.sim.model.actuator_ctrlrange
bias = 0.5 * (ctrl_range[:, 1] + ctrl_range[:, 0])
weight = 0.5 * (ctrl_range[:, 1] - ctrl_range[:, 0])
applied_action = bias + weight * action
self.sim.data.ctrl[:] = applied_action
# gravity compensation
self.sim.data.qfrc_applied[
self._ref_joint_vel_indexes
] = self.sim.data.qfrc_bias[self._ref_joint_vel_indexes]
if self.use_indicator_object:
self.sim.data.qfrc_applied[
self._ref_indicator_vel_low : self._ref_indicator_vel_high
] = self.sim.data.qfrc_bias[
self._ref_indicator_vel_low : self._ref_indicator_vel_high
] | python | def _pre_action(self, action):
# clip actions into valid range
assert len(action) == self.dof, "environment got invalid action dimension"
low, high = self.action_spec
action = np.clip(action, low, high)
if self.has_gripper:
arm_action = action[: self.mujoco_robot.dof]
gripper_action_in = action[
self.mujoco_robot.dof : self.mujoco_robot.dof + self.gripper.dof
]
gripper_action_actual = self.gripper.format_action(gripper_action_in)
action = np.concatenate([arm_action, gripper_action_actual])
# rescale normalized action to control ranges
ctrl_range = self.sim.model.actuator_ctrlrange
bias = 0.5 * (ctrl_range[:, 1] + ctrl_range[:, 0])
weight = 0.5 * (ctrl_range[:, 1] - ctrl_range[:, 0])
applied_action = bias + weight * action
self.sim.data.ctrl[:] = applied_action
# gravity compensation
self.sim.data.qfrc_applied[
self._ref_joint_vel_indexes
] = self.sim.data.qfrc_bias[self._ref_joint_vel_indexes]
if self.use_indicator_object:
self.sim.data.qfrc_applied[
self._ref_indicator_vel_low : self._ref_indicator_vel_high
] = self.sim.data.qfrc_bias[
self._ref_indicator_vel_low : self._ref_indicator_vel_high
] | [
"def",
"_pre_action",
"(",
"self",
",",
"action",
")",
":",
"# clip actions into valid range",
"assert",
"len",
"(",
"action",
")",
"==",
"self",
".",
"dof",
",",
"\"environment got invalid action dimension\"",
"low",
",",
"high",
"=",
"self",
".",
"action_spec",
... | Overrides the superclass method to actuate the robot with the
passed joint velocities and gripper control.
Args:
action (numpy array): The control to apply to the robot. The first
@self.mujoco_robot.dof dimensions should be the desired
normalized joint velocities and if the robot has
a gripper, the next @self.gripper.dof dimensions should be
actuation controls for the gripper. | [
"Overrides",
"the",
"superclass",
"method",
"to",
"actuate",
"the",
"robot",
"with",
"the",
"passed",
"joint",
"velocities",
"and",
"gripper",
"control",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/sawyer.py#L184-L227 |
230,598 | StanfordVL/robosuite | robosuite/scripts/demo_collect_and_playback_data.py | collect_random_trajectory | def collect_random_trajectory(env, timesteps=1000):
"""Run a random policy to collect trajectories.
The rollout trajectory is saved to files in npz format.
Modify the DataCollectionWrapper wrapper to add new fields or change data formats.
"""
obs = env.reset()
dof = env.dof
for t in range(timesteps):
action = 0.5 * np.random.randn(dof)
obs, reward, done, info = env.step(action)
env.render()
if t % 100 == 0:
print(t) | python | def collect_random_trajectory(env, timesteps=1000):
obs = env.reset()
dof = env.dof
for t in range(timesteps):
action = 0.5 * np.random.randn(dof)
obs, reward, done, info = env.step(action)
env.render()
if t % 100 == 0:
print(t) | [
"def",
"collect_random_trajectory",
"(",
"env",
",",
"timesteps",
"=",
"1000",
")",
":",
"obs",
"=",
"env",
".",
"reset",
"(",
")",
"dof",
"=",
"env",
".",
"dof",
"for",
"t",
"in",
"range",
"(",
"timesteps",
")",
":",
"action",
"=",
"0.5",
"*",
"np... | Run a random policy to collect trajectories.
The rollout trajectory is saved to files in npz format.
Modify the DataCollectionWrapper wrapper to add new fields or change data formats. | [
"Run",
"a",
"random",
"policy",
"to",
"collect",
"trajectories",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/scripts/demo_collect_and_playback_data.py#L17-L32 |
230,599 | StanfordVL/robosuite | robosuite/scripts/demo_collect_and_playback_data.py | playback_trajectory | def playback_trajectory(env, ep_dir):
"""Playback data from an episode.
Args:
ep_dir: The path to the directory containing data for an episode.
"""
# first reload the model from the xml
xml_path = os.path.join(ep_dir, "model.xml")
with open(xml_path, "r") as f:
env.reset_from_xml_string(f.read())
state_paths = os.path.join(ep_dir, "state_*.npz")
# read states back, load them one by one, and render
t = 0
for state_file in sorted(glob(state_paths)):
print(state_file)
dic = np.load(state_file)
states = dic["states"]
for state in states:
env.sim.set_state_from_flattened(state)
env.sim.forward()
env.render()
t += 1
if t % 100 == 0:
print(t) | python | def playback_trajectory(env, ep_dir):
# first reload the model from the xml
xml_path = os.path.join(ep_dir, "model.xml")
with open(xml_path, "r") as f:
env.reset_from_xml_string(f.read())
state_paths = os.path.join(ep_dir, "state_*.npz")
# read states back, load them one by one, and render
t = 0
for state_file in sorted(glob(state_paths)):
print(state_file)
dic = np.load(state_file)
states = dic["states"]
for state in states:
env.sim.set_state_from_flattened(state)
env.sim.forward()
env.render()
t += 1
if t % 100 == 0:
print(t) | [
"def",
"playback_trajectory",
"(",
"env",
",",
"ep_dir",
")",
":",
"# first reload the model from the xml",
"xml_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ep_dir",
",",
"\"model.xml\"",
")",
"with",
"open",
"(",
"xml_path",
",",
"\"r\"",
")",
"as",
"... | Playback data from an episode.
Args:
ep_dir: The path to the directory containing data for an episode. | [
"Playback",
"data",
"from",
"an",
"episode",
"."
] | 65cd16810e2ed647e3ec88746af3412065b7f278 | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/scripts/demo_collect_and_playback_data.py#L35-L61 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.