repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/models.py | Model.set_database | def set_database(self, db):
'''
Sets the `Database` that this model instance belongs to.
This is done automatically when the instance is read from the database or written to it.
'''
# This can not be imported globally due to circular import
from .database import Database
assert isinstance(db, Database), "database must be database.Database instance"
self._database = db | python | def set_database(self, db):
'''
Sets the `Database` that this model instance belongs to.
This is done automatically when the instance is read from the database or written to it.
'''
# This can not be imported globally due to circular import
from .database import Database
assert isinstance(db, Database), "database must be database.Database instance"
self._database = db | [
"def",
"set_database",
"(",
"self",
",",
"db",
")",
":",
"# This can not be imported globally due to circular import",
"from",
".",
"database",
"import",
"Database",
"assert",
"isinstance",
"(",
"db",
",",
"Database",
")",
",",
"\"database must be database.Database instan... | Sets the `Database` that this model instance belongs to.
This is done automatically when the instance is read from the database or written to it. | [
"Sets",
"the",
"Database",
"that",
"this",
"model",
"instance",
"belongs",
"to",
".",
"This",
"is",
"done",
"automatically",
"when",
"the",
"instance",
"is",
"read",
"from",
"the",
"database",
"or",
"written",
"to",
"it",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/models.py#L153-L161 | train | 222,300 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/models.py | Model.from_tsv | def from_tsv(cls, line, field_names, timezone_in_use=pytz.utc, database=None):
'''
Create a model instance from a tab-separated line. The line may or may not include a newline.
The `field_names` list must match the fields defined in the model, but does not have to include all of them.
- `line`: the TSV-formatted data.
- `field_names`: names of the model fields in the data.
- `timezone_in_use`: the timezone to use when parsing dates and datetimes.
- `database`: if given, sets the database that this instance belongs to.
'''
from six import next
values = iter(parse_tsv(line))
kwargs = {}
for name in field_names:
field = getattr(cls, name)
kwargs[name] = field.to_python(next(values), timezone_in_use)
obj = cls(**kwargs)
if database is not None:
obj.set_database(database)
return obj | python | def from_tsv(cls, line, field_names, timezone_in_use=pytz.utc, database=None):
'''
Create a model instance from a tab-separated line. The line may or may not include a newline.
The `field_names` list must match the fields defined in the model, but does not have to include all of them.
- `line`: the TSV-formatted data.
- `field_names`: names of the model fields in the data.
- `timezone_in_use`: the timezone to use when parsing dates and datetimes.
- `database`: if given, sets the database that this instance belongs to.
'''
from six import next
values = iter(parse_tsv(line))
kwargs = {}
for name in field_names:
field = getattr(cls, name)
kwargs[name] = field.to_python(next(values), timezone_in_use)
obj = cls(**kwargs)
if database is not None:
obj.set_database(database)
return obj | [
"def",
"from_tsv",
"(",
"cls",
",",
"line",
",",
"field_names",
",",
"timezone_in_use",
"=",
"pytz",
".",
"utc",
",",
"database",
"=",
"None",
")",
":",
"from",
"six",
"import",
"next",
"values",
"=",
"iter",
"(",
"parse_tsv",
"(",
"line",
")",
")",
... | Create a model instance from a tab-separated line. The line may or may not include a newline.
The `field_names` list must match the fields defined in the model, but does not have to include all of them.
- `line`: the TSV-formatted data.
- `field_names`: names of the model fields in the data.
- `timezone_in_use`: the timezone to use when parsing dates and datetimes.
- `database`: if given, sets the database that this instance belongs to. | [
"Create",
"a",
"model",
"instance",
"from",
"a",
"tab",
"-",
"separated",
"line",
".",
"The",
"line",
"may",
"or",
"may",
"not",
"include",
"a",
"newline",
".",
"The",
"field_names",
"list",
"must",
"match",
"the",
"fields",
"defined",
"in",
"the",
"mode... | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/models.py#L207-L228 | train | 222,301 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/models.py | Model.to_tsv | def to_tsv(self, include_readonly=True):
'''
Returns the instance's column values as a tab-separated line. A newline is not included.
- `include_readonly`: if false, returns only fields that can be inserted into database.
'''
data = self.__dict__
fields = self.fields(writable=not include_readonly)
return '\t'.join(field.to_db_string(data[name], quote=False) for name, field in iteritems(fields)) | python | def to_tsv(self, include_readonly=True):
'''
Returns the instance's column values as a tab-separated line. A newline is not included.
- `include_readonly`: if false, returns only fields that can be inserted into database.
'''
data = self.__dict__
fields = self.fields(writable=not include_readonly)
return '\t'.join(field.to_db_string(data[name], quote=False) for name, field in iteritems(fields)) | [
"def",
"to_tsv",
"(",
"self",
",",
"include_readonly",
"=",
"True",
")",
":",
"data",
"=",
"self",
".",
"__dict__",
"fields",
"=",
"self",
".",
"fields",
"(",
"writable",
"=",
"not",
"include_readonly",
")",
"return",
"'\\t'",
".",
"join",
"(",
"field",
... | Returns the instance's column values as a tab-separated line. A newline is not included.
- `include_readonly`: if false, returns only fields that can be inserted into database. | [
"Returns",
"the",
"instance",
"s",
"column",
"values",
"as",
"a",
"tab",
"-",
"separated",
"line",
".",
"A",
"newline",
"is",
"not",
"included",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/models.py#L230-L238 | train | 222,302 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/models.py | Model.to_dict | def to_dict(self, include_readonly=True, field_names=None):
'''
Returns the instance's column values as a dict.
- `include_readonly`: if false, returns only fields that can be inserted into database.
- `field_names`: an iterable of field names to return (optional)
'''
fields = self.fields(writable=not include_readonly)
if field_names is not None:
fields = [f for f in fields if f in field_names]
data = self.__dict__
return {name: data[name] for name in fields} | python | def to_dict(self, include_readonly=True, field_names=None):
'''
Returns the instance's column values as a dict.
- `include_readonly`: if false, returns only fields that can be inserted into database.
- `field_names`: an iterable of field names to return (optional)
'''
fields = self.fields(writable=not include_readonly)
if field_names is not None:
fields = [f for f in fields if f in field_names]
data = self.__dict__
return {name: data[name] for name in fields} | [
"def",
"to_dict",
"(",
"self",
",",
"include_readonly",
"=",
"True",
",",
"field_names",
"=",
"None",
")",
":",
"fields",
"=",
"self",
".",
"fields",
"(",
"writable",
"=",
"not",
"include_readonly",
")",
"if",
"field_names",
"is",
"not",
"None",
":",
"fi... | Returns the instance's column values as a dict.
- `include_readonly`: if false, returns only fields that can be inserted into database.
- `field_names`: an iterable of field names to return (optional) | [
"Returns",
"the",
"instance",
"s",
"column",
"values",
"as",
"a",
"dict",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/models.py#L240-L253 | train | 222,303 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/utils.py | import_submodules | def import_submodules(package_name):
"""
Import all submodules of a module.
"""
import importlib, pkgutil
package = importlib.import_module(package_name)
return {
name: importlib.import_module(package_name + '.' + name)
for _, name, _ in pkgutil.iter_modules(package.__path__)
} | python | def import_submodules(package_name):
"""
Import all submodules of a module.
"""
import importlib, pkgutil
package = importlib.import_module(package_name)
return {
name: importlib.import_module(package_name + '.' + name)
for _, name, _ in pkgutil.iter_modules(package.__path__)
} | [
"def",
"import_submodules",
"(",
"package_name",
")",
":",
"import",
"importlib",
",",
"pkgutil",
"package",
"=",
"importlib",
".",
"import_module",
"(",
"package_name",
")",
"return",
"{",
"name",
":",
"importlib",
".",
"import_module",
"(",
"package_name",
"+"... | Import all submodules of a module. | [
"Import",
"all",
"submodules",
"of",
"a",
"module",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/utils.py#L84-L93 | train | 222,304 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/database.py | ServerError.get_error_code_msg | def get_error_code_msg(cls, full_error_message):
"""
Extract the code and message of the exception that clickhouse-server generated.
See the list of error codes here:
https://github.com/yandex/ClickHouse/blob/master/dbms/src/Common/ErrorCodes.cpp
"""
for pattern in cls.ERROR_PATTERNS:
match = pattern.match(full_error_message)
if match:
# assert match.group('type1') == match.group('type2')
return int(match.group('code')), match.group('msg').strip()
return 0, full_error_message | python | def get_error_code_msg(cls, full_error_message):
"""
Extract the code and message of the exception that clickhouse-server generated.
See the list of error codes here:
https://github.com/yandex/ClickHouse/blob/master/dbms/src/Common/ErrorCodes.cpp
"""
for pattern in cls.ERROR_PATTERNS:
match = pattern.match(full_error_message)
if match:
# assert match.group('type1') == match.group('type2')
return int(match.group('code')), match.group('msg').strip()
return 0, full_error_message | [
"def",
"get_error_code_msg",
"(",
"cls",
",",
"full_error_message",
")",
":",
"for",
"pattern",
"in",
"cls",
".",
"ERROR_PATTERNS",
":",
"match",
"=",
"pattern",
".",
"match",
"(",
"full_error_message",
")",
"if",
"match",
":",
"# assert match.group('type1') == ma... | Extract the code and message of the exception that clickhouse-server generated.
See the list of error codes here:
https://github.com/yandex/ClickHouse/blob/master/dbms/src/Common/ErrorCodes.cpp | [
"Extract",
"the",
"code",
"and",
"message",
"of",
"the",
"exception",
"that",
"clickhouse",
"-",
"server",
"generated",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/database.py#L58-L71 | train | 222,305 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/database.py | Database.create_table | def create_table(self, model_class):
'''
Creates a table for the given model class, if it does not exist already.
'''
if model_class.is_system_model():
raise DatabaseException("You can't create system table")
if getattr(model_class, 'engine') is None:
raise DatabaseException("%s class must define an engine" % model_class.__name__)
self._send(model_class.create_table_sql(self)) | python | def create_table(self, model_class):
'''
Creates a table for the given model class, if it does not exist already.
'''
if model_class.is_system_model():
raise DatabaseException("You can't create system table")
if getattr(model_class, 'engine') is None:
raise DatabaseException("%s class must define an engine" % model_class.__name__)
self._send(model_class.create_table_sql(self)) | [
"def",
"create_table",
"(",
"self",
",",
"model_class",
")",
":",
"if",
"model_class",
".",
"is_system_model",
"(",
")",
":",
"raise",
"DatabaseException",
"(",
"\"You can't create system table\"",
")",
"if",
"getattr",
"(",
"model_class",
",",
"'engine'",
")",
... | Creates a table for the given model class, if it does not exist already. | [
"Creates",
"a",
"table",
"for",
"the",
"given",
"model",
"class",
"if",
"it",
"does",
"not",
"exist",
"already",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/database.py#L136-L144 | train | 222,306 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/database.py | Database.drop_table | def drop_table(self, model_class):
'''
Drops the database table of the given model class, if it exists.
'''
if model_class.is_system_model():
raise DatabaseException("You can't drop system table")
self._send(model_class.drop_table_sql(self)) | python | def drop_table(self, model_class):
'''
Drops the database table of the given model class, if it exists.
'''
if model_class.is_system_model():
raise DatabaseException("You can't drop system table")
self._send(model_class.drop_table_sql(self)) | [
"def",
"drop_table",
"(",
"self",
",",
"model_class",
")",
":",
"if",
"model_class",
".",
"is_system_model",
"(",
")",
":",
"raise",
"DatabaseException",
"(",
"\"You can't drop system table\"",
")",
"self",
".",
"_send",
"(",
"model_class",
".",
"drop_table_sql",
... | Drops the database table of the given model class, if it exists. | [
"Drops",
"the",
"database",
"table",
"of",
"the",
"given",
"model",
"class",
"if",
"it",
"exists",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/database.py#L146-L152 | train | 222,307 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/database.py | Database.does_table_exist | def does_table_exist(self, model_class):
'''
Checks whether a table for the given model class already exists.
Note that this only checks for existence of a table with the expected name.
'''
sql = "SELECT count() FROM system.tables WHERE database = '%s' AND name = '%s'"
r = self._send(sql % (self.db_name, model_class.table_name()))
return r.text.strip() == '1' | python | def does_table_exist(self, model_class):
'''
Checks whether a table for the given model class already exists.
Note that this only checks for existence of a table with the expected name.
'''
sql = "SELECT count() FROM system.tables WHERE database = '%s' AND name = '%s'"
r = self._send(sql % (self.db_name, model_class.table_name()))
return r.text.strip() == '1' | [
"def",
"does_table_exist",
"(",
"self",
",",
"model_class",
")",
":",
"sql",
"=",
"\"SELECT count() FROM system.tables WHERE database = '%s' AND name = '%s'\"",
"r",
"=",
"self",
".",
"_send",
"(",
"sql",
"%",
"(",
"self",
".",
"db_name",
",",
"model_class",
".",
... | Checks whether a table for the given model class already exists.
Note that this only checks for existence of a table with the expected name. | [
"Checks",
"whether",
"a",
"table",
"for",
"the",
"given",
"model",
"class",
"already",
"exists",
".",
"Note",
"that",
"this",
"only",
"checks",
"for",
"existence",
"of",
"a",
"table",
"with",
"the",
"expected",
"name",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/database.py#L154-L161 | train | 222,308 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/database.py | Database.insert | def insert(self, model_instances, batch_size=1000):
'''
Insert records into the database.
- `model_instances`: any iterable containing instances of a single model class.
- `batch_size`: number of records to send per chunk (use a lower number if your records are very large).
'''
from six import next
from io import BytesIO
i = iter(model_instances)
try:
first_instance = next(i)
except StopIteration:
return # model_instances is empty
model_class = first_instance.__class__
if first_instance.is_read_only() or first_instance.is_system_model():
raise DatabaseException("You can't insert into read only and system tables")
fields_list = ','.join(
['`%s`' % name for name in first_instance.fields(writable=True)])
def gen():
buf = BytesIO()
query = 'INSERT INTO $table (%s) FORMAT TabSeparated\n' % fields_list
buf.write(self._substitute(query, model_class).encode('utf-8'))
first_instance.set_database(self)
buf.write(first_instance.to_tsv(include_readonly=False).encode('utf-8'))
buf.write('\n'.encode('utf-8'))
# Collect lines in batches of batch_size
lines = 2
for instance in i:
instance.set_database(self)
buf.write(instance.to_tsv(include_readonly=False).encode('utf-8'))
buf.write('\n'.encode('utf-8'))
lines += 1
if lines >= batch_size:
# Return the current batch of lines
yield buf.getvalue()
# Start a new batch
buf = BytesIO()
lines = 0
# Return any remaining lines in partial batch
if lines:
yield buf.getvalue()
self._send(gen()) | python | def insert(self, model_instances, batch_size=1000):
'''
Insert records into the database.
- `model_instances`: any iterable containing instances of a single model class.
- `batch_size`: number of records to send per chunk (use a lower number if your records are very large).
'''
from six import next
from io import BytesIO
i = iter(model_instances)
try:
first_instance = next(i)
except StopIteration:
return # model_instances is empty
model_class = first_instance.__class__
if first_instance.is_read_only() or first_instance.is_system_model():
raise DatabaseException("You can't insert into read only and system tables")
fields_list = ','.join(
['`%s`' % name for name in first_instance.fields(writable=True)])
def gen():
buf = BytesIO()
query = 'INSERT INTO $table (%s) FORMAT TabSeparated\n' % fields_list
buf.write(self._substitute(query, model_class).encode('utf-8'))
first_instance.set_database(self)
buf.write(first_instance.to_tsv(include_readonly=False).encode('utf-8'))
buf.write('\n'.encode('utf-8'))
# Collect lines in batches of batch_size
lines = 2
for instance in i:
instance.set_database(self)
buf.write(instance.to_tsv(include_readonly=False).encode('utf-8'))
buf.write('\n'.encode('utf-8'))
lines += 1
if lines >= batch_size:
# Return the current batch of lines
yield buf.getvalue()
# Start a new batch
buf = BytesIO()
lines = 0
# Return any remaining lines in partial batch
if lines:
yield buf.getvalue()
self._send(gen()) | [
"def",
"insert",
"(",
"self",
",",
"model_instances",
",",
"batch_size",
"=",
"1000",
")",
":",
"from",
"six",
"import",
"next",
"from",
"io",
"import",
"BytesIO",
"i",
"=",
"iter",
"(",
"model_instances",
")",
"try",
":",
"first_instance",
"=",
"next",
... | Insert records into the database.
- `model_instances`: any iterable containing instances of a single model class.
- `batch_size`: number of records to send per chunk (use a lower number if your records are very large). | [
"Insert",
"records",
"into",
"the",
"database",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/database.py#L177-L222 | train | 222,309 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/database.py | Database.count | def count(self, model_class, conditions=None):
'''
Counts the number of records in the model's table.
- `model_class`: the model to count.
- `conditions`: optional SQL conditions (contents of the WHERE clause).
'''
query = 'SELECT count() FROM $table'
if conditions:
query += ' WHERE ' + conditions
query = self._substitute(query, model_class)
r = self._send(query)
return int(r.text) if r.text else 0 | python | def count(self, model_class, conditions=None):
'''
Counts the number of records in the model's table.
- `model_class`: the model to count.
- `conditions`: optional SQL conditions (contents of the WHERE clause).
'''
query = 'SELECT count() FROM $table'
if conditions:
query += ' WHERE ' + conditions
query = self._substitute(query, model_class)
r = self._send(query)
return int(r.text) if r.text else 0 | [
"def",
"count",
"(",
"self",
",",
"model_class",
",",
"conditions",
"=",
"None",
")",
":",
"query",
"=",
"'SELECT count() FROM $table'",
"if",
"conditions",
":",
"query",
"+=",
"' WHERE '",
"+",
"conditions",
"query",
"=",
"self",
".",
"_substitute",
"(",
"q... | Counts the number of records in the model's table.
- `model_class`: the model to count.
- `conditions`: optional SQL conditions (contents of the WHERE clause). | [
"Counts",
"the",
"number",
"of",
"records",
"in",
"the",
"model",
"s",
"table",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/database.py#L224-L236 | train | 222,310 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/database.py | Database.select | def select(self, query, model_class=None, settings=None):
'''
Performs a query and returns a generator of model instances.
- `query`: the SQL query to execute.
- `model_class`: the model class matching the query's table,
or `None` for getting back instances of an ad-hoc model.
- `settings`: query settings to send as HTTP GET parameters
'''
query += ' FORMAT TabSeparatedWithNamesAndTypes'
query = self._substitute(query, model_class)
r = self._send(query, settings, True)
lines = r.iter_lines()
field_names = parse_tsv(next(lines))
field_types = parse_tsv(next(lines))
model_class = model_class or ModelBase.create_ad_hoc_model(zip(field_names, field_types))
for line in lines:
# skip blank line left by WITH TOTALS modifier
if line:
yield model_class.from_tsv(line, field_names, self.server_timezone, self) | python | def select(self, query, model_class=None, settings=None):
'''
Performs a query and returns a generator of model instances.
- `query`: the SQL query to execute.
- `model_class`: the model class matching the query's table,
or `None` for getting back instances of an ad-hoc model.
- `settings`: query settings to send as HTTP GET parameters
'''
query += ' FORMAT TabSeparatedWithNamesAndTypes'
query = self._substitute(query, model_class)
r = self._send(query, settings, True)
lines = r.iter_lines()
field_names = parse_tsv(next(lines))
field_types = parse_tsv(next(lines))
model_class = model_class or ModelBase.create_ad_hoc_model(zip(field_names, field_types))
for line in lines:
# skip blank line left by WITH TOTALS modifier
if line:
yield model_class.from_tsv(line, field_names, self.server_timezone, self) | [
"def",
"select",
"(",
"self",
",",
"query",
",",
"model_class",
"=",
"None",
",",
"settings",
"=",
"None",
")",
":",
"query",
"+=",
"' FORMAT TabSeparatedWithNamesAndTypes'",
"query",
"=",
"self",
".",
"_substitute",
"(",
"query",
",",
"model_class",
")",
"r... | Performs a query and returns a generator of model instances.
- `query`: the SQL query to execute.
- `model_class`: the model class matching the query's table,
or `None` for getting back instances of an ad-hoc model.
- `settings`: query settings to send as HTTP GET parameters | [
"Performs",
"a",
"query",
"and",
"returns",
"a",
"generator",
"of",
"model",
"instances",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/database.py#L238-L257 | train | 222,311 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/database.py | Database.raw | def raw(self, query, settings=None, stream=False):
'''
Performs a query and returns its output as text.
- `query`: the SQL query to execute.
- `settings`: query settings to send as HTTP GET parameters
- `stream`: if true, the HTTP response from ClickHouse will be streamed.
'''
query = self._substitute(query, None)
return self._send(query, settings=settings, stream=stream).text | python | def raw(self, query, settings=None, stream=False):
'''
Performs a query and returns its output as text.
- `query`: the SQL query to execute.
- `settings`: query settings to send as HTTP GET parameters
- `stream`: if true, the HTTP response from ClickHouse will be streamed.
'''
query = self._substitute(query, None)
return self._send(query, settings=settings, stream=stream).text | [
"def",
"raw",
"(",
"self",
",",
"query",
",",
"settings",
"=",
"None",
",",
"stream",
"=",
"False",
")",
":",
"query",
"=",
"self",
".",
"_substitute",
"(",
"query",
",",
"None",
")",
"return",
"self",
".",
"_send",
"(",
"query",
",",
"settings",
"... | Performs a query and returns its output as text.
- `query`: the SQL query to execute.
- `settings`: query settings to send as HTTP GET parameters
- `stream`: if true, the HTTP response from ClickHouse will be streamed. | [
"Performs",
"a",
"query",
"and",
"returns",
"its",
"output",
"as",
"text",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/database.py#L259-L268 | train | 222,312 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/database.py | Database.paginate | def paginate(self, model_class, order_by, page_num=1, page_size=100, conditions=None, settings=None):
'''
Selects records and returns a single page of model instances.
- `model_class`: the model class matching the query's table,
or `None` for getting back instances of an ad-hoc model.
- `order_by`: columns to use for sorting the query (contents of the ORDER BY clause).
- `page_num`: the page number (1-based), or -1 to get the last page.
- `page_size`: number of records to return per page.
- `conditions`: optional SQL conditions (contents of the WHERE clause).
- `settings`: query settings to send as HTTP GET parameters
The result is a namedtuple containing `objects` (list), `number_of_objects`,
`pages_total`, `number` (of the current page), and `page_size`.
'''
count = self.count(model_class, conditions)
pages_total = int(ceil(count / float(page_size)))
if page_num == -1:
page_num = max(pages_total, 1)
elif page_num < 1:
raise ValueError('Invalid page number: %d' % page_num)
offset = (page_num - 1) * page_size
query = 'SELECT * FROM $table'
if conditions:
query += ' WHERE ' + conditions
query += ' ORDER BY %s' % order_by
query += ' LIMIT %d, %d' % (offset, page_size)
query = self._substitute(query, model_class)
return Page(
objects=list(self.select(query, model_class, settings)) if count else [],
number_of_objects=count,
pages_total=pages_total,
number=page_num,
page_size=page_size
) | python | def paginate(self, model_class, order_by, page_num=1, page_size=100, conditions=None, settings=None):
'''
Selects records and returns a single page of model instances.
- `model_class`: the model class matching the query's table,
or `None` for getting back instances of an ad-hoc model.
- `order_by`: columns to use for sorting the query (contents of the ORDER BY clause).
- `page_num`: the page number (1-based), or -1 to get the last page.
- `page_size`: number of records to return per page.
- `conditions`: optional SQL conditions (contents of the WHERE clause).
- `settings`: query settings to send as HTTP GET parameters
The result is a namedtuple containing `objects` (list), `number_of_objects`,
`pages_total`, `number` (of the current page), and `page_size`.
'''
count = self.count(model_class, conditions)
pages_total = int(ceil(count / float(page_size)))
if page_num == -1:
page_num = max(pages_total, 1)
elif page_num < 1:
raise ValueError('Invalid page number: %d' % page_num)
offset = (page_num - 1) * page_size
query = 'SELECT * FROM $table'
if conditions:
query += ' WHERE ' + conditions
query += ' ORDER BY %s' % order_by
query += ' LIMIT %d, %d' % (offset, page_size)
query = self._substitute(query, model_class)
return Page(
objects=list(self.select(query, model_class, settings)) if count else [],
number_of_objects=count,
pages_total=pages_total,
number=page_num,
page_size=page_size
) | [
"def",
"paginate",
"(",
"self",
",",
"model_class",
",",
"order_by",
",",
"page_num",
"=",
"1",
",",
"page_size",
"=",
"100",
",",
"conditions",
"=",
"None",
",",
"settings",
"=",
"None",
")",
":",
"count",
"=",
"self",
".",
"count",
"(",
"model_class"... | Selects records and returns a single page of model instances.
- `model_class`: the model class matching the query's table,
or `None` for getting back instances of an ad-hoc model.
- `order_by`: columns to use for sorting the query (contents of the ORDER BY clause).
- `page_num`: the page number (1-based), or -1 to get the last page.
- `page_size`: number of records to return per page.
- `conditions`: optional SQL conditions (contents of the WHERE clause).
- `settings`: query settings to send as HTTP GET parameters
The result is a namedtuple containing `objects` (list), `number_of_objects`,
`pages_total`, `number` (of the current page), and `page_size`. | [
"Selects",
"records",
"and",
"returns",
"a",
"single",
"page",
"of",
"model",
"instances",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/database.py#L270-L304 | train | 222,313 |
Infinidat/infi.clickhouse_orm | src/infi/clickhouse_orm/database.py | Database.migrate | def migrate(self, migrations_package_name, up_to=9999):
'''
Executes schema migrations.
- `migrations_package_name` - fully qualified name of the Python package
containing the migrations.
- `up_to` - number of the last migration to apply.
'''
from .migrations import MigrationHistory
logger = logging.getLogger('migrations')
applied_migrations = self._get_applied_migrations(migrations_package_name)
modules = import_submodules(migrations_package_name)
unapplied_migrations = set(modules.keys()) - applied_migrations
for name in sorted(unapplied_migrations):
logger.info('Applying migration %s...', name)
for operation in modules[name].operations:
operation.apply(self)
self.insert([MigrationHistory(package_name=migrations_package_name, module_name=name, applied=datetime.date.today())])
if int(name[:4]) >= up_to:
break | python | def migrate(self, migrations_package_name, up_to=9999):
'''
Executes schema migrations.
- `migrations_package_name` - fully qualified name of the Python package
containing the migrations.
- `up_to` - number of the last migration to apply.
'''
from .migrations import MigrationHistory
logger = logging.getLogger('migrations')
applied_migrations = self._get_applied_migrations(migrations_package_name)
modules = import_submodules(migrations_package_name)
unapplied_migrations = set(modules.keys()) - applied_migrations
for name in sorted(unapplied_migrations):
logger.info('Applying migration %s...', name)
for operation in modules[name].operations:
operation.apply(self)
self.insert([MigrationHistory(package_name=migrations_package_name, module_name=name, applied=datetime.date.today())])
if int(name[:4]) >= up_to:
break | [
"def",
"migrate",
"(",
"self",
",",
"migrations_package_name",
",",
"up_to",
"=",
"9999",
")",
":",
"from",
".",
"migrations",
"import",
"MigrationHistory",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'migrations'",
")",
"applied_migrations",
"=",
"self",
... | Executes schema migrations.
- `migrations_package_name` - fully qualified name of the Python package
containing the migrations.
- `up_to` - number of the last migration to apply. | [
"Executes",
"schema",
"migrations",
"."
] | 595f2023e334e3925a5c3fbfdd6083a5992a7169 | https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/database.py#L306-L325 | train | 222,314 |
pyusb/pyusb | usb/core.py | _try_get_string | def _try_get_string(dev, index, langid = None, default_str_i0 = "",
default_access_error = "Error Accessing String"):
""" try to get a string, but return a string no matter what
"""
if index == 0 :
string = default_str_i0
else:
try:
if langid is None:
string = util.get_string(dev, index)
else:
string = util.get_string(dev, index, langid)
except :
string = default_access_error
return string | python | def _try_get_string(dev, index, langid = None, default_str_i0 = "",
default_access_error = "Error Accessing String"):
""" try to get a string, but return a string no matter what
"""
if index == 0 :
string = default_str_i0
else:
try:
if langid is None:
string = util.get_string(dev, index)
else:
string = util.get_string(dev, index, langid)
except :
string = default_access_error
return string | [
"def",
"_try_get_string",
"(",
"dev",
",",
"index",
",",
"langid",
"=",
"None",
",",
"default_str_i0",
"=",
"\"\"",
",",
"default_access_error",
"=",
"\"Error Accessing String\"",
")",
":",
"if",
"index",
"==",
"0",
":",
"string",
"=",
"default_str_i0",
"else"... | try to get a string, but return a string no matter what | [
"try",
"to",
"get",
"a",
"string",
"but",
"return",
"a",
"string",
"no",
"matter",
"what"
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/core.py#L52-L66 | train | 222,315 |
pyusb/pyusb | usb/core.py | _try_lookup | def _try_lookup(table, value, default = ""):
""" try to get a string from the lookup table, return "" instead of key
error
"""
try:
string = table[ value ]
except KeyError:
string = default
return string | python | def _try_lookup(table, value, default = ""):
""" try to get a string from the lookup table, return "" instead of key
error
"""
try:
string = table[ value ]
except KeyError:
string = default
return string | [
"def",
"_try_lookup",
"(",
"table",
",",
"value",
",",
"default",
"=",
"\"\"",
")",
":",
"try",
":",
"string",
"=",
"table",
"[",
"value",
"]",
"except",
"KeyError",
":",
"string",
"=",
"default",
"return",
"string"
] | try to get a string from the lookup table, return "" instead of key
error | [
"try",
"to",
"get",
"a",
"string",
"from",
"the",
"lookup",
"table",
"return",
"instead",
"of",
"key",
"error"
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/core.py#L68-L76 | train | 222,316 |
pyusb/pyusb | usb/core.py | find | def find(find_all=False, backend = None, custom_match = None, **args):
r"""Find an USB device and return it.
find() is the function used to discover USB devices. You can pass as
arguments any combination of the USB Device Descriptor fields to match a
device. For example:
find(idVendor=0x3f4, idProduct=0x2009)
will return the Device object for the device with idVendor field equals
to 0x3f4 and idProduct equals to 0x2009.
If there is more than one device which matchs the criteria, the first one
found will be returned. If a matching device cannot be found the function
returns None. If you want to get all devices, you can set the parameter
find_all to True, then find will return an iterator with all matched devices.
If no matching device is found, it will return an empty iterator. Example:
for printer in find(find_all=True, bDeviceClass=7):
print (printer)
This call will get all the USB printers connected to the system. (actually
may be not, because some devices put their class information in the
Interface Descriptor).
You can also use a customized match criteria:
dev = find(custom_match = lambda d: d.idProduct=0x3f4 and d.idvendor=0x2009)
A more accurate printer finder using a customized match would be like
so:
def is_printer(dev):
import usb.util
if dev.bDeviceClass == 7:
return True
for cfg in dev:
if usb.util.find_descriptor(cfg, bInterfaceClass=7) is not None:
return True
for printer in find(find_all=True, custom_match = is_printer):
print (printer)
Now even if the device class code is in the interface descriptor the
printer will be found.
You can combine a customized match with device descriptor fields. In this
case, the fields must match and the custom_match must return True. In the
our previous example, if we would like to get all printers belonging to the
manufacturer 0x3f4, the code would be like so:
printers = list(find(find_all=True, idVendor=0x3f4, custom_match=is_printer))
If you want to use find as a 'list all devices' function, just call
it with find_all = True:
devices = list(find(find_all=True))
Finally, you can pass a custom backend to the find function:
find(backend = MyBackend())
PyUSB has builtin backends for libusb 0.1, libusb 1.0 and OpenUSB. If you
do not supply a backend explicitly, find() function will select one of the
predefineds backends according to system availability.
Backends are explained in the usb.backend module.
"""
def device_iter(**kwargs):
for dev in backend.enumerate_devices():
d = Device(dev, backend)
tests = (val == getattr(d, key) for key, val in kwargs.items())
if _interop._all(tests) and (custom_match is None or custom_match(d)):
yield d
if backend is None:
import usb.backend.libusb1 as libusb1
import usb.backend.libusb0 as libusb0
import usb.backend.openusb as openusb
for m in (libusb1, openusb, libusb0):
backend = m.get_backend()
if backend is not None:
_logger.info('find(): using backend "%s"', m.__name__)
break
else:
raise NoBackendError('No backend available')
if find_all:
return device_iter(**args)
else:
try:
return _interop._next(device_iter(**args))
except StopIteration:
return None | python | def find(find_all=False, backend = None, custom_match = None, **args):
r"""Find an USB device and return it.
find() is the function used to discover USB devices. You can pass as
arguments any combination of the USB Device Descriptor fields to match a
device. For example:
find(idVendor=0x3f4, idProduct=0x2009)
will return the Device object for the device with idVendor field equals
to 0x3f4 and idProduct equals to 0x2009.
If there is more than one device which matchs the criteria, the first one
found will be returned. If a matching device cannot be found the function
returns None. If you want to get all devices, you can set the parameter
find_all to True, then find will return an iterator with all matched devices.
If no matching device is found, it will return an empty iterator. Example:
for printer in find(find_all=True, bDeviceClass=7):
print (printer)
This call will get all the USB printers connected to the system. (actually
may be not, because some devices put their class information in the
Interface Descriptor).
You can also use a customized match criteria:
dev = find(custom_match = lambda d: d.idProduct=0x3f4 and d.idvendor=0x2009)
A more accurate printer finder using a customized match would be like
so:
def is_printer(dev):
import usb.util
if dev.bDeviceClass == 7:
return True
for cfg in dev:
if usb.util.find_descriptor(cfg, bInterfaceClass=7) is not None:
return True
for printer in find(find_all=True, custom_match = is_printer):
print (printer)
Now even if the device class code is in the interface descriptor the
printer will be found.
You can combine a customized match with device descriptor fields. In this
case, the fields must match and the custom_match must return True. In the
our previous example, if we would like to get all printers belonging to the
manufacturer 0x3f4, the code would be like so:
printers = list(find(find_all=True, idVendor=0x3f4, custom_match=is_printer))
If you want to use find as a 'list all devices' function, just call
it with find_all = True:
devices = list(find(find_all=True))
Finally, you can pass a custom backend to the find function:
find(backend = MyBackend())
PyUSB has builtin backends for libusb 0.1, libusb 1.0 and OpenUSB. If you
do not supply a backend explicitly, find() function will select one of the
predefineds backends according to system availability.
Backends are explained in the usb.backend module.
"""
def device_iter(**kwargs):
for dev in backend.enumerate_devices():
d = Device(dev, backend)
tests = (val == getattr(d, key) for key, val in kwargs.items())
if _interop._all(tests) and (custom_match is None or custom_match(d)):
yield d
if backend is None:
import usb.backend.libusb1 as libusb1
import usb.backend.libusb0 as libusb0
import usb.backend.openusb as openusb
for m in (libusb1, openusb, libusb0):
backend = m.get_backend()
if backend is not None:
_logger.info('find(): using backend "%s"', m.__name__)
break
else:
raise NoBackendError('No backend available')
if find_all:
return device_iter(**args)
else:
try:
return _interop._next(device_iter(**args))
except StopIteration:
return None | [
"def",
"find",
"(",
"find_all",
"=",
"False",
",",
"backend",
"=",
"None",
",",
"custom_match",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"def",
"device_iter",
"(",
"*",
"*",
"kwargs",
")",
":",
"for",
"dev",
"in",
"backend",
".",
"enumerate_devi... | r"""Find an USB device and return it.
find() is the function used to discover USB devices. You can pass as
arguments any combination of the USB Device Descriptor fields to match a
device. For example:
find(idVendor=0x3f4, idProduct=0x2009)
will return the Device object for the device with idVendor field equals
to 0x3f4 and idProduct equals to 0x2009.
If there is more than one device which matchs the criteria, the first one
found will be returned. If a matching device cannot be found the function
returns None. If you want to get all devices, you can set the parameter
find_all to True, then find will return an iterator with all matched devices.
If no matching device is found, it will return an empty iterator. Example:
for printer in find(find_all=True, bDeviceClass=7):
print (printer)
This call will get all the USB printers connected to the system. (actually
may be not, because some devices put their class information in the
Interface Descriptor).
You can also use a customized match criteria:
dev = find(custom_match = lambda d: d.idProduct=0x3f4 and d.idvendor=0x2009)
A more accurate printer finder using a customized match would be like
so:
def is_printer(dev):
import usb.util
if dev.bDeviceClass == 7:
return True
for cfg in dev:
if usb.util.find_descriptor(cfg, bInterfaceClass=7) is not None:
return True
for printer in find(find_all=True, custom_match = is_printer):
print (printer)
Now even if the device class code is in the interface descriptor the
printer will be found.
You can combine a customized match with device descriptor fields. In this
case, the fields must match and the custom_match must return True. In the
our previous example, if we would like to get all printers belonging to the
manufacturer 0x3f4, the code would be like so:
printers = list(find(find_all=True, idVendor=0x3f4, custom_match=is_printer))
If you want to use find as a 'list all devices' function, just call
it with find_all = True:
devices = list(find(find_all=True))
Finally, you can pass a custom backend to the find function:
find(backend = MyBackend())
PyUSB has builtin backends for libusb 0.1, libusb 1.0 and OpenUSB. If you
do not supply a backend explicitly, find() function will select one of the
predefineds backends according to system availability.
Backends are explained in the usb.backend module. | [
"r",
"Find",
"an",
"USB",
"device",
"and",
"return",
"it",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/core.py#L1179-L1273 | train | 222,317 |
pyusb/pyusb | usb/core.py | show_devices | def show_devices(verbose=False, **kwargs):
"""Show information about connected devices.
The verbose flag sets to verbose or not.
**kwargs are passed directly to the find() function.
"""
kwargs["find_all"] = True
devices = find(**kwargs)
strings = ""
for device in devices:
if not verbose:
strings += "%s, %s\n" % (device._str(), _try_lookup(
_lu.device_classes, device.bDeviceClass))
else:
strings += "%s\n\n" % str(device)
return _DescriptorInfo(strings) | python | def show_devices(verbose=False, **kwargs):
"""Show information about connected devices.
The verbose flag sets to verbose or not.
**kwargs are passed directly to the find() function.
"""
kwargs["find_all"] = True
devices = find(**kwargs)
strings = ""
for device in devices:
if not verbose:
strings += "%s, %s\n" % (device._str(), _try_lookup(
_lu.device_classes, device.bDeviceClass))
else:
strings += "%s\n\n" % str(device)
return _DescriptorInfo(strings) | [
"def",
"show_devices",
"(",
"verbose",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"find_all\"",
"]",
"=",
"True",
"devices",
"=",
"find",
"(",
"*",
"*",
"kwargs",
")",
"strings",
"=",
"\"\"",
"for",
"device",
"in",
"devices",
"... | Show information about connected devices.
The verbose flag sets to verbose or not.
**kwargs are passed directly to the find() function. | [
"Show",
"information",
"about",
"connected",
"devices",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/core.py#L1275-L1291 | train | 222,318 |
pyusb/pyusb | usb/core.py | Device.langids | def langids(self):
""" Return the USB device's supported language ID codes.
These are 16-bit codes familiar to Windows developers, where for
example instead of en-US you say 0x0409. USB_LANGIDS.pdf on the usb.org
developer site for more info. String requests using a LANGID not
in this array should not be sent to the device.
This property will cause some USB traffic the first time it is accessed
and cache the resulting value for future use.
"""
if self._langids is None:
try:
self._langids = util.get_langids(self)
except USBError:
self._langids = ()
return self._langids | python | def langids(self):
""" Return the USB device's supported language ID codes.
These are 16-bit codes familiar to Windows developers, where for
example instead of en-US you say 0x0409. USB_LANGIDS.pdf on the usb.org
developer site for more info. String requests using a LANGID not
in this array should not be sent to the device.
This property will cause some USB traffic the first time it is accessed
and cache the resulting value for future use.
"""
if self._langids is None:
try:
self._langids = util.get_langids(self)
except USBError:
self._langids = ()
return self._langids | [
"def",
"langids",
"(",
"self",
")",
":",
"if",
"self",
".",
"_langids",
"is",
"None",
":",
"try",
":",
"self",
".",
"_langids",
"=",
"util",
".",
"get_langids",
"(",
"self",
")",
"except",
"USBError",
":",
"self",
".",
"_langids",
"=",
"(",
")",
"r... | Return the USB device's supported language ID codes.
These are 16-bit codes familiar to Windows developers, where for
example instead of en-US you say 0x0409. USB_LANGIDS.pdf on the usb.org
developer site for more info. String requests using a LANGID not
in this array should not be sent to the device.
This property will cause some USB traffic the first time it is accessed
and cache the resulting value for future use. | [
"Return",
"the",
"USB",
"device",
"s",
"supported",
"language",
"ID",
"codes",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/core.py#L794-L810 | train | 222,319 |
pyusb/pyusb | usb/core.py | Device.serial_number | def serial_number(self):
""" Return the USB device's serial number string descriptor.
This property will cause some USB traffic the first time it is accessed
and cache the resulting value for future use.
"""
if self._serial_number is None:
self._serial_number = util.get_string(self, self.iSerialNumber)
return self._serial_number | python | def serial_number(self):
""" Return the USB device's serial number string descriptor.
This property will cause some USB traffic the first time it is accessed
and cache the resulting value for future use.
"""
if self._serial_number is None:
self._serial_number = util.get_string(self, self.iSerialNumber)
return self._serial_number | [
"def",
"serial_number",
"(",
"self",
")",
":",
"if",
"self",
".",
"_serial_number",
"is",
"None",
":",
"self",
".",
"_serial_number",
"=",
"util",
".",
"get_string",
"(",
"self",
",",
"self",
".",
"iSerialNumber",
")",
"return",
"self",
".",
"_serial_numbe... | Return the USB device's serial number string descriptor.
This property will cause some USB traffic the first time it is accessed
and cache the resulting value for future use. | [
"Return",
"the",
"USB",
"device",
"s",
"serial",
"number",
"string",
"descriptor",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/core.py#L813-L821 | train | 222,320 |
pyusb/pyusb | usb/core.py | Device.product | def product(self):
""" Return the USB device's product string descriptor.
This property will cause some USB traffic the first time it is accessed
and cache the resulting value for future use.
"""
if self._product is None:
self._product = util.get_string(self, self.iProduct)
return self._product | python | def product(self):
""" Return the USB device's product string descriptor.
This property will cause some USB traffic the first time it is accessed
and cache the resulting value for future use.
"""
if self._product is None:
self._product = util.get_string(self, self.iProduct)
return self._product | [
"def",
"product",
"(",
"self",
")",
":",
"if",
"self",
".",
"_product",
"is",
"None",
":",
"self",
".",
"_product",
"=",
"util",
".",
"get_string",
"(",
"self",
",",
"self",
".",
"iProduct",
")",
"return",
"self",
".",
"_product"
] | Return the USB device's product string descriptor.
This property will cause some USB traffic the first time it is accessed
and cache the resulting value for future use. | [
"Return",
"the",
"USB",
"device",
"s",
"product",
"string",
"descriptor",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/core.py#L824-L832 | train | 222,321 |
pyusb/pyusb | usb/core.py | Device.parent | def parent(self):
""" Return the parent device. """
if self._has_parent is None:
_parent = self._ctx.backend.get_parent(self._ctx.dev)
self._has_parent = _parent is not None
if self._has_parent:
self._parent = Device(_parent, self._ctx.backend)
else:
self._parent = None
return self._parent | python | def parent(self):
""" Return the parent device. """
if self._has_parent is None:
_parent = self._ctx.backend.get_parent(self._ctx.dev)
self._has_parent = _parent is not None
if self._has_parent:
self._parent = Device(_parent, self._ctx.backend)
else:
self._parent = None
return self._parent | [
"def",
"parent",
"(",
"self",
")",
":",
"if",
"self",
".",
"_has_parent",
"is",
"None",
":",
"_parent",
"=",
"self",
".",
"_ctx",
".",
"backend",
".",
"get_parent",
"(",
"self",
".",
"_ctx",
".",
"dev",
")",
"self",
".",
"_has_parent",
"=",
"_parent"... | Return the parent device. | [
"Return",
"the",
"parent",
"device",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/core.py#L835-L844 | train | 222,322 |
pyusb/pyusb | usb/core.py | Device.manufacturer | def manufacturer(self):
""" Return the USB device's manufacturer string descriptor.
This property will cause some USB traffic the first time it is accessed
and cache the resulting value for future use.
"""
if self._manufacturer is None:
self._manufacturer = util.get_string(self, self.iManufacturer)
return self._manufacturer | python | def manufacturer(self):
""" Return the USB device's manufacturer string descriptor.
This property will cause some USB traffic the first time it is accessed
and cache the resulting value for future use.
"""
if self._manufacturer is None:
self._manufacturer = util.get_string(self, self.iManufacturer)
return self._manufacturer | [
"def",
"manufacturer",
"(",
"self",
")",
":",
"if",
"self",
".",
"_manufacturer",
"is",
"None",
":",
"self",
".",
"_manufacturer",
"=",
"util",
".",
"get_string",
"(",
"self",
",",
"self",
".",
"iManufacturer",
")",
"return",
"self",
".",
"_manufacturer"
] | Return the USB device's manufacturer string descriptor.
This property will cause some USB traffic the first time it is accessed
and cache the resulting value for future use. | [
"Return",
"the",
"USB",
"device",
"s",
"manufacturer",
"string",
"descriptor",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/core.py#L847-L855 | train | 222,323 |
pyusb/pyusb | usb/core.py | Device.set_interface_altsetting | def set_interface_altsetting(self, interface = None, alternate_setting = None):
r"""Set the alternate setting for an interface.
When you want to use an interface and it has more than one alternate
setting, you should call this method to select the appropriate
alternate setting. If you call the method without one or the two
parameters, it will be selected the first one found in the Device in
the same way of the set_configuration method.
Commonly, an interface has only one alternate setting and this call is
not necessary. For most devices, either it has more than one
alternate setting or not, it is not harmful to make a call to this
method with no arguments, as devices will silently ignore the request
when there is only one alternate setting, though the USB Spec allows
devices with no additional alternate setting return an error to the
Host in response to a SET_INTERFACE request.
If you are in doubt, you may want to call it with no arguments wrapped
by a try/except clause:
>>> try:
>>> dev.set_interface_altsetting()
>>> except usb.core.USBError:
>>> pass
"""
self._ctx.managed_set_interface(self, interface, alternate_setting) | python | def set_interface_altsetting(self, interface = None, alternate_setting = None):
r"""Set the alternate setting for an interface.
When you want to use an interface and it has more than one alternate
setting, you should call this method to select the appropriate
alternate setting. If you call the method without one or the two
parameters, it will be selected the first one found in the Device in
the same way of the set_configuration method.
Commonly, an interface has only one alternate setting and this call is
not necessary. For most devices, either it has more than one
alternate setting or not, it is not harmful to make a call to this
method with no arguments, as devices will silently ignore the request
when there is only one alternate setting, though the USB Spec allows
devices with no additional alternate setting return an error to the
Host in response to a SET_INTERFACE request.
If you are in doubt, you may want to call it with no arguments wrapped
by a try/except clause:
>>> try:
>>> dev.set_interface_altsetting()
>>> except usb.core.USBError:
>>> pass
"""
self._ctx.managed_set_interface(self, interface, alternate_setting) | [
"def",
"set_interface_altsetting",
"(",
"self",
",",
"interface",
"=",
"None",
",",
"alternate_setting",
"=",
"None",
")",
":",
"self",
".",
"_ctx",
".",
"managed_set_interface",
"(",
"self",
",",
"interface",
",",
"alternate_setting",
")"
] | r"""Set the alternate setting for an interface.
When you want to use an interface and it has more than one alternate
setting, you should call this method to select the appropriate
alternate setting. If you call the method without one or the two
parameters, it will be selected the first one found in the Device in
the same way of the set_configuration method.
Commonly, an interface has only one alternate setting and this call is
not necessary. For most devices, either it has more than one
alternate setting or not, it is not harmful to make a call to this
method with no arguments, as devices will silently ignore the request
when there is only one alternate setting, though the USB Spec allows
devices with no additional alternate setting return an error to the
Host in response to a SET_INTERFACE request.
If you are in doubt, you may want to call it with no arguments wrapped
by a try/except clause:
>>> try:
>>> dev.set_interface_altsetting()
>>> except usb.core.USBError:
>>> pass | [
"r",
"Set",
"the",
"alternate",
"setting",
"for",
"an",
"interface",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/core.py#L879-L904 | train | 222,324 |
pyusb/pyusb | usb/core.py | Device.reset | def reset(self):
r"""Reset the device."""
self._ctx.managed_open()
self._ctx.dispose(self, False)
self._ctx.backend.reset_device(self._ctx.handle)
self._ctx.dispose(self, True) | python | def reset(self):
r"""Reset the device."""
self._ctx.managed_open()
self._ctx.dispose(self, False)
self._ctx.backend.reset_device(self._ctx.handle)
self._ctx.dispose(self, True) | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_ctx",
".",
"managed_open",
"(",
")",
"self",
".",
"_ctx",
".",
"dispose",
"(",
"self",
",",
"False",
")",
"self",
".",
"_ctx",
".",
"backend",
".",
"reset_device",
"(",
"self",
".",
"_ctx",
".",... | r"""Reset the device. | [
"r",
"Reset",
"the",
"device",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/core.py#L913-L918 | train | 222,325 |
pyusb/pyusb | usb/core.py | Device.ctrl_transfer | def ctrl_transfer(self, bmRequestType, bRequest, wValue=0, wIndex=0,
data_or_wLength = None, timeout = None):
r"""Do a control transfer on the endpoint 0.
This method is used to issue a control transfer over the endpoint 0
(endpoint 0 is required to always be a control endpoint).
The parameters bmRequestType, bRequest, wValue and wIndex are the same
of the USB Standard Control Request format.
Control requests may or may not have a data payload to write/read.
In cases which it has, the direction bit of the bmRequestType
field is used to infer the desired request direction. For
host to device requests (OUT), data_or_wLength parameter is
the data payload to send, and it must be a sequence type convertible
to an array object. In this case, the return value is the number
of bytes written in the data payload. For device to host requests
(IN), data_or_wLength is either the wLength parameter of the control
request specifying the number of bytes to read in data payload, and
the return value is an array object with data read, or an array
object which the data will be read to, and the return value is the
number of bytes read.
"""
try:
buff = util.create_buffer(data_or_wLength)
except TypeError:
buff = _interop.as_array(data_or_wLength)
self._ctx.managed_open()
# Thanks to Johannes Stezenbach to point me out that we need to
# claim the recipient interface
recipient = bmRequestType & 3
rqtype = bmRequestType & (3 << 5)
if recipient == util.CTRL_RECIPIENT_INTERFACE \
and rqtype != util.CTRL_TYPE_VENDOR:
interface_number = wIndex & 0xff
self._ctx.managed_claim_interface(self, interface_number)
ret = self._ctx.backend.ctrl_transfer(
self._ctx.handle,
bmRequestType,
bRequest,
wValue,
wIndex,
buff,
self.__get_timeout(timeout))
if isinstance(data_or_wLength, array.array) \
or util.ctrl_direction(bmRequestType) == util.CTRL_OUT:
return ret
elif ret != len(buff) * buff.itemsize:
return buff[:ret]
else:
return buff | python | def ctrl_transfer(self, bmRequestType, bRequest, wValue=0, wIndex=0,
data_or_wLength = None, timeout = None):
r"""Do a control transfer on the endpoint 0.
This method is used to issue a control transfer over the endpoint 0
(endpoint 0 is required to always be a control endpoint).
The parameters bmRequestType, bRequest, wValue and wIndex are the same
of the USB Standard Control Request format.
Control requests may or may not have a data payload to write/read.
In cases which it has, the direction bit of the bmRequestType
field is used to infer the desired request direction. For
host to device requests (OUT), data_or_wLength parameter is
the data payload to send, and it must be a sequence type convertible
to an array object. In this case, the return value is the number
of bytes written in the data payload. For device to host requests
(IN), data_or_wLength is either the wLength parameter of the control
request specifying the number of bytes to read in data payload, and
the return value is an array object with data read, or an array
object which the data will be read to, and the return value is the
number of bytes read.
"""
try:
buff = util.create_buffer(data_or_wLength)
except TypeError:
buff = _interop.as_array(data_or_wLength)
self._ctx.managed_open()
# Thanks to Johannes Stezenbach to point me out that we need to
# claim the recipient interface
recipient = bmRequestType & 3
rqtype = bmRequestType & (3 << 5)
if recipient == util.CTRL_RECIPIENT_INTERFACE \
and rqtype != util.CTRL_TYPE_VENDOR:
interface_number = wIndex & 0xff
self._ctx.managed_claim_interface(self, interface_number)
ret = self._ctx.backend.ctrl_transfer(
self._ctx.handle,
bmRequestType,
bRequest,
wValue,
wIndex,
buff,
self.__get_timeout(timeout))
if isinstance(data_or_wLength, array.array) \
or util.ctrl_direction(bmRequestType) == util.CTRL_OUT:
return ret
elif ret != len(buff) * buff.itemsize:
return buff[:ret]
else:
return buff | [
"def",
"ctrl_transfer",
"(",
"self",
",",
"bmRequestType",
",",
"bRequest",
",",
"wValue",
"=",
"0",
",",
"wIndex",
"=",
"0",
",",
"data_or_wLength",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"buff",
"=",
"util",
".",
"create_buff... | r"""Do a control transfer on the endpoint 0.
This method is used to issue a control transfer over the endpoint 0
(endpoint 0 is required to always be a control endpoint).
The parameters bmRequestType, bRequest, wValue and wIndex are the same
of the USB Standard Control Request format.
Control requests may or may not have a data payload to write/read.
In cases which it has, the direction bit of the bmRequestType
field is used to infer the desired request direction. For
host to device requests (OUT), data_or_wLength parameter is
the data payload to send, and it must be a sequence type convertible
to an array object. In this case, the return value is the number
of bytes written in the data payload. For device to host requests
(IN), data_or_wLength is either the wLength parameter of the control
request specifying the number of bytes to read in data payload, and
the return value is an array object with data read, or an array
object which the data will be read to, and the return value is the
number of bytes read. | [
"r",
"Do",
"a",
"control",
"transfer",
"on",
"the",
"endpoint",
"0",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/core.py#L999-L1053 | train | 222,326 |
pyusb/pyusb | usb/core.py | Device.is_kernel_driver_active | def is_kernel_driver_active(self, interface):
r"""Determine if there is kernel driver associated with the interface.
If a kernel driver is active, the object will be unable to perform
I/O.
The interface parameter is the device interface number to check.
"""
self._ctx.managed_open()
return self._ctx.backend.is_kernel_driver_active(
self._ctx.handle,
interface) | python | def is_kernel_driver_active(self, interface):
r"""Determine if there is kernel driver associated with the interface.
If a kernel driver is active, the object will be unable to perform
I/O.
The interface parameter is the device interface number to check.
"""
self._ctx.managed_open()
return self._ctx.backend.is_kernel_driver_active(
self._ctx.handle,
interface) | [
"def",
"is_kernel_driver_active",
"(",
"self",
",",
"interface",
")",
":",
"self",
".",
"_ctx",
".",
"managed_open",
"(",
")",
"return",
"self",
".",
"_ctx",
".",
"backend",
".",
"is_kernel_driver_active",
"(",
"self",
".",
"_ctx",
".",
"handle",
",",
"int... | r"""Determine if there is kernel driver associated with the interface.
If a kernel driver is active, the object will be unable to perform
I/O.
The interface parameter is the device interface number to check. | [
"r",
"Determine",
"if",
"there",
"is",
"kernel",
"driver",
"associated",
"with",
"the",
"interface",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/core.py#L1055-L1066 | train | 222,327 |
pyusb/pyusb | usb/core.py | Device.detach_kernel_driver | def detach_kernel_driver(self, interface):
r"""Detach a kernel driver.
If successful, you will then be able to perform I/O.
The interface parameter is the device interface number to detach the
driver from.
"""
self._ctx.managed_open()
self._ctx.backend.detach_kernel_driver(
self._ctx.handle,
interface) | python | def detach_kernel_driver(self, interface):
r"""Detach a kernel driver.
If successful, you will then be able to perform I/O.
The interface parameter is the device interface number to detach the
driver from.
"""
self._ctx.managed_open()
self._ctx.backend.detach_kernel_driver(
self._ctx.handle,
interface) | [
"def",
"detach_kernel_driver",
"(",
"self",
",",
"interface",
")",
":",
"self",
".",
"_ctx",
".",
"managed_open",
"(",
")",
"self",
".",
"_ctx",
".",
"backend",
".",
"detach_kernel_driver",
"(",
"self",
".",
"_ctx",
".",
"handle",
",",
"interface",
")"
] | r"""Detach a kernel driver.
If successful, you will then be able to perform I/O.
The interface parameter is the device interface number to detach the
driver from. | [
"r",
"Detach",
"a",
"kernel",
"driver",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/core.py#L1068-L1079 | train | 222,328 |
pyusb/pyusb | usb/libloader.py | load_library | def load_library(lib, name=None, lib_cls=None):
"""Loads a library. Catches and logs exceptions.
Returns: the loaded library or None
arguments:
* lib -- path to/name of the library to be loaded
* name -- the library's identifier (for logging)
Defaults to None.
* lib_cls -- library class. Defaults to None (-> ctypes.CDLL).
"""
try:
if lib_cls:
return lib_cls(lib)
else:
return ctypes.CDLL(lib)
except Exception:
if name:
lib_msg = '%s (%s)' % (name, lib)
else:
lib_msg = lib
lib_msg += ' could not be loaded'
if sys.platform == 'cygwin':
lib_msg += ' in cygwin'
_LOGGER.error(lib_msg, exc_info=True)
return None | python | def load_library(lib, name=None, lib_cls=None):
"""Loads a library. Catches and logs exceptions.
Returns: the loaded library or None
arguments:
* lib -- path to/name of the library to be loaded
* name -- the library's identifier (for logging)
Defaults to None.
* lib_cls -- library class. Defaults to None (-> ctypes.CDLL).
"""
try:
if lib_cls:
return lib_cls(lib)
else:
return ctypes.CDLL(lib)
except Exception:
if name:
lib_msg = '%s (%s)' % (name, lib)
else:
lib_msg = lib
lib_msg += ' could not be loaded'
if sys.platform == 'cygwin':
lib_msg += ' in cygwin'
_LOGGER.error(lib_msg, exc_info=True)
return None | [
"def",
"load_library",
"(",
"lib",
",",
"name",
"=",
"None",
",",
"lib_cls",
"=",
"None",
")",
":",
"try",
":",
"if",
"lib_cls",
":",
"return",
"lib_cls",
"(",
"lib",
")",
"else",
":",
"return",
"ctypes",
".",
"CDLL",
"(",
"lib",
")",
"except",
"Ex... | Loads a library. Catches and logs exceptions.
Returns: the loaded library or None
arguments:
* lib -- path to/name of the library to be loaded
* name -- the library's identifier (for logging)
Defaults to None.
* lib_cls -- library class. Defaults to None (-> ctypes.CDLL). | [
"Loads",
"a",
"library",
".",
"Catches",
"and",
"logs",
"exceptions",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/libloader.py#L88-L115 | train | 222,329 |
pyusb/pyusb | usb/libloader.py | load_locate_library | def load_locate_library(candidates, cygwin_lib, name,
win_cls=None, cygwin_cls=None, others_cls=None,
find_library=None, check_symbols=None):
"""Locates and loads a library.
Returns: the loaded library
arguments:
* candidates -- candidates list for locate_library()
* cygwin_lib -- name of the cygwin library
* name -- lib identifier (for logging). Defaults to None.
* win_cls -- class that is used to instantiate the library on
win32 platforms. Defaults to None (-> ctypes.CDLL).
* cygwin_cls -- library class for cygwin platforms.
Defaults to None (-> ctypes.CDLL).
* others_cls -- library class for all other platforms.
Defaults to None (-> ctypes.CDLL).
* find_library -- see locate_library(). Defaults to None.
* check_symbols -- either None or a list of symbols that the loaded lib
must provide (hasattr(<>)) in order to be considered
valid. LibraryMissingSymbolsException is raised if
any symbol is missing.
raises:
* NoLibraryCandidatesException
* LibraryNotFoundException
* LibraryNotLoadedException
* LibraryMissingSymbolsException
"""
if sys.platform == 'cygwin':
if cygwin_lib:
loaded_lib = load_library(cygwin_lib, name, cygwin_cls)
else:
raise NoLibraryCandidatesException(name)
elif candidates:
lib = locate_library(candidates, find_library)
if lib:
if sys.platform == 'win32':
loaded_lib = load_library(lib, name, win_cls)
else:
loaded_lib = load_library(lib, name, others_cls)
else:
_LOGGER.error('%r could not be found', (name or candidates))
raise LibraryNotFoundException(name)
else:
raise NoLibraryCandidatesException(name)
if loaded_lib is None:
raise LibraryNotLoadedException(name)
elif check_symbols:
symbols_missing = [
s for s in check_symbols if not hasattr(loaded_lib, s)
]
if symbols_missing:
msg = ('%r, missing symbols: %r', lib, symbols_missing )
_LOGGER.error(msg)
raise LibraryMissingSymbolsException(lib)
else:
return loaded_lib
else:
return loaded_lib | python | def load_locate_library(candidates, cygwin_lib, name,
win_cls=None, cygwin_cls=None, others_cls=None,
find_library=None, check_symbols=None):
"""Locates and loads a library.
Returns: the loaded library
arguments:
* candidates -- candidates list for locate_library()
* cygwin_lib -- name of the cygwin library
* name -- lib identifier (for logging). Defaults to None.
* win_cls -- class that is used to instantiate the library on
win32 platforms. Defaults to None (-> ctypes.CDLL).
* cygwin_cls -- library class for cygwin platforms.
Defaults to None (-> ctypes.CDLL).
* others_cls -- library class for all other platforms.
Defaults to None (-> ctypes.CDLL).
* find_library -- see locate_library(). Defaults to None.
* check_symbols -- either None or a list of symbols that the loaded lib
must provide (hasattr(<>)) in order to be considered
valid. LibraryMissingSymbolsException is raised if
any symbol is missing.
raises:
* NoLibraryCandidatesException
* LibraryNotFoundException
* LibraryNotLoadedException
* LibraryMissingSymbolsException
"""
if sys.platform == 'cygwin':
if cygwin_lib:
loaded_lib = load_library(cygwin_lib, name, cygwin_cls)
else:
raise NoLibraryCandidatesException(name)
elif candidates:
lib = locate_library(candidates, find_library)
if lib:
if sys.platform == 'win32':
loaded_lib = load_library(lib, name, win_cls)
else:
loaded_lib = load_library(lib, name, others_cls)
else:
_LOGGER.error('%r could not be found', (name or candidates))
raise LibraryNotFoundException(name)
else:
raise NoLibraryCandidatesException(name)
if loaded_lib is None:
raise LibraryNotLoadedException(name)
elif check_symbols:
symbols_missing = [
s for s in check_symbols if not hasattr(loaded_lib, s)
]
if symbols_missing:
msg = ('%r, missing symbols: %r', lib, symbols_missing )
_LOGGER.error(msg)
raise LibraryMissingSymbolsException(lib)
else:
return loaded_lib
else:
return loaded_lib | [
"def",
"load_locate_library",
"(",
"candidates",
",",
"cygwin_lib",
",",
"name",
",",
"win_cls",
"=",
"None",
",",
"cygwin_cls",
"=",
"None",
",",
"others_cls",
"=",
"None",
",",
"find_library",
"=",
"None",
",",
"check_symbols",
"=",
"None",
")",
":",
"if... | Locates and loads a library.
Returns: the loaded library
arguments:
* candidates -- candidates list for locate_library()
* cygwin_lib -- name of the cygwin library
* name -- lib identifier (for logging). Defaults to None.
* win_cls -- class that is used to instantiate the library on
win32 platforms. Defaults to None (-> ctypes.CDLL).
* cygwin_cls -- library class for cygwin platforms.
Defaults to None (-> ctypes.CDLL).
* others_cls -- library class for all other platforms.
Defaults to None (-> ctypes.CDLL).
* find_library -- see locate_library(). Defaults to None.
* check_symbols -- either None or a list of symbols that the loaded lib
must provide (hasattr(<>)) in order to be considered
valid. LibraryMissingSymbolsException is raised if
any symbol is missing.
raises:
* NoLibraryCandidatesException
* LibraryNotFoundException
* LibraryNotLoadedException
* LibraryMissingSymbolsException | [
"Locates",
"and",
"loads",
"a",
"library",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/libloader.py#L117-L177 | train | 222,330 |
pyusb/pyusb | usb/control.py | get_status | def get_status(dev, recipient = None):
r"""Return the status for the specified recipient.
dev is the Device object to which the request will be
sent to.
The recipient can be None (on which the status will be queried
from the device), an Interface or Endpoint descriptors.
The status value is returned as an integer with the lower
word being the two bytes status value.
"""
bmRequestType, wIndex = _parse_recipient(recipient, util.CTRL_IN)
ret = dev.ctrl_transfer(bmRequestType = bmRequestType,
bRequest = 0x00,
wIndex = wIndex,
data_or_wLength = 2)
return ret[0] | (ret[1] << 8) | python | def get_status(dev, recipient = None):
r"""Return the status for the specified recipient.
dev is the Device object to which the request will be
sent to.
The recipient can be None (on which the status will be queried
from the device), an Interface or Endpoint descriptors.
The status value is returned as an integer with the lower
word being the two bytes status value.
"""
bmRequestType, wIndex = _parse_recipient(recipient, util.CTRL_IN)
ret = dev.ctrl_transfer(bmRequestType = bmRequestType,
bRequest = 0x00,
wIndex = wIndex,
data_or_wLength = 2)
return ret[0] | (ret[1] << 8) | [
"def",
"get_status",
"(",
"dev",
",",
"recipient",
"=",
"None",
")",
":",
"bmRequestType",
",",
"wIndex",
"=",
"_parse_recipient",
"(",
"recipient",
",",
"util",
".",
"CTRL_IN",
")",
"ret",
"=",
"dev",
".",
"ctrl_transfer",
"(",
"bmRequestType",
"=",
"bmRe... | r"""Return the status for the specified recipient.
dev is the Device object to which the request will be
sent to.
The recipient can be None (on which the status will be queried
from the device), an Interface or Endpoint descriptors.
The status value is returned as an integer with the lower
word being the two bytes status value. | [
"r",
"Return",
"the",
"status",
"for",
"the",
"specified",
"recipient",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/control.py#L79-L96 | train | 222,331 |
pyusb/pyusb | usb/control.py | get_descriptor | def get_descriptor(dev, desc_size, desc_type, desc_index, wIndex = 0):
r"""Return the specified descriptor.
dev is the Device object to which the request will be
sent to.
desc_size is the descriptor size.
desc_type and desc_index are the descriptor type and index,
respectively. wIndex index is used for string descriptors
and represents the Language ID. For other types of descriptors,
it is zero.
"""
wValue = desc_index | (desc_type << 8)
bmRequestType = util.build_request_type(
util.CTRL_IN,
util.CTRL_TYPE_STANDARD,
util.CTRL_RECIPIENT_DEVICE)
return dev.ctrl_transfer(
bmRequestType = bmRequestType,
bRequest = 0x06,
wValue = wValue,
wIndex = wIndex,
data_or_wLength = desc_size) | python | def get_descriptor(dev, desc_size, desc_type, desc_index, wIndex = 0):
r"""Return the specified descriptor.
dev is the Device object to which the request will be
sent to.
desc_size is the descriptor size.
desc_type and desc_index are the descriptor type and index,
respectively. wIndex index is used for string descriptors
and represents the Language ID. For other types of descriptors,
it is zero.
"""
wValue = desc_index | (desc_type << 8)
bmRequestType = util.build_request_type(
util.CTRL_IN,
util.CTRL_TYPE_STANDARD,
util.CTRL_RECIPIENT_DEVICE)
return dev.ctrl_transfer(
bmRequestType = bmRequestType,
bRequest = 0x06,
wValue = wValue,
wIndex = wIndex,
data_or_wLength = desc_size) | [
"def",
"get_descriptor",
"(",
"dev",
",",
"desc_size",
",",
"desc_type",
",",
"desc_index",
",",
"wIndex",
"=",
"0",
")",
":",
"wValue",
"=",
"desc_index",
"|",
"(",
"desc_type",
"<<",
"8",
")",
"bmRequestType",
"=",
"util",
".",
"build_request_type",
"(",... | r"""Return the specified descriptor.
dev is the Device object to which the request will be
sent to.
desc_size is the descriptor size.
desc_type and desc_index are the descriptor type and index,
respectively. wIndex index is used for string descriptors
and represents the Language ID. For other types of descriptors,
it is zero. | [
"r",
"Return",
"the",
"specified",
"descriptor",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/control.py#L135-L160 | train | 222,332 |
pyusb/pyusb | usb/control.py | set_descriptor | def set_descriptor(dev, desc, desc_type, desc_index, wIndex = None):
r"""Update an existing descriptor or add a new one.
dev is the Device object to which the request will be
sent to.
The desc parameter is the descriptor to be sent to the device.
desc_type and desc_index are the descriptor type and index,
respectively. wIndex index is used for string descriptors
and represents the Language ID. For other types of descriptors,
it is zero.
"""
wValue = desc_index | (desc_type << 8)
bmRequestType = util.build_request_type(
util.CTRL_OUT,
util.CTRL_TYPE_STANDARD,
util.CTRL_RECIPIENT_DEVICE)
dev.ctrl_transfer(
bmRequestType = bmRequestType,
bRequest = 0x07,
wValue = wValue,
wIndex = wIndex,
data_or_wLength = desc) | python | def set_descriptor(dev, desc, desc_type, desc_index, wIndex = None):
r"""Update an existing descriptor or add a new one.
dev is the Device object to which the request will be
sent to.
The desc parameter is the descriptor to be sent to the device.
desc_type and desc_index are the descriptor type and index,
respectively. wIndex index is used for string descriptors
and represents the Language ID. For other types of descriptors,
it is zero.
"""
wValue = desc_index | (desc_type << 8)
bmRequestType = util.build_request_type(
util.CTRL_OUT,
util.CTRL_TYPE_STANDARD,
util.CTRL_RECIPIENT_DEVICE)
dev.ctrl_transfer(
bmRequestType = bmRequestType,
bRequest = 0x07,
wValue = wValue,
wIndex = wIndex,
data_or_wLength = desc) | [
"def",
"set_descriptor",
"(",
"dev",
",",
"desc",
",",
"desc_type",
",",
"desc_index",
",",
"wIndex",
"=",
"None",
")",
":",
"wValue",
"=",
"desc_index",
"|",
"(",
"desc_type",
"<<",
"8",
")",
"bmRequestType",
"=",
"util",
".",
"build_request_type",
"(",
... | r"""Update an existing descriptor or add a new one.
dev is the Device object to which the request will be
sent to.
The desc parameter is the descriptor to be sent to the device.
desc_type and desc_index are the descriptor type and index,
respectively. wIndex index is used for string descriptors
and represents the Language ID. For other types of descriptors,
it is zero. | [
"r",
"Update",
"an",
"existing",
"descriptor",
"or",
"add",
"a",
"new",
"one",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/control.py#L162-L186 | train | 222,333 |
pyusb/pyusb | usb/control.py | get_configuration | def get_configuration(dev):
r"""Get the current active configuration of the device.
dev is the Device object to which the request will be
sent to.
This function differs from the Device.get_active_configuration
method because the later may use cached data, while this
function always does a device request.
"""
bmRequestType = util.build_request_type(
util.CTRL_IN,
util.CTRL_TYPE_STANDARD,
util.CTRL_RECIPIENT_DEVICE)
return dev.ctrl_transfer(
bmRequestType,
bRequest = 0x08,
data_or_wLength = 1)[0] | python | def get_configuration(dev):
r"""Get the current active configuration of the device.
dev is the Device object to which the request will be
sent to.
This function differs from the Device.get_active_configuration
method because the later may use cached data, while this
function always does a device request.
"""
bmRequestType = util.build_request_type(
util.CTRL_IN,
util.CTRL_TYPE_STANDARD,
util.CTRL_RECIPIENT_DEVICE)
return dev.ctrl_transfer(
bmRequestType,
bRequest = 0x08,
data_or_wLength = 1)[0] | [
"def",
"get_configuration",
"(",
"dev",
")",
":",
"bmRequestType",
"=",
"util",
".",
"build_request_type",
"(",
"util",
".",
"CTRL_IN",
",",
"util",
".",
"CTRL_TYPE_STANDARD",
",",
"util",
".",
"CTRL_RECIPIENT_DEVICE",
")",
"return",
"dev",
".",
"ctrl_transfer",... | r"""Get the current active configuration of the device.
dev is the Device object to which the request will be
sent to.
This function differs from the Device.get_active_configuration
method because the later may use cached data, while this
function always does a device request. | [
"r",
"Get",
"the",
"current",
"active",
"configuration",
"of",
"the",
"device",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/control.py#L188-L206 | train | 222,334 |
pyusb/pyusb | usb/control.py | get_interface | def get_interface(dev, bInterfaceNumber):
r"""Get the current alternate setting of the interface.
dev is the Device object to which the request will be
sent to.
"""
bmRequestType = util.build_request_type(
util.CTRL_IN,
util.CTRL_TYPE_STANDARD,
util.CTRL_RECIPIENT_INTERFACE)
return dev.ctrl_transfer(
bmRequestType = bmRequestType,
bRequest = 0x0a,
wIndex = bInterfaceNumber,
data_or_wLength = 1)[0] | python | def get_interface(dev, bInterfaceNumber):
r"""Get the current alternate setting of the interface.
dev is the Device object to which the request will be
sent to.
"""
bmRequestType = util.build_request_type(
util.CTRL_IN,
util.CTRL_TYPE_STANDARD,
util.CTRL_RECIPIENT_INTERFACE)
return dev.ctrl_transfer(
bmRequestType = bmRequestType,
bRequest = 0x0a,
wIndex = bInterfaceNumber,
data_or_wLength = 1)[0] | [
"def",
"get_interface",
"(",
"dev",
",",
"bInterfaceNumber",
")",
":",
"bmRequestType",
"=",
"util",
".",
"build_request_type",
"(",
"util",
".",
"CTRL_IN",
",",
"util",
".",
"CTRL_TYPE_STANDARD",
",",
"util",
".",
"CTRL_RECIPIENT_INTERFACE",
")",
"return",
"dev... | r"""Get the current alternate setting of the interface.
dev is the Device object to which the request will be
sent to. | [
"r",
"Get",
"the",
"current",
"alternate",
"setting",
"of",
"the",
"interface",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/control.py#L216-L231 | train | 222,335 |
pyusb/pyusb | tools/vcp_terminal.py | configInputQueue | def configInputQueue():
""" configure a queue for accepting characters and return the queue
"""
def captureInput(iqueue):
while True:
c = getch()
if c == '\x03' or c == '\x04': # end on ctrl+c / ctrl+d
log.debug("Break received (\\x{0:02X})".format(ord(c)))
iqueue.put(c)
break
log.debug(
"Input Char '{}' received".format(
c if c != '\r' else '\\r'))
iqueue.put(c)
input_queue = queue.Queue()
input_thread = threading.Thread(target=lambda: captureInput(input_queue))
input_thread.daemon = True
input_thread.start()
return input_queue, input_thread | python | def configInputQueue():
""" configure a queue for accepting characters and return the queue
"""
def captureInput(iqueue):
while True:
c = getch()
if c == '\x03' or c == '\x04': # end on ctrl+c / ctrl+d
log.debug("Break received (\\x{0:02X})".format(ord(c)))
iqueue.put(c)
break
log.debug(
"Input Char '{}' received".format(
c if c != '\r' else '\\r'))
iqueue.put(c)
input_queue = queue.Queue()
input_thread = threading.Thread(target=lambda: captureInput(input_queue))
input_thread.daemon = True
input_thread.start()
return input_queue, input_thread | [
"def",
"configInputQueue",
"(",
")",
":",
"def",
"captureInput",
"(",
"iqueue",
")",
":",
"while",
"True",
":",
"c",
"=",
"getch",
"(",
")",
"if",
"c",
"==",
"'\\x03'",
"or",
"c",
"==",
"'\\x04'",
":",
"# end on ctrl+c / ctrl+d",
"log",
".",
"debug",
"... | configure a queue for accepting characters and return the queue | [
"configure",
"a",
"queue",
"for",
"accepting",
"characters",
"and",
"return",
"the",
"queue"
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/tools/vcp_terminal.py#L518-L537 | train | 222,336 |
pyusb/pyusb | tools/vcp_terminal.py | fmt_text | def fmt_text(text):
""" convert characters that aren't printable to hex format
"""
PRINTABLE_CHAR = set(
list(range(ord(' '), ord('~') + 1)) + [ord('\r'), ord('\n')])
newtext = ("\\x{:02X}".format(
c) if c not in PRINTABLE_CHAR else chr(c) for c in text)
textlines = "\r\n".join(l.strip('\r')
for l in "".join(newtext).split('\n'))
return textlines | python | def fmt_text(text):
""" convert characters that aren't printable to hex format
"""
PRINTABLE_CHAR = set(
list(range(ord(' '), ord('~') + 1)) + [ord('\r'), ord('\n')])
newtext = ("\\x{:02X}".format(
c) if c not in PRINTABLE_CHAR else chr(c) for c in text)
textlines = "\r\n".join(l.strip('\r')
for l in "".join(newtext).split('\n'))
return textlines | [
"def",
"fmt_text",
"(",
"text",
")",
":",
"PRINTABLE_CHAR",
"=",
"set",
"(",
"list",
"(",
"range",
"(",
"ord",
"(",
"' '",
")",
",",
"ord",
"(",
"'~'",
")",
"+",
"1",
")",
")",
"+",
"[",
"ord",
"(",
"'\\r'",
")",
",",
"ord",
"(",
"'\\n'",
")"... | convert characters that aren't printable to hex format | [
"convert",
"characters",
"that",
"aren",
"t",
"printable",
"to",
"hex",
"format"
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/tools/vcp_terminal.py#L540-L549 | train | 222,337 |
pyusb/pyusb | tools/vcp_terminal.py | ftdi_to_clkbits | def ftdi_to_clkbits(baudrate): # from libftdi
"""
10,27 => divisor = 10000, rate = 300
88,13 => divisor = 5000, rate = 600
C4,09 => divisor = 2500, rate = 1200
E2,04 => divisor = 1250, rate = 2,400
71,02 => divisor = 625, rate = 4,800
38,41 => divisor = 312.5, rate = 9,600
D0,80 => divisor = 208.25, rate = 14406
9C,80 => divisor = 156, rate = 19,230
4E,C0 => divisor = 78, rate = 38,461
34,00 => divisor = 52, rate = 57,692
1A,00 => divisor = 26, rate = 115,384
0D,00 => divisor = 13, rate = 230,769
"""
clk = 48000000
clk_div = 16
frac_code = [0, 3, 2, 4, 1, 5, 6, 7]
actual_baud = 0
if baudrate >= clk / clk_div:
encoded_divisor = 0
actual_baud = (clk // clk_div)
elif baudrate >= clk / (clk_div + clk_div / 2):
encoded_divisor = 1
actual_baud = clk // (clk_div + clk_div // 2)
elif baudrate >= clk / (2 * clk_div):
encoded_divisor = 2
actual_baud = clk // (2 * clk_div)
else:
# We divide by 16 to have 3 fractional bits and one bit for rounding
divisor = clk * 16 // clk_div // baudrate
best_divisor = (divisor + 1) // 2
if best_divisor > 0x20000:
best_divisor = 0x1ffff
actual_baud = clk * 16 // clk_div // best_divisor
actual_baud = (actual_baud + 1) // 2
encoded_divisor = ((best_divisor >> 3) +
(frac_code[best_divisor & 0x7] << 14))
value = encoded_divisor & 0xFFFF
index = encoded_divisor >> 16
return actual_baud, value, index | python | def ftdi_to_clkbits(baudrate): # from libftdi
"""
10,27 => divisor = 10000, rate = 300
88,13 => divisor = 5000, rate = 600
C4,09 => divisor = 2500, rate = 1200
E2,04 => divisor = 1250, rate = 2,400
71,02 => divisor = 625, rate = 4,800
38,41 => divisor = 312.5, rate = 9,600
D0,80 => divisor = 208.25, rate = 14406
9C,80 => divisor = 156, rate = 19,230
4E,C0 => divisor = 78, rate = 38,461
34,00 => divisor = 52, rate = 57,692
1A,00 => divisor = 26, rate = 115,384
0D,00 => divisor = 13, rate = 230,769
"""
clk = 48000000
clk_div = 16
frac_code = [0, 3, 2, 4, 1, 5, 6, 7]
actual_baud = 0
if baudrate >= clk / clk_div:
encoded_divisor = 0
actual_baud = (clk // clk_div)
elif baudrate >= clk / (clk_div + clk_div / 2):
encoded_divisor = 1
actual_baud = clk // (clk_div + clk_div // 2)
elif baudrate >= clk / (2 * clk_div):
encoded_divisor = 2
actual_baud = clk // (2 * clk_div)
else:
# We divide by 16 to have 3 fractional bits and one bit for rounding
divisor = clk * 16 // clk_div // baudrate
best_divisor = (divisor + 1) // 2
if best_divisor > 0x20000:
best_divisor = 0x1ffff
actual_baud = clk * 16 // clk_div // best_divisor
actual_baud = (actual_baud + 1) // 2
encoded_divisor = ((best_divisor >> 3) +
(frac_code[best_divisor & 0x7] << 14))
value = encoded_divisor & 0xFFFF
index = encoded_divisor >> 16
return actual_baud, value, index | [
"def",
"ftdi_to_clkbits",
"(",
"baudrate",
")",
":",
"# from libftdi",
"clk",
"=",
"48000000",
"clk_div",
"=",
"16",
"frac_code",
"=",
"[",
"0",
",",
"3",
",",
"2",
",",
"4",
",",
"1",
",",
"5",
",",
"6",
",",
"7",
"]",
"actual_baud",
"=",
"0",
"... | 10,27 => divisor = 10000, rate = 300
88,13 => divisor = 5000, rate = 600
C4,09 => divisor = 2500, rate = 1200
E2,04 => divisor = 1250, rate = 2,400
71,02 => divisor = 625, rate = 4,800
38,41 => divisor = 312.5, rate = 9,600
D0,80 => divisor = 208.25, rate = 14406
9C,80 => divisor = 156, rate = 19,230
4E,C0 => divisor = 78, rate = 38,461
34,00 => divisor = 52, rate = 57,692
1A,00 => divisor = 26, rate = 115,384
0D,00 => divisor = 13, rate = 230,769 | [
"10",
"27",
"=",
">",
"divisor",
"=",
"10000",
"rate",
"=",
"300",
"88",
"13",
"=",
">",
"divisor",
"=",
"5000",
"rate",
"=",
"600",
"C4",
"09",
"=",
">",
"divisor",
"=",
"2500",
"rate",
"=",
"1200",
"E2",
"04",
"=",
">",
"divisor",
"=",
"1250"... | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/tools/vcp_terminal.py#L576-L617 | train | 222,338 |
pyusb/pyusb | tools/vcp_terminal.py | ComPort._read | def _read(self):
""" check ep for data, add it to queue and sleep for interval """
while self._rxactive:
try:
rv = self._ep_in.read(self._ep_in.wMaxPacketSize)
if self._isFTDI:
status = rv[:2] # FTDI prepends 2 flow control characters,
# modem status and line status of the UART
if status[0] != 1 or status[1] != 0x60:
log.info(
"USB Status: 0x{0:02X} 0x{1:02X}".format(
*status))
rv = rv[2:]
for rvi in rv:
self._rxqueue.put(rvi)
except usb.USBError as e:
log.warn("USB Error on _read {}".format(e))
return
time.sleep(self._rxinterval) | python | def _read(self):
""" check ep for data, add it to queue and sleep for interval """
while self._rxactive:
try:
rv = self._ep_in.read(self._ep_in.wMaxPacketSize)
if self._isFTDI:
status = rv[:2] # FTDI prepends 2 flow control characters,
# modem status and line status of the UART
if status[0] != 1 or status[1] != 0x60:
log.info(
"USB Status: 0x{0:02X} 0x{1:02X}".format(
*status))
rv = rv[2:]
for rvi in rv:
self._rxqueue.put(rvi)
except usb.USBError as e:
log.warn("USB Error on _read {}".format(e))
return
time.sleep(self._rxinterval) | [
"def",
"_read",
"(",
"self",
")",
":",
"while",
"self",
".",
"_rxactive",
":",
"try",
":",
"rv",
"=",
"self",
".",
"_ep_in",
".",
"read",
"(",
"self",
".",
"_ep_in",
".",
"wMaxPacketSize",
")",
"if",
"self",
".",
"_isFTDI",
":",
"status",
"=",
"rv"... | check ep for data, add it to queue and sleep for interval | [
"check",
"ep",
"for",
"data",
"add",
"it",
"to",
"queue",
"and",
"sleep",
"for",
"interval"
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/tools/vcp_terminal.py#L187-L206 | train | 222,339 |
pyusb/pyusb | tools/vcp_terminal.py | ComPort._resetFTDI | def _resetFTDI(self):
""" reset the FTDI device
"""
if not self._isFTDI:
return
txdir = 0 # 0:OUT, 1:IN
req_type = 2 # 0:std, 1:class, 2:vendor
recipient = 0 # 0:device, 1:interface, 2:endpoint, 3:other
req_type = (txdir << 7) + (req_type << 5) + recipient
self.device.ctrl_transfer(
bmRequestType=req_type,
bRequest=0, # RESET
wValue=0, # RESET
wIndex=1,
data_or_wLength=0) | python | def _resetFTDI(self):
""" reset the FTDI device
"""
if not self._isFTDI:
return
txdir = 0 # 0:OUT, 1:IN
req_type = 2 # 0:std, 1:class, 2:vendor
recipient = 0 # 0:device, 1:interface, 2:endpoint, 3:other
req_type = (txdir << 7) + (req_type << 5) + recipient
self.device.ctrl_transfer(
bmRequestType=req_type,
bRequest=0, # RESET
wValue=0, # RESET
wIndex=1,
data_or_wLength=0) | [
"def",
"_resetFTDI",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_isFTDI",
":",
"return",
"txdir",
"=",
"0",
"# 0:OUT, 1:IN",
"req_type",
"=",
"2",
"# 0:std, 1:class, 2:vendor",
"recipient",
"=",
"0",
"# 0:device, 1:interface, 2:endpoint, 3:other",
"req_type",... | reset the FTDI device | [
"reset",
"the",
"FTDI",
"device"
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/tools/vcp_terminal.py#L359-L373 | train | 222,340 |
pyusb/pyusb | usb/legacy.py | busses | def busses():
r"""Returns a tuple with the usb busses."""
return (Bus(g) for k, g in groupby(
sorted(core.find(find_all=True), key=lambda d: d.bus),
lambda d: d.bus)) | python | def busses():
r"""Returns a tuple with the usb busses."""
return (Bus(g) for k, g in groupby(
sorted(core.find(find_all=True), key=lambda d: d.bus),
lambda d: d.bus)) | [
"def",
"busses",
"(",
")",
":",
"return",
"(",
"Bus",
"(",
"g",
")",
"for",
"k",
",",
"g",
"in",
"groupby",
"(",
"sorted",
"(",
"core",
".",
"find",
"(",
"find_all",
"=",
"True",
")",
",",
"key",
"=",
"lambda",
"d",
":",
"d",
".",
"bus",
")",... | r"""Returns a tuple with the usb busses. | [
"r",
"Returns",
"a",
"tuple",
"with",
"the",
"usb",
"busses",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L337-L341 | train | 222,341 |
pyusb/pyusb | usb/legacy.py | DeviceHandle.bulkWrite | def bulkWrite(self, endpoint, buffer, timeout = 100):
r"""Perform a bulk write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written.
"""
return self.dev.write(endpoint, buffer, timeout) | python | def bulkWrite(self, endpoint, buffer, timeout = 100):
r"""Perform a bulk write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written.
"""
return self.dev.write(endpoint, buffer, timeout) | [
"def",
"bulkWrite",
"(",
"self",
",",
"endpoint",
",",
"buffer",
",",
"timeout",
"=",
"100",
")",
":",
"return",
"self",
".",
"dev",
".",
"write",
"(",
"endpoint",
",",
"buffer",
",",
"timeout",
")"
] | r"""Perform a bulk write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written. | [
"r",
"Perform",
"a",
"bulk",
"write",
"request",
"to",
"the",
"endpoint",
"specified",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L131-L141 | train | 222,342 |
pyusb/pyusb | usb/legacy.py | DeviceHandle.bulkRead | def bulkRead(self, endpoint, size, timeout = 100):
r"""Performs a bulk read request to the endpoint specified.
Arguments:
endpoint: endpoint number.
size: number of bytes to read.
timeout: operation timeout in milliseconds. (default: 100)
Returns a tuple with the data read.
"""
return self.dev.read(endpoint, size, timeout) | python | def bulkRead(self, endpoint, size, timeout = 100):
r"""Performs a bulk read request to the endpoint specified.
Arguments:
endpoint: endpoint number.
size: number of bytes to read.
timeout: operation timeout in milliseconds. (default: 100)
Returns a tuple with the data read.
"""
return self.dev.read(endpoint, size, timeout) | [
"def",
"bulkRead",
"(",
"self",
",",
"endpoint",
",",
"size",
",",
"timeout",
"=",
"100",
")",
":",
"return",
"self",
".",
"dev",
".",
"read",
"(",
"endpoint",
",",
"size",
",",
"timeout",
")"
] | r"""Performs a bulk read request to the endpoint specified.
Arguments:
endpoint: endpoint number.
size: number of bytes to read.
timeout: operation timeout in milliseconds. (default: 100)
Returns a tuple with the data read. | [
"r",
"Performs",
"a",
"bulk",
"read",
"request",
"to",
"the",
"endpoint",
"specified",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L143-L152 | train | 222,343 |
pyusb/pyusb | usb/legacy.py | DeviceHandle.interruptWrite | def interruptWrite(self, endpoint, buffer, timeout = 100):
r"""Perform a interrupt write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written.
"""
return self.dev.write(endpoint, buffer, timeout) | python | def interruptWrite(self, endpoint, buffer, timeout = 100):
r"""Perform a interrupt write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written.
"""
return self.dev.write(endpoint, buffer, timeout) | [
"def",
"interruptWrite",
"(",
"self",
",",
"endpoint",
",",
"buffer",
",",
"timeout",
"=",
"100",
")",
":",
"return",
"self",
".",
"dev",
".",
"write",
"(",
"endpoint",
",",
"buffer",
",",
"timeout",
")"
] | r"""Perform a interrupt write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written. | [
"r",
"Perform",
"a",
"interrupt",
"write",
"request",
"to",
"the",
"endpoint",
"specified",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L154-L164 | train | 222,344 |
pyusb/pyusb | usb/legacy.py | DeviceHandle.interruptRead | def interruptRead(self, endpoint, size, timeout = 100):
r"""Performs a interrupt read request to the endpoint specified.
Arguments:
endpoint: endpoint number.
size: number of bytes to read.
timeout: operation timeout in milliseconds. (default: 100)
Returns a tuple with the data read.
"""
return self.dev.read(endpoint, size, timeout) | python | def interruptRead(self, endpoint, size, timeout = 100):
r"""Performs a interrupt read request to the endpoint specified.
Arguments:
endpoint: endpoint number.
size: number of bytes to read.
timeout: operation timeout in milliseconds. (default: 100)
Returns a tuple with the data read.
"""
return self.dev.read(endpoint, size, timeout) | [
"def",
"interruptRead",
"(",
"self",
",",
"endpoint",
",",
"size",
",",
"timeout",
"=",
"100",
")",
":",
"return",
"self",
".",
"dev",
".",
"read",
"(",
"endpoint",
",",
"size",
",",
"timeout",
")"
] | r"""Performs a interrupt read request to the endpoint specified.
Arguments:
endpoint: endpoint number.
size: number of bytes to read.
timeout: operation timeout in milliseconds. (default: 100)
Returns a tuple with the data read. | [
"r",
"Performs",
"a",
"interrupt",
"read",
"request",
"to",
"the",
"endpoint",
"specified",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L166-L175 | train | 222,345 |
pyusb/pyusb | usb/legacy.py | DeviceHandle.controlMsg | def controlMsg(self, requestType, request, buffer, value = 0, index = 0, timeout = 100):
r"""Perform a control request to the default control pipe on a device.
Arguments:
requestType: specifies the direction of data flow, the type
of request, and the recipient.
request: specifies the request.
buffer: if the transfer is a write transfer, buffer is a sequence
with the transfer data, otherwise, buffer is the number of
bytes to read.
value: specific information to pass to the device. (default: 0)
index: specific information to pass to the device. (default: 0)
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written.
"""
return self.dev.ctrl_transfer(
requestType,
request,
wValue = value,
wIndex = index,
data_or_wLength = buffer,
timeout = timeout) | python | def controlMsg(self, requestType, request, buffer, value = 0, index = 0, timeout = 100):
r"""Perform a control request to the default control pipe on a device.
Arguments:
requestType: specifies the direction of data flow, the type
of request, and the recipient.
request: specifies the request.
buffer: if the transfer is a write transfer, buffer is a sequence
with the transfer data, otherwise, buffer is the number of
bytes to read.
value: specific information to pass to the device. (default: 0)
index: specific information to pass to the device. (default: 0)
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written.
"""
return self.dev.ctrl_transfer(
requestType,
request,
wValue = value,
wIndex = index,
data_or_wLength = buffer,
timeout = timeout) | [
"def",
"controlMsg",
"(",
"self",
",",
"requestType",
",",
"request",
",",
"buffer",
",",
"value",
"=",
"0",
",",
"index",
"=",
"0",
",",
"timeout",
"=",
"100",
")",
":",
"return",
"self",
".",
"dev",
".",
"ctrl_transfer",
"(",
"requestType",
",",
"r... | r"""Perform a control request to the default control pipe on a device.
Arguments:
requestType: specifies the direction of data flow, the type
of request, and the recipient.
request: specifies the request.
buffer: if the transfer is a write transfer, buffer is a sequence
with the transfer data, otherwise, buffer is the number of
bytes to read.
value: specific information to pass to the device. (default: 0)
index: specific information to pass to the device. (default: 0)
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written. | [
"r",
"Perform",
"a",
"control",
"request",
"to",
"the",
"default",
"control",
"pipe",
"on",
"a",
"device",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L177-L198 | train | 222,346 |
pyusb/pyusb | usb/legacy.py | DeviceHandle.claimInterface | def claimInterface(self, interface):
r"""Claims the interface with the Operating System.
Arguments:
interface: interface number or an Interface object.
"""
if isinstance(interface, Interface):
interface = interface.interfaceNumber
util.claim_interface(self.dev, interface)
self.__claimed_interface = interface | python | def claimInterface(self, interface):
r"""Claims the interface with the Operating System.
Arguments:
interface: interface number or an Interface object.
"""
if isinstance(interface, Interface):
interface = interface.interfaceNumber
util.claim_interface(self.dev, interface)
self.__claimed_interface = interface | [
"def",
"claimInterface",
"(",
"self",
",",
"interface",
")",
":",
"if",
"isinstance",
"(",
"interface",
",",
"Interface",
")",
":",
"interface",
"=",
"interface",
".",
"interfaceNumber",
"util",
".",
"claim_interface",
"(",
"self",
".",
"dev",
",",
"interfac... | r"""Claims the interface with the Operating System.
Arguments:
interface: interface number or an Interface object. | [
"r",
"Claims",
"the",
"interface",
"with",
"the",
"Operating",
"System",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L208-L218 | train | 222,347 |
pyusb/pyusb | usb/legacy.py | DeviceHandle.releaseInterface | def releaseInterface(self):
r"""Release an interface previously claimed with claimInterface."""
util.release_interface(self.dev, self.__claimed_interface)
self.__claimed_interface = -1 | python | def releaseInterface(self):
r"""Release an interface previously claimed with claimInterface."""
util.release_interface(self.dev, self.__claimed_interface)
self.__claimed_interface = -1 | [
"def",
"releaseInterface",
"(",
"self",
")",
":",
"util",
".",
"release_interface",
"(",
"self",
".",
"dev",
",",
"self",
".",
"__claimed_interface",
")",
"self",
".",
"__claimed_interface",
"=",
"-",
"1"
] | r"""Release an interface previously claimed with claimInterface. | [
"r",
"Release",
"an",
"interface",
"previously",
"claimed",
"with",
"claimInterface",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L220-L223 | train | 222,348 |
pyusb/pyusb | usb/legacy.py | DeviceHandle.setConfiguration | def setConfiguration(self, configuration):
r"""Set the active configuration of a device.
Arguments:
configuration: a configuration value or a Configuration object.
"""
if isinstance(configuration, Configuration):
configuration = configuration.value
self.dev.set_configuration(configuration) | python | def setConfiguration(self, configuration):
r"""Set the active configuration of a device.
Arguments:
configuration: a configuration value or a Configuration object.
"""
if isinstance(configuration, Configuration):
configuration = configuration.value
self.dev.set_configuration(configuration) | [
"def",
"setConfiguration",
"(",
"self",
",",
"configuration",
")",
":",
"if",
"isinstance",
"(",
"configuration",
",",
"Configuration",
")",
":",
"configuration",
"=",
"configuration",
".",
"value",
"self",
".",
"dev",
".",
"set_configuration",
"(",
"configurati... | r"""Set the active configuration of a device.
Arguments:
configuration: a configuration value or a Configuration object. | [
"r",
"Set",
"the",
"active",
"configuration",
"of",
"a",
"device",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L238-L247 | train | 222,349 |
pyusb/pyusb | usb/legacy.py | DeviceHandle.setAltInterface | def setAltInterface(self, alternate):
r"""Sets the active alternate setting of the current interface.
Arguments:
alternate: an alternate setting number or an Interface object.
"""
if isinstance(alternate, Interface):
alternate = alternate.alternateSetting
self.dev.set_interface_altsetting(self.__claimed_interface, alternate) | python | def setAltInterface(self, alternate):
r"""Sets the active alternate setting of the current interface.
Arguments:
alternate: an alternate setting number or an Interface object.
"""
if isinstance(alternate, Interface):
alternate = alternate.alternateSetting
self.dev.set_interface_altsetting(self.__claimed_interface, alternate) | [
"def",
"setAltInterface",
"(",
"self",
",",
"alternate",
")",
":",
"if",
"isinstance",
"(",
"alternate",
",",
"Interface",
")",
":",
"alternate",
"=",
"alternate",
".",
"alternateSetting",
"self",
".",
"dev",
".",
"set_interface_altsetting",
"(",
"self",
".",
... | r"""Sets the active alternate setting of the current interface.
Arguments:
alternate: an alternate setting number or an Interface object. | [
"r",
"Sets",
"the",
"active",
"alternate",
"setting",
"of",
"the",
"current",
"interface",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L249-L258 | train | 222,350 |
pyusb/pyusb | usb/legacy.py | DeviceHandle.getString | def getString(self, index, length, langid = None):
r"""Retrieve the string descriptor specified by index
and langid from a device.
Arguments:
index: index of descriptor in the device.
length: number of bytes of the string (ignored)
langid: Language ID. If it is omitted, the first
language will be used.
"""
return util.get_string(self.dev, index, langid).encode('ascii') | python | def getString(self, index, length, langid = None):
r"""Retrieve the string descriptor specified by index
and langid from a device.
Arguments:
index: index of descriptor in the device.
length: number of bytes of the string (ignored)
langid: Language ID. If it is omitted, the first
language will be used.
"""
return util.get_string(self.dev, index, langid).encode('ascii') | [
"def",
"getString",
"(",
"self",
",",
"index",
",",
"length",
",",
"langid",
"=",
"None",
")",
":",
"return",
"util",
".",
"get_string",
"(",
"self",
".",
"dev",
",",
"index",
",",
"langid",
")",
".",
"encode",
"(",
"'ascii'",
")"
] | r"""Retrieve the string descriptor specified by index
and langid from a device.
Arguments:
index: index of descriptor in the device.
length: number of bytes of the string (ignored)
langid: Language ID. If it is omitted, the first
language will be used. | [
"r",
"Retrieve",
"the",
"string",
"descriptor",
"specified",
"by",
"index",
"and",
"langid",
"from",
"a",
"device",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L260-L270 | train | 222,351 |
pyusb/pyusb | usb/legacy.py | DeviceHandle.getDescriptor | def getDescriptor(self, desc_type, desc_index, length, endpoint = -1):
r"""Retrieves a descriptor from the device identified by the type
and index of the descriptor.
Arguments:
desc_type: descriptor type.
desc_index: index of the descriptor.
len: descriptor length.
endpoint: ignored.
"""
return control.get_descriptor(self.dev, length, desc_type, desc_index) | python | def getDescriptor(self, desc_type, desc_index, length, endpoint = -1):
r"""Retrieves a descriptor from the device identified by the type
and index of the descriptor.
Arguments:
desc_type: descriptor type.
desc_index: index of the descriptor.
len: descriptor length.
endpoint: ignored.
"""
return control.get_descriptor(self.dev, length, desc_type, desc_index) | [
"def",
"getDescriptor",
"(",
"self",
",",
"desc_type",
",",
"desc_index",
",",
"length",
",",
"endpoint",
"=",
"-",
"1",
")",
":",
"return",
"control",
".",
"get_descriptor",
"(",
"self",
".",
"dev",
",",
"length",
",",
"desc_type",
",",
"desc_index",
")... | r"""Retrieves a descriptor from the device identified by the type
and index of the descriptor.
Arguments:
desc_type: descriptor type.
desc_index: index of the descriptor.
len: descriptor length.
endpoint: ignored. | [
"r",
"Retrieves",
"a",
"descriptor",
"from",
"the",
"device",
"identified",
"by",
"the",
"type",
"and",
"index",
"of",
"the",
"descriptor",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L272-L282 | train | 222,352 |
pyusb/pyusb | usb/backend/__init__.py | IBackend.get_endpoint_descriptor | def get_endpoint_descriptor(self, dev, ep, intf, alt, config):
r"""Return an endpoint descriptor of the given device.
The object returned is required to have all the Endpoint Descriptor
fields acessible as member variables. They must be convertible (but
not required to be equal) to the int type.
The ep parameter is the endpoint logical index (not the bEndpointAddress
field) of the endpoint descriptor desired. dev, intf, alt and config are the same
values already described in the get_interface_descriptor() method.
"""
_not_implemented(self.get_endpoint_descriptor) | python | def get_endpoint_descriptor(self, dev, ep, intf, alt, config):
r"""Return an endpoint descriptor of the given device.
The object returned is required to have all the Endpoint Descriptor
fields acessible as member variables. They must be convertible (but
not required to be equal) to the int type.
The ep parameter is the endpoint logical index (not the bEndpointAddress
field) of the endpoint descriptor desired. dev, intf, alt and config are the same
values already described in the get_interface_descriptor() method.
"""
_not_implemented(self.get_endpoint_descriptor) | [
"def",
"get_endpoint_descriptor",
"(",
"self",
",",
"dev",
",",
"ep",
",",
"intf",
",",
"alt",
",",
"config",
")",
":",
"_not_implemented",
"(",
"self",
".",
"get_endpoint_descriptor",
")"
] | r"""Return an endpoint descriptor of the given device.
The object returned is required to have all the Endpoint Descriptor
fields acessible as member variables. They must be convertible (but
not required to be equal) to the int type.
The ep parameter is the endpoint logical index (not the bEndpointAddress
field) of the endpoint descriptor desired. dev, intf, alt and config are the same
values already described in the get_interface_descriptor() method. | [
"r",
"Return",
"an",
"endpoint",
"descriptor",
"of",
"the",
"given",
"device",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/backend/__init__.py#L140-L151 | train | 222,353 |
pyusb/pyusb | usb/backend/__init__.py | IBackend.bulk_write | def bulk_write(self, dev_handle, ep, intf, data, timeout):
r"""Perform a bulk write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
of the interface containing the endpoint. The data parameter
is the data to be sent. It must be an instance of the array.array
class. The timeout parameter specifies a time limit to the operation
in miliseconds.
The method returns the number of bytes written.
"""
_not_implemented(self.bulk_write) | python | def bulk_write(self, dev_handle, ep, intf, data, timeout):
r"""Perform a bulk write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
of the interface containing the endpoint. The data parameter
is the data to be sent. It must be an instance of the array.array
class. The timeout parameter specifies a time limit to the operation
in miliseconds.
The method returns the number of bytes written.
"""
_not_implemented(self.bulk_write) | [
"def",
"bulk_write",
"(",
"self",
",",
"dev_handle",
",",
"ep",
",",
"intf",
",",
"data",
",",
"timeout",
")",
":",
"_not_implemented",
"(",
"self",
".",
"bulk_write",
")"
] | r"""Perform a bulk write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
of the interface containing the endpoint. The data parameter
is the data to be sent. It must be an instance of the array.array
class. The timeout parameter specifies a time limit to the operation
in miliseconds.
The method returns the number of bytes written. | [
"r",
"Perform",
"a",
"bulk",
"write",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/backend/__init__.py#L225-L238 | train | 222,354 |
pyusb/pyusb | usb/backend/__init__.py | IBackend.bulk_read | def bulk_read(self, dev_handle, ep, intf, buff, timeout):
r"""Perform a bulk read.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be received from. intf is the bInterfaceNumber field
of the interface containing the endpoint. The buff parameter
is the buffer to receive the data read, the length of the buffer
tells how many bytes should be read. The timeout parameter
specifies a time limit to the operation in miliseconds.
The method returns the number of bytes actually read.
"""
_not_implemented(self.bulk_read) | python | def bulk_read(self, dev_handle, ep, intf, buff, timeout):
r"""Perform a bulk read.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be received from. intf is the bInterfaceNumber field
of the interface containing the endpoint. The buff parameter
is the buffer to receive the data read, the length of the buffer
tells how many bytes should be read. The timeout parameter
specifies a time limit to the operation in miliseconds.
The method returns the number of bytes actually read.
"""
_not_implemented(self.bulk_read) | [
"def",
"bulk_read",
"(",
"self",
",",
"dev_handle",
",",
"ep",
",",
"intf",
",",
"buff",
",",
"timeout",
")",
":",
"_not_implemented",
"(",
"self",
".",
"bulk_read",
")"
] | r"""Perform a bulk read.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be received from. intf is the bInterfaceNumber field
of the interface containing the endpoint. The buff parameter
is the buffer to receive the data read, the length of the buffer
tells how many bytes should be read. The timeout parameter
specifies a time limit to the operation in miliseconds.
The method returns the number of bytes actually read. | [
"r",
"Perform",
"a",
"bulk",
"read",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/backend/__init__.py#L240-L253 | train | 222,355 |
pyusb/pyusb | usb/backend/__init__.py | IBackend.intr_write | def intr_write(self, dev_handle, ep, intf, data, timeout):
r"""Perform an interrupt write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
of the interface containing the endpoint. The data parameter
is the data to be sent. It must be an instance of the array.array
class. The timeout parameter specifies a time limit to the operation
in miliseconds.
The method returns the number of bytes written.
"""
_not_implemented(self.intr_write) | python | def intr_write(self, dev_handle, ep, intf, data, timeout):
r"""Perform an interrupt write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
of the interface containing the endpoint. The data parameter
is the data to be sent. It must be an instance of the array.array
class. The timeout parameter specifies a time limit to the operation
in miliseconds.
The method returns the number of bytes written.
"""
_not_implemented(self.intr_write) | [
"def",
"intr_write",
"(",
"self",
",",
"dev_handle",
",",
"ep",
",",
"intf",
",",
"data",
",",
"timeout",
")",
":",
"_not_implemented",
"(",
"self",
".",
"intr_write",
")"
] | r"""Perform an interrupt write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
of the interface containing the endpoint. The data parameter
is the data to be sent. It must be an instance of the array.array
class. The timeout parameter specifies a time limit to the operation
in miliseconds.
The method returns the number of bytes written. | [
"r",
"Perform",
"an",
"interrupt",
"write",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/backend/__init__.py#L255-L268 | train | 222,356 |
pyusb/pyusb | usb/backend/__init__.py | IBackend.intr_read | def intr_read(self, dev_handle, ep, intf, size, timeout):
r"""Perform an interrut read.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be received from. intf is the bInterfaceNumber field
of the interface containing the endpoint. The buff parameter
is the buffer to receive the data read, the length of the buffer
tells how many bytes should be read. The timeout parameter
specifies a time limit to the operation in miliseconds.
The method returns the number of bytes actually read.
"""
_not_implemented(self.intr_read) | python | def intr_read(self, dev_handle, ep, intf, size, timeout):
r"""Perform an interrut read.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be received from. intf is the bInterfaceNumber field
of the interface containing the endpoint. The buff parameter
is the buffer to receive the data read, the length of the buffer
tells how many bytes should be read. The timeout parameter
specifies a time limit to the operation in miliseconds.
The method returns the number of bytes actually read.
"""
_not_implemented(self.intr_read) | [
"def",
"intr_read",
"(",
"self",
",",
"dev_handle",
",",
"ep",
",",
"intf",
",",
"size",
",",
"timeout",
")",
":",
"_not_implemented",
"(",
"self",
".",
"intr_read",
")"
] | r"""Perform an interrut read.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be received from. intf is the bInterfaceNumber field
of the interface containing the endpoint. The buff parameter
is the buffer to receive the data read, the length of the buffer
tells how many bytes should be read. The timeout parameter
specifies a time limit to the operation in miliseconds.
The method returns the number of bytes actually read. | [
"r",
"Perform",
"an",
"interrut",
"read",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/backend/__init__.py#L270-L283 | train | 222,357 |
pyusb/pyusb | usb/backend/__init__.py | IBackend.iso_write | def iso_write(self, dev_handle, ep, intf, data, timeout):
r"""Perform an isochronous write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
of the interface containing the endpoint. The data parameter
is the data to be sent. It must be an instance of the array.array
class. The timeout parameter specifies a time limit to the operation
in miliseconds.
The method returns the number of bytes written.
"""
_not_implemented(self.iso_write) | python | def iso_write(self, dev_handle, ep, intf, data, timeout):
r"""Perform an isochronous write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
of the interface containing the endpoint. The data parameter
is the data to be sent. It must be an instance of the array.array
class. The timeout parameter specifies a time limit to the operation
in miliseconds.
The method returns the number of bytes written.
"""
_not_implemented(self.iso_write) | [
"def",
"iso_write",
"(",
"self",
",",
"dev_handle",
",",
"ep",
",",
"intf",
",",
"data",
",",
"timeout",
")",
":",
"_not_implemented",
"(",
"self",
".",
"iso_write",
")"
] | r"""Perform an isochronous write.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to. intf is the bInterfaceNumber field
of the interface containing the endpoint. The data parameter
is the data to be sent. It must be an instance of the array.array
class. The timeout parameter specifies a time limit to the operation
in miliseconds.
The method returns the number of bytes written. | [
"r",
"Perform",
"an",
"isochronous",
"write",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/backend/__init__.py#L285-L298 | train | 222,358 |
pyusb/pyusb | usb/backend/__init__.py | IBackend.iso_read | def iso_read(self, dev_handle, ep, intf, size, timeout):
r"""Perform an isochronous read.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be received from. intf is the bInterfaceNumber field
of the interface containing the endpoint. The buff parameter
is buffer to receive the data read, the length of the buffer tells
how many bytes should be read. The timeout parameter specifies
a time limit to the operation in miliseconds.
The method returns the number of bytes actually read.
"""
_not_implemented(self.iso_read) | python | def iso_read(self, dev_handle, ep, intf, size, timeout):
r"""Perform an isochronous read.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be received from. intf is the bInterfaceNumber field
of the interface containing the endpoint. The buff parameter
is buffer to receive the data read, the length of the buffer tells
how many bytes should be read. The timeout parameter specifies
a time limit to the operation in miliseconds.
The method returns the number of bytes actually read.
"""
_not_implemented(self.iso_read) | [
"def",
"iso_read",
"(",
"self",
",",
"dev_handle",
",",
"ep",
",",
"intf",
",",
"size",
",",
"timeout",
")",
":",
"_not_implemented",
"(",
"self",
".",
"iso_read",
")"
] | r"""Perform an isochronous read.
dev_handle is the value returned by the open_device() method.
The ep parameter is the bEndpointAddress field whose endpoint
the data will be received from. intf is the bInterfaceNumber field
of the interface containing the endpoint. The buff parameter
is buffer to receive the data read, the length of the buffer tells
how many bytes should be read. The timeout parameter specifies
a time limit to the operation in miliseconds.
The method returns the number of bytes actually read. | [
"r",
"Perform",
"an",
"isochronous",
"read",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/backend/__init__.py#L300-L313 | train | 222,359 |
pyusb/pyusb | usb/backend/__init__.py | IBackend.ctrl_transfer | def ctrl_transfer(self,
dev_handle,
bmRequestType,
bRequest,
wValue,
wIndex,
data,
timeout):
r"""Perform a control transfer on the endpoint 0.
The direction of the transfer is inferred from the bmRequestType
field of the setup packet.
dev_handle is the value returned by the open_device() method.
bmRequestType, bRequest, wValue and wIndex are the same fields
of the setup packet. data is an array object, for OUT requests
it contains the bytes to transmit in the data stage and for
IN requests it is the buffer to hold the data read. The number
of bytes requested to transmit or receive is equal to the length
of the array times the data.itemsize field. The timeout parameter
specifies a time limit to the operation in miliseconds.
Return the number of bytes written (for OUT transfers) or the data
read (for IN transfers), as an array.array object.
"""
_not_implemented(self.ctrl_transfer) | python | def ctrl_transfer(self,
dev_handle,
bmRequestType,
bRequest,
wValue,
wIndex,
data,
timeout):
r"""Perform a control transfer on the endpoint 0.
The direction of the transfer is inferred from the bmRequestType
field of the setup packet.
dev_handle is the value returned by the open_device() method.
bmRequestType, bRequest, wValue and wIndex are the same fields
of the setup packet. data is an array object, for OUT requests
it contains the bytes to transmit in the data stage and for
IN requests it is the buffer to hold the data read. The number
of bytes requested to transmit or receive is equal to the length
of the array times the data.itemsize field. The timeout parameter
specifies a time limit to the operation in miliseconds.
Return the number of bytes written (for OUT transfers) or the data
read (for IN transfers), as an array.array object.
"""
_not_implemented(self.ctrl_transfer) | [
"def",
"ctrl_transfer",
"(",
"self",
",",
"dev_handle",
",",
"bmRequestType",
",",
"bRequest",
",",
"wValue",
",",
"wIndex",
",",
"data",
",",
"timeout",
")",
":",
"_not_implemented",
"(",
"self",
".",
"ctrl_transfer",
")"
] | r"""Perform a control transfer on the endpoint 0.
The direction of the transfer is inferred from the bmRequestType
field of the setup packet.
dev_handle is the value returned by the open_device() method.
bmRequestType, bRequest, wValue and wIndex are the same fields
of the setup packet. data is an array object, for OUT requests
it contains the bytes to transmit in the data stage and for
IN requests it is the buffer to hold the data read. The number
of bytes requested to transmit or receive is equal to the length
of the array times the data.itemsize field. The timeout parameter
specifies a time limit to the operation in miliseconds.
Return the number of bytes written (for OUT transfers) or the data
read (for IN transfers), as an array.array object. | [
"r",
"Perform",
"a",
"control",
"transfer",
"on",
"the",
"endpoint",
"0",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/backend/__init__.py#L315-L340 | train | 222,360 |
pyusb/pyusb | usb/util.py | find_descriptor | def find_descriptor(desc, find_all=False, custom_match=None, **args):
r"""Find an inner descriptor.
find_descriptor works in the same way as the core.find() function does,
but it acts on general descriptor objects. For example, suppose you
have a Device object called dev and want a Configuration of this
object with its bConfigurationValue equals to 1, the code would
be like so:
>>> cfg = util.find_descriptor(dev, bConfigurationValue=1)
You can use any field of the Descriptor as a match criteria, and you
can supply a customized match just like core.find() does. The
find_descriptor function also accepts the find_all parameter to get
an iterator instead of just one descriptor.
"""
def desc_iter(**kwargs):
for d in desc:
tests = (val == getattr(d, key) for key, val in kwargs.items())
if _interop._all(tests) and (custom_match is None or custom_match(d)):
yield d
if find_all:
return desc_iter(**args)
else:
try:
return _interop._next(desc_iter(**args))
except StopIteration:
return None | python | def find_descriptor(desc, find_all=False, custom_match=None, **args):
r"""Find an inner descriptor.
find_descriptor works in the same way as the core.find() function does,
but it acts on general descriptor objects. For example, suppose you
have a Device object called dev and want a Configuration of this
object with its bConfigurationValue equals to 1, the code would
be like so:
>>> cfg = util.find_descriptor(dev, bConfigurationValue=1)
You can use any field of the Descriptor as a match criteria, and you
can supply a customized match just like core.find() does. The
find_descriptor function also accepts the find_all parameter to get
an iterator instead of just one descriptor.
"""
def desc_iter(**kwargs):
for d in desc:
tests = (val == getattr(d, key) for key, val in kwargs.items())
if _interop._all(tests) and (custom_match is None or custom_match(d)):
yield d
if find_all:
return desc_iter(**args)
else:
try:
return _interop._next(desc_iter(**args))
except StopIteration:
return None | [
"def",
"find_descriptor",
"(",
"desc",
",",
"find_all",
"=",
"False",
",",
"custom_match",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"def",
"desc_iter",
"(",
"*",
"*",
"kwargs",
")",
":",
"for",
"d",
"in",
"desc",
":",
"tests",
"=",
"(",
"val",... | r"""Find an inner descriptor.
find_descriptor works in the same way as the core.find() function does,
but it acts on general descriptor objects. For example, suppose you
have a Device object called dev and want a Configuration of this
object with its bConfigurationValue equals to 1, the code would
be like so:
>>> cfg = util.find_descriptor(dev, bConfigurationValue=1)
You can use any field of the Descriptor as a match criteria, and you
can supply a customized match just like core.find() does. The
find_descriptor function also accepts the find_all parameter to get
an iterator instead of just one descriptor. | [
"r",
"Find",
"an",
"inner",
"descriptor",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/util.py#L151-L179 | train | 222,361 |
pyusb/pyusb | usb/util.py | get_langids | def get_langids(dev):
r"""Retrieve the list of supported Language IDs from the device.
Most client code should not call this function directly, but instead use
the langids property on the Device object, which will call this function as
needed and cache the result.
USB LANGIDs are 16-bit integers familiar to Windows developers, where
for example instead of en-US you say 0x0409. See the file USB_LANGIDS.pdf
somewhere on the usb.org site for a list, which does not claim to be
complete. It requires "system software must allow the enumeration and
selection of LANGIDs that are not currently on this list." It also requires
"system software should never request a LANGID not defined in the LANGID
code array (string index = 0) presented by a device." Client code can
check this tuple before issuing string requests for a specific language ID.
dev is the Device object whose supported language IDs will be retrieved.
The return value is a tuple of integer LANGIDs, possibly empty if the
device does not support strings at all (which USB 3.1 r1.0 section
9.6.9 allows). In that case client code should not request strings at all.
A USBError may be raised from this function for some devices that have no
string support, instead of returning an empty tuple. The accessor for the
langids property on Device catches that case and supplies an empty tuple,
so client code can ignore this detail by using the langids property instead
of directly calling this function.
"""
from usb.control import get_descriptor
buf = get_descriptor(
dev,
254,
DESC_TYPE_STRING,
0
)
# The array is retrieved by asking for string descriptor zero, which is
# never the index of a real string. The returned descriptor has bLength
# and bDescriptorType bytes followed by pairs of bytes representing
# little-endian LANGIDs. That is, buf[0] contains the length of the
# returned array, buf[2] is the least-significant byte of the first LANGID
# (if any), buf[3] is the most-significant byte, and in general the LSBs of
# all the LANGIDs are given by buf[2:buf[0]:2] and MSBs by buf[3:buf[0]:2].
# If the length of buf came back odd, something is wrong.
if len(buf) < 4 or buf[0] < 4 or buf[0]&1 != 0:
return ()
return tuple(map(lambda x,y: x+(y<<8), buf[2:buf[0]:2], buf[3:buf[0]:2])) | python | def get_langids(dev):
r"""Retrieve the list of supported Language IDs from the device.
Most client code should not call this function directly, but instead use
the langids property on the Device object, which will call this function as
needed and cache the result.
USB LANGIDs are 16-bit integers familiar to Windows developers, where
for example instead of en-US you say 0x0409. See the file USB_LANGIDS.pdf
somewhere on the usb.org site for a list, which does not claim to be
complete. It requires "system software must allow the enumeration and
selection of LANGIDs that are not currently on this list." It also requires
"system software should never request a LANGID not defined in the LANGID
code array (string index = 0) presented by a device." Client code can
check this tuple before issuing string requests for a specific language ID.
dev is the Device object whose supported language IDs will be retrieved.
The return value is a tuple of integer LANGIDs, possibly empty if the
device does not support strings at all (which USB 3.1 r1.0 section
9.6.9 allows). In that case client code should not request strings at all.
A USBError may be raised from this function for some devices that have no
string support, instead of returning an empty tuple. The accessor for the
langids property on Device catches that case and supplies an empty tuple,
so client code can ignore this detail by using the langids property instead
of directly calling this function.
"""
from usb.control import get_descriptor
buf = get_descriptor(
dev,
254,
DESC_TYPE_STRING,
0
)
# The array is retrieved by asking for string descriptor zero, which is
# never the index of a real string. The returned descriptor has bLength
# and bDescriptorType bytes followed by pairs of bytes representing
# little-endian LANGIDs. That is, buf[0] contains the length of the
# returned array, buf[2] is the least-significant byte of the first LANGID
# (if any), buf[3] is the most-significant byte, and in general the LSBs of
# all the LANGIDs are given by buf[2:buf[0]:2] and MSBs by buf[3:buf[0]:2].
# If the length of buf came back odd, something is wrong.
if len(buf) < 4 or buf[0] < 4 or buf[0]&1 != 0:
return ()
return tuple(map(lambda x,y: x+(y<<8), buf[2:buf[0]:2], buf[3:buf[0]:2])) | [
"def",
"get_langids",
"(",
"dev",
")",
":",
"from",
"usb",
".",
"control",
"import",
"get_descriptor",
"buf",
"=",
"get_descriptor",
"(",
"dev",
",",
"254",
",",
"DESC_TYPE_STRING",
",",
"0",
")",
"# The array is retrieved by asking for string descriptor zero, which i... | r"""Retrieve the list of supported Language IDs from the device.
Most client code should not call this function directly, but instead use
the langids property on the Device object, which will call this function as
needed and cache the result.
USB LANGIDs are 16-bit integers familiar to Windows developers, where
for example instead of en-US you say 0x0409. See the file USB_LANGIDS.pdf
somewhere on the usb.org site for a list, which does not claim to be
complete. It requires "system software must allow the enumeration and
selection of LANGIDs that are not currently on this list." It also requires
"system software should never request a LANGID not defined in the LANGID
code array (string index = 0) presented by a device." Client code can
check this tuple before issuing string requests for a specific language ID.
dev is the Device object whose supported language IDs will be retrieved.
The return value is a tuple of integer LANGIDs, possibly empty if the
device does not support strings at all (which USB 3.1 r1.0 section
9.6.9 allows). In that case client code should not request strings at all.
A USBError may be raised from this function for some devices that have no
string support, instead of returning an empty tuple. The accessor for the
langids property on Device catches that case and supplies an empty tuple,
so client code can ignore this detail by using the langids property instead
of directly calling this function. | [
"r",
"Retrieve",
"the",
"list",
"of",
"supported",
"Language",
"IDs",
"from",
"the",
"device",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/util.py#L222-L270 | train | 222,362 |
pyusb/pyusb | usb/util.py | get_string | def get_string(dev, index, langid = None):
r"""Retrieve a string descriptor from the device.
dev is the Device object which the string will be read from.
index is the string descriptor index and langid is the Language
ID of the descriptor. If langid is omitted, the string descriptor
of the first Language ID will be returned.
Zero is never the index of a real string. The USB spec allows a device to
use zero in a string index field to indicate that no string is provided.
So the caller does not have to treat that case specially, this function
returns None if passed an index of zero, and generates no traffic
to the device.
The return value is the unicode string present in the descriptor, or None
if the requested index was zero.
It is a ValueError to request a real string (index not zero), if: the
device's langid tuple is empty, or with an explicit langid the device does
not support.
"""
if 0 == index:
return None
from usb.control import get_descriptor
langids = dev.langids
if 0 == len(langids):
raise ValueError("The device has no langid")
if langid is None:
langid = langids[0]
elif langid not in langids:
raise ValueError("The device does not support the specified langid")
buf = get_descriptor(
dev,
255, # Maximum descriptor size
DESC_TYPE_STRING,
index,
langid
)
if hexversion >= 0x03020000:
return buf[2:buf[0]].tobytes().decode('utf-16-le')
else:
return buf[2:buf[0]].tostring().decode('utf-16-le') | python | def get_string(dev, index, langid = None):
r"""Retrieve a string descriptor from the device.
dev is the Device object which the string will be read from.
index is the string descriptor index and langid is the Language
ID of the descriptor. If langid is omitted, the string descriptor
of the first Language ID will be returned.
Zero is never the index of a real string. The USB spec allows a device to
use zero in a string index field to indicate that no string is provided.
So the caller does not have to treat that case specially, this function
returns None if passed an index of zero, and generates no traffic
to the device.
The return value is the unicode string present in the descriptor, or None
if the requested index was zero.
It is a ValueError to request a real string (index not zero), if: the
device's langid tuple is empty, or with an explicit langid the device does
not support.
"""
if 0 == index:
return None
from usb.control import get_descriptor
langids = dev.langids
if 0 == len(langids):
raise ValueError("The device has no langid")
if langid is None:
langid = langids[0]
elif langid not in langids:
raise ValueError("The device does not support the specified langid")
buf = get_descriptor(
dev,
255, # Maximum descriptor size
DESC_TYPE_STRING,
index,
langid
)
if hexversion >= 0x03020000:
return buf[2:buf[0]].tobytes().decode('utf-16-le')
else:
return buf[2:buf[0]].tostring().decode('utf-16-le') | [
"def",
"get_string",
"(",
"dev",
",",
"index",
",",
"langid",
"=",
"None",
")",
":",
"if",
"0",
"==",
"index",
":",
"return",
"None",
"from",
"usb",
".",
"control",
"import",
"get_descriptor",
"langids",
"=",
"dev",
".",
"langids",
"if",
"0",
"==",
"... | r"""Retrieve a string descriptor from the device.
dev is the Device object which the string will be read from.
index is the string descriptor index and langid is the Language
ID of the descriptor. If langid is omitted, the string descriptor
of the first Language ID will be returned.
Zero is never the index of a real string. The USB spec allows a device to
use zero in a string index field to indicate that no string is provided.
So the caller does not have to treat that case specially, this function
returns None if passed an index of zero, and generates no traffic
to the device.
The return value is the unicode string present in the descriptor, or None
if the requested index was zero.
It is a ValueError to request a real string (index not zero), if: the
device's langid tuple is empty, or with an explicit langid the device does
not support. | [
"r",
"Retrieve",
"a",
"string",
"descriptor",
"from",
"the",
"device",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/util.py#L272-L317 | train | 222,363 |
atztogo/phonopy | phonopy/unfolding/core.py | Unfolding._set_translations | def _set_translations(self):
"""Set primitive translations in supercell
_trans_s
Translations with respect to supercell basis vectors
_trans_p
Translations with respect to primitive cell basis vectors
_N
Number of the translations = det(supercel_matrix)
"""
pcell = PhonopyAtoms(numbers=[1],
scaled_positions=[[0, 0, 0]],
cell=np.diag([1, 1, 1]))
smat = self._supercell_matrix
self._trans_s = get_supercell(pcell, smat).get_scaled_positions()
self._trans_p = np.dot(self._trans_s, self._supercell_matrix.T)
self._N = len(self._trans_s) | python | def _set_translations(self):
"""Set primitive translations in supercell
_trans_s
Translations with respect to supercell basis vectors
_trans_p
Translations with respect to primitive cell basis vectors
_N
Number of the translations = det(supercel_matrix)
"""
pcell = PhonopyAtoms(numbers=[1],
scaled_positions=[[0, 0, 0]],
cell=np.diag([1, 1, 1]))
smat = self._supercell_matrix
self._trans_s = get_supercell(pcell, smat).get_scaled_positions()
self._trans_p = np.dot(self._trans_s, self._supercell_matrix.T)
self._N = len(self._trans_s) | [
"def",
"_set_translations",
"(",
"self",
")",
":",
"pcell",
"=",
"PhonopyAtoms",
"(",
"numbers",
"=",
"[",
"1",
"]",
",",
"scaled_positions",
"=",
"[",
"[",
"0",
",",
"0",
",",
"0",
"]",
"]",
",",
"cell",
"=",
"np",
".",
"diag",
"(",
"[",
"1",
... | Set primitive translations in supercell
_trans_s
Translations with respect to supercell basis vectors
_trans_p
Translations with respect to primitive cell basis vectors
_N
Number of the translations = det(supercel_matrix) | [
"Set",
"primitive",
"translations",
"in",
"supercell"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/unfolding/core.py#L164-L182 | train | 222,364 |
atztogo/phonopy | phonopy/qha/core.py | QHA.run | def run(self, verbose=False):
"""Fit parameters to EOS at temperatures
Even if fitting failed, simply omit the volume point. In this case,
the failed temperature point doesn't exist in the returned arrays.
"""
if verbose:
print(("#%11s" + "%14s" * 4) % ("T", "E_0", "B_0", "B'_0", "V_0"))
# Plus one temperature point is necessary for computing e.g. beta.
num_elems = self._get_num_elems(self._all_temperatures) + 1
if num_elems > len(self._all_temperatures):
num_elems -= 1
temperatures = []
parameters = []
free_energies = []
for i in range(num_elems): # loop over temperaturs
if self._electronic_energies.ndim == 1:
el_energy = self._electronic_energies
else:
el_energy = self._electronic_energies[i]
fe = [ph_e + el_e
for ph_e, el_e in zip(self._fe_phonon[i], el_energy)]
try:
ep = fit_to_eos(self._volumes, fe, self._eos)
except TypeError:
print("Fitting failure at T=%.1f" % self._all_temperatures[i])
if ep is None:
# Simply omit volume point where the fitting failed.
continue
else:
[ee, eb, ebp, ev] = ep
t = self._all_temperatures[i]
temperatures.append(t)
parameters.append(ep)
free_energies.append(fe)
if verbose:
print(("%14.6f" * 5) %
(t, ep[0], ep[1] * EVAngstromToGPa, ep[2], ep[3]))
self._free_energies = np.array(free_energies)
self._temperatures = np.array(temperatures)
self._equiv_parameters = np.array(parameters)
self._equiv_volumes = np.array(self._equiv_parameters[:, 3])
self._equiv_energies = np.array(self._equiv_parameters[:, 0])
self._equiv_bulk_modulus = np.array(
self._equiv_parameters[:, 1] * EVAngstromToGPa)
self._num_elems = len(self._temperatures)
# For computing following values at temperatures, finite difference
# method is used. Therefore number of temperature points are needed
# larger than self._num_elems that nearly equals to the temparature
# point we expect.
self._set_thermal_expansion()
self._set_heat_capacity_P_numerical()
self._set_heat_capacity_P_polyfit()
self._set_gruneisen_parameter() # To be run after thermal expansion.
self._len = len(self._thermal_expansions)
assert(self._len + 1 == self._num_elems) | python | def run(self, verbose=False):
"""Fit parameters to EOS at temperatures
Even if fitting failed, simply omit the volume point. In this case,
the failed temperature point doesn't exist in the returned arrays.
"""
if verbose:
print(("#%11s" + "%14s" * 4) % ("T", "E_0", "B_0", "B'_0", "V_0"))
# Plus one temperature point is necessary for computing e.g. beta.
num_elems = self._get_num_elems(self._all_temperatures) + 1
if num_elems > len(self._all_temperatures):
num_elems -= 1
temperatures = []
parameters = []
free_energies = []
for i in range(num_elems): # loop over temperaturs
if self._electronic_energies.ndim == 1:
el_energy = self._electronic_energies
else:
el_energy = self._electronic_energies[i]
fe = [ph_e + el_e
for ph_e, el_e in zip(self._fe_phonon[i], el_energy)]
try:
ep = fit_to_eos(self._volumes, fe, self._eos)
except TypeError:
print("Fitting failure at T=%.1f" % self._all_temperatures[i])
if ep is None:
# Simply omit volume point where the fitting failed.
continue
else:
[ee, eb, ebp, ev] = ep
t = self._all_temperatures[i]
temperatures.append(t)
parameters.append(ep)
free_energies.append(fe)
if verbose:
print(("%14.6f" * 5) %
(t, ep[0], ep[1] * EVAngstromToGPa, ep[2], ep[3]))
self._free_energies = np.array(free_energies)
self._temperatures = np.array(temperatures)
self._equiv_parameters = np.array(parameters)
self._equiv_volumes = np.array(self._equiv_parameters[:, 3])
self._equiv_energies = np.array(self._equiv_parameters[:, 0])
self._equiv_bulk_modulus = np.array(
self._equiv_parameters[:, 1] * EVAngstromToGPa)
self._num_elems = len(self._temperatures)
# For computing following values at temperatures, finite difference
# method is used. Therefore number of temperature points are needed
# larger than self._num_elems that nearly equals to the temparature
# point we expect.
self._set_thermal_expansion()
self._set_heat_capacity_P_numerical()
self._set_heat_capacity_P_polyfit()
self._set_gruneisen_parameter() # To be run after thermal expansion.
self._len = len(self._thermal_expansions)
assert(self._len + 1 == self._num_elems) | [
"def",
"run",
"(",
"self",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"(",
"\"#%11s\"",
"+",
"\"%14s\"",
"*",
"4",
")",
"%",
"(",
"\"T\"",
",",
"\"E_0\"",
",",
"\"B_0\"",
",",
"\"B'_0\"",
",",
"\"V_0\"",
")",
")",
... | Fit parameters to EOS at temperatures
Even if fitting failed, simply omit the volume point. In this case,
the failed temperature point doesn't exist in the returned arrays. | [
"Fit",
"parameters",
"to",
"EOS",
"at",
"temperatures"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/qha/core.py#L144-L211 | train | 222,365 |
atztogo/phonopy | phonopy/structure/cells.py | _trim_cell | def _trim_cell(relative_axes, cell, symprec):
"""Trim overlapping atoms
Parameters
----------
relative_axes: ndarray
Transformation matrix to transform supercell to a smaller cell such as:
trimmed_lattice = np.dot(relative_axes.T, cell.get_cell())
shape=(3,3)
cell: PhonopyAtoms
A supercell
symprec: float
Tolerance to find overlapping atoms in the trimmed cell
Returns
-------
tuple
trimmed_cell, extracted_atoms, mapping_table
"""
positions = cell.get_scaled_positions()
numbers = cell.get_atomic_numbers()
masses = cell.get_masses()
magmoms = cell.get_magnetic_moments()
lattice = cell.get_cell()
trimmed_lattice = np.dot(relative_axes.T, lattice)
trimmed_positions = []
trimmed_numbers = []
if masses is None:
trimmed_masses = None
else:
trimmed_masses = []
if magmoms is None:
trimmed_magmoms = None
else:
trimmed_magmoms = []
extracted_atoms = []
positions_in_new_lattice = np.dot(positions,
np.linalg.inv(relative_axes).T)
positions_in_new_lattice -= np.floor(positions_in_new_lattice)
trimmed_positions = np.zeros_like(positions_in_new_lattice)
num_atom = 0
mapping_table = np.arange(len(positions), dtype='intc')
for i, pos in enumerate(positions_in_new_lattice):
is_overlap = False
if num_atom > 0:
diff = trimmed_positions[:num_atom] - pos
diff -= np.rint(diff)
# Older numpy doesn't support axis argument.
# distances = np.linalg.norm(np.dot(diff, trimmed_lattice), axis=1)
# overlap_indices = np.where(distances < symprec)[0]
distances = np.sqrt(
np.sum(np.dot(diff, trimmed_lattice) ** 2, axis=1))
overlap_indices = np.where(distances < symprec)[0]
if len(overlap_indices) > 0:
assert len(overlap_indices) == 1
is_overlap = True
mapping_table[i] = extracted_atoms[overlap_indices[0]]
if not is_overlap:
trimmed_positions[num_atom] = pos
num_atom += 1
trimmed_numbers.append(numbers[i])
if masses is not None:
trimmed_masses.append(masses[i])
if magmoms is not None:
trimmed_magmoms.append(magmoms[i])
extracted_atoms.append(i)
# scale is not always to become integer.
scale = 1.0 / np.linalg.det(relative_axes)
if len(numbers) == np.rint(scale * len(trimmed_numbers)):
trimmed_cell = PhonopyAtoms(
numbers=trimmed_numbers,
masses=trimmed_masses,
magmoms=trimmed_magmoms,
scaled_positions=trimmed_positions[:num_atom],
cell=trimmed_lattice,
pbc=True)
return trimmed_cell, extracted_atoms, mapping_table
else:
return False | python | def _trim_cell(relative_axes, cell, symprec):
"""Trim overlapping atoms
Parameters
----------
relative_axes: ndarray
Transformation matrix to transform supercell to a smaller cell such as:
trimmed_lattice = np.dot(relative_axes.T, cell.get_cell())
shape=(3,3)
cell: PhonopyAtoms
A supercell
symprec: float
Tolerance to find overlapping atoms in the trimmed cell
Returns
-------
tuple
trimmed_cell, extracted_atoms, mapping_table
"""
positions = cell.get_scaled_positions()
numbers = cell.get_atomic_numbers()
masses = cell.get_masses()
magmoms = cell.get_magnetic_moments()
lattice = cell.get_cell()
trimmed_lattice = np.dot(relative_axes.T, lattice)
trimmed_positions = []
trimmed_numbers = []
if masses is None:
trimmed_masses = None
else:
trimmed_masses = []
if magmoms is None:
trimmed_magmoms = None
else:
trimmed_magmoms = []
extracted_atoms = []
positions_in_new_lattice = np.dot(positions,
np.linalg.inv(relative_axes).T)
positions_in_new_lattice -= np.floor(positions_in_new_lattice)
trimmed_positions = np.zeros_like(positions_in_new_lattice)
num_atom = 0
mapping_table = np.arange(len(positions), dtype='intc')
for i, pos in enumerate(positions_in_new_lattice):
is_overlap = False
if num_atom > 0:
diff = trimmed_positions[:num_atom] - pos
diff -= np.rint(diff)
# Older numpy doesn't support axis argument.
# distances = np.linalg.norm(np.dot(diff, trimmed_lattice), axis=1)
# overlap_indices = np.where(distances < symprec)[0]
distances = np.sqrt(
np.sum(np.dot(diff, trimmed_lattice) ** 2, axis=1))
overlap_indices = np.where(distances < symprec)[0]
if len(overlap_indices) > 0:
assert len(overlap_indices) == 1
is_overlap = True
mapping_table[i] = extracted_atoms[overlap_indices[0]]
if not is_overlap:
trimmed_positions[num_atom] = pos
num_atom += 1
trimmed_numbers.append(numbers[i])
if masses is not None:
trimmed_masses.append(masses[i])
if magmoms is not None:
trimmed_magmoms.append(magmoms[i])
extracted_atoms.append(i)
# scale is not always to become integer.
scale = 1.0 / np.linalg.det(relative_axes)
if len(numbers) == np.rint(scale * len(trimmed_numbers)):
trimmed_cell = PhonopyAtoms(
numbers=trimmed_numbers,
masses=trimmed_masses,
magmoms=trimmed_magmoms,
scaled_positions=trimmed_positions[:num_atom],
cell=trimmed_lattice,
pbc=True)
return trimmed_cell, extracted_atoms, mapping_table
else:
return False | [
"def",
"_trim_cell",
"(",
"relative_axes",
",",
"cell",
",",
"symprec",
")",
":",
"positions",
"=",
"cell",
".",
"get_scaled_positions",
"(",
")",
"numbers",
"=",
"cell",
".",
"get_atomic_numbers",
"(",
")",
"masses",
"=",
"cell",
".",
"get_masses",
"(",
"... | Trim overlapping atoms
Parameters
----------
relative_axes: ndarray
Transformation matrix to transform supercell to a smaller cell such as:
trimmed_lattice = np.dot(relative_axes.T, cell.get_cell())
shape=(3,3)
cell: PhonopyAtoms
A supercell
symprec: float
Tolerance to find overlapping atoms in the trimmed cell
Returns
-------
tuple
trimmed_cell, extracted_atoms, mapping_table | [
"Trim",
"overlapping",
"atoms"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L459-L543 | train | 222,366 |
atztogo/phonopy | phonopy/structure/cells.py | get_reduced_bases | def get_reduced_bases(lattice,
method='delaunay',
tolerance=1e-5):
"""Search kinds of shortest basis vectors
Parameters
----------
lattice : ndarray or list of list
Basis vectors by row vectors, [a, b, c]^T
shape=(3, 3)
method : str
delaunay: Delaunay reduction
niggli: Niggli reduction
tolerance : float
Tolerance to find shortest basis vecotrs
Returns
--------
Reduced basis as row vectors, [a_red, b_red, c_red]^T
dtype='double'
shape=(3, 3)
order='C'
"""
if method == 'niggli':
return spg.niggli_reduce(lattice, eps=tolerance)
else:
return spg.delaunay_reduce(lattice, eps=tolerance) | python | def get_reduced_bases(lattice,
method='delaunay',
tolerance=1e-5):
"""Search kinds of shortest basis vectors
Parameters
----------
lattice : ndarray or list of list
Basis vectors by row vectors, [a, b, c]^T
shape=(3, 3)
method : str
delaunay: Delaunay reduction
niggli: Niggli reduction
tolerance : float
Tolerance to find shortest basis vecotrs
Returns
--------
Reduced basis as row vectors, [a_red, b_red, c_red]^T
dtype='double'
shape=(3, 3)
order='C'
"""
if method == 'niggli':
return spg.niggli_reduce(lattice, eps=tolerance)
else:
return spg.delaunay_reduce(lattice, eps=tolerance) | [
"def",
"get_reduced_bases",
"(",
"lattice",
",",
"method",
"=",
"'delaunay'",
",",
"tolerance",
"=",
"1e-5",
")",
":",
"if",
"method",
"==",
"'niggli'",
":",
"return",
"spg",
".",
"niggli_reduce",
"(",
"lattice",
",",
"eps",
"=",
"tolerance",
")",
"else",
... | Search kinds of shortest basis vectors
Parameters
----------
lattice : ndarray or list of list
Basis vectors by row vectors, [a, b, c]^T
shape=(3, 3)
method : str
delaunay: Delaunay reduction
niggli: Niggli reduction
tolerance : float
Tolerance to find shortest basis vecotrs
Returns
--------
Reduced basis as row vectors, [a_red, b_red, c_red]^T
dtype='double'
shape=(3, 3)
order='C' | [
"Search",
"kinds",
"of",
"shortest",
"basis",
"vectors"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L549-L577 | train | 222,367 |
atztogo/phonopy | phonopy/structure/cells.py | get_smallest_vectors | def get_smallest_vectors(supercell_bases,
supercell_pos,
primitive_pos,
symprec=1e-5):
"""Find shortest atomic pair vectors
Note
----
Shortest vectors from an atom in primitive cell to an atom in
supercell in the fractional coordinates of primitive cell. If an
atom in supercell is on the border centered at an atom in
primitive and there are multiple vectors that have the same
distance (up to tolerance) and different directions, several
shortest vectors are stored.
In fact, this method is not limited to search shortest vectors between
sueprcell atoms and primitive cell atoms, but can be used to measure
shortest vectors between atoms in periodic supercell lattice frame.
Parameters
----------
supercell_bases : ndarray
Supercell basis vectors as row vectors, (a, b, c)^T. Must be order='C'.
dtype='double'
shape=(3, 3)
supercell_pos : array_like
Atomic positions in fractional coordinates of supercell.
dtype='double'
shape=(size_super, 3)
primitive_pos : array_like
Atomic positions in fractional coordinates of supercell. Note that not
in fractional coodinates of primitive cell.
dtype='double'
shape=(size_prim, 3)
symprec : float, optional, default=1e-5
Tolerance to find equal distances of vectors
Returns
-------
shortest_vectors : ndarray
Shortest vectors in supercell coordinates. The 27 in shape is the
possible maximum number of elements.
dtype='double'
shape=(size_super, size_prim, 27, 3)
multiplicities : ndarray
Number of equidistance shortest vectors
dtype='intc'
shape=(size_super, size_prim)
"""
reduced_bases = get_reduced_bases(supercell_bases,
method='delaunay',
tolerance=symprec)
trans_mat_float = np.dot(supercell_bases, np.linalg.inv(reduced_bases))
trans_mat = np.rint(trans_mat_float).astype(int)
assert (np.abs(trans_mat_float - trans_mat) < 1e-8).all()
trans_mat_inv_float = np.linalg.inv(trans_mat)
trans_mat_inv = np.rint(trans_mat_inv_float).astype(int)
assert (np.abs(trans_mat_inv_float - trans_mat_inv) < 1e-8).all()
# Reduce all positions into the cell formed by the reduced bases.
supercell_fracs = np.dot(supercell_pos, trans_mat)
supercell_fracs -= np.rint(supercell_fracs)
supercell_fracs = np.array(supercell_fracs, dtype='double', order='C')
primitive_fracs = np.dot(primitive_pos, trans_mat)
primitive_fracs -= np.rint(primitive_fracs)
primitive_fracs = np.array(primitive_fracs, dtype='double', order='C')
# For each vector, we will need to consider all nearby images in the
# reduced bases.
lattice_points = np.array([[i, j, k]
for i in (-1, 0, 1)
for j in (-1, 0, 1)
for k in (-1, 0, 1)],
dtype='intc', order='C')
# Here's where things get interesting.
# We want to avoid manually iterating over all possible pairings of
# supercell atoms and primitive atoms, because doing so creates a
# tight loop in larger structures that is difficult to optimize.
#
# Furthermore, it seems wise to call numpy.dot on as large of an array
# as possible, since numpy can shell out to BLAS to handle the
# real heavy lifting.
shortest_vectors = np.zeros(
(len(supercell_fracs), len(primitive_fracs), 27, 3),
dtype='double', order='C')
multiplicity = np.zeros((len(supercell_fracs), len(primitive_fracs)),
dtype='intc', order='C')
import phonopy._phonopy as phonoc
phonoc.gsv_set_smallest_vectors(
shortest_vectors,
multiplicity,
supercell_fracs,
primitive_fracs,
lattice_points,
np.array(reduced_bases.T, dtype='double', order='C'),
np.array(trans_mat_inv.T, dtype='intc', order='C'),
symprec)
# # For every atom in the supercell and every atom in the primitive cell,
# # we want 27 images of the vector between them.
# #
# # 'None' is used to insert trivial axes to make these arrays broadcast.
# #
# # shape: (size_super, size_prim, 27, 3)
# candidate_fracs = (
# supercell_fracs[:, None, None, :] # shape: (size_super, 1, 1, 3)
# - primitive_fracs[None, :, None, :] # shape: (1, size_prim, 1, 3)
# + lattice_points[None, None, :, :] # shape: (1, 1, 27, 3)
# )
# # To compute the lengths, we want cartesian positions.
# #
# # Conveniently, calling 'numpy.dot' between a 4D array and a 2D array
# # does vector-matrix multiplication on each row vector in the last axis
# # of the 4D array.
# #
# # shape: (size_super, size_prim, 27)
# lengths = np.array(np.sqrt(
# np.sum(np.dot(candidate_fracs, reduced_bases)**2, axis=-1)),
# dtype='double', order='C')
# # Create the output, initially consisting of all candidate vectors scaled
# # by the primitive cell.
# #
# # shape: (size_super, size_prim, 27, 3)
# candidate_vectors = np.array(np.dot(candidate_fracs, trans_mat_inv),
# dtype='double', order='C')
# # The last final bits are done in C.
# #
# # We will gather the shortest ones from each list of 27 vectors.
# shortest_vectors = np.zeros_like(candidate_vectors,
# dtype='double', order='C')
# multiplicity = np.zeros(shortest_vectors.shape[:2], dtype='intc',
# order='C')
# import phonopy._phonopy as phonoc
# phonoc.gsv_copy_smallest_vectors(shortest_vectors,
# multiplicity,
# candidate_vectors,
# lengths,
# symprec)
return shortest_vectors, multiplicity | python | def get_smallest_vectors(supercell_bases,
supercell_pos,
primitive_pos,
symprec=1e-5):
"""Find shortest atomic pair vectors
Note
----
Shortest vectors from an atom in primitive cell to an atom in
supercell in the fractional coordinates of primitive cell. If an
atom in supercell is on the border centered at an atom in
primitive and there are multiple vectors that have the same
distance (up to tolerance) and different directions, several
shortest vectors are stored.
In fact, this method is not limited to search shortest vectors between
sueprcell atoms and primitive cell atoms, but can be used to measure
shortest vectors between atoms in periodic supercell lattice frame.
Parameters
----------
supercell_bases : ndarray
Supercell basis vectors as row vectors, (a, b, c)^T. Must be order='C'.
dtype='double'
shape=(3, 3)
supercell_pos : array_like
Atomic positions in fractional coordinates of supercell.
dtype='double'
shape=(size_super, 3)
primitive_pos : array_like
Atomic positions in fractional coordinates of supercell. Note that not
in fractional coodinates of primitive cell.
dtype='double'
shape=(size_prim, 3)
symprec : float, optional, default=1e-5
Tolerance to find equal distances of vectors
Returns
-------
shortest_vectors : ndarray
Shortest vectors in supercell coordinates. The 27 in shape is the
possible maximum number of elements.
dtype='double'
shape=(size_super, size_prim, 27, 3)
multiplicities : ndarray
Number of equidistance shortest vectors
dtype='intc'
shape=(size_super, size_prim)
"""
reduced_bases = get_reduced_bases(supercell_bases,
method='delaunay',
tolerance=symprec)
trans_mat_float = np.dot(supercell_bases, np.linalg.inv(reduced_bases))
trans_mat = np.rint(trans_mat_float).astype(int)
assert (np.abs(trans_mat_float - trans_mat) < 1e-8).all()
trans_mat_inv_float = np.linalg.inv(trans_mat)
trans_mat_inv = np.rint(trans_mat_inv_float).astype(int)
assert (np.abs(trans_mat_inv_float - trans_mat_inv) < 1e-8).all()
# Reduce all positions into the cell formed by the reduced bases.
supercell_fracs = np.dot(supercell_pos, trans_mat)
supercell_fracs -= np.rint(supercell_fracs)
supercell_fracs = np.array(supercell_fracs, dtype='double', order='C')
primitive_fracs = np.dot(primitive_pos, trans_mat)
primitive_fracs -= np.rint(primitive_fracs)
primitive_fracs = np.array(primitive_fracs, dtype='double', order='C')
# For each vector, we will need to consider all nearby images in the
# reduced bases.
lattice_points = np.array([[i, j, k]
for i in (-1, 0, 1)
for j in (-1, 0, 1)
for k in (-1, 0, 1)],
dtype='intc', order='C')
# Here's where things get interesting.
# We want to avoid manually iterating over all possible pairings of
# supercell atoms and primitive atoms, because doing so creates a
# tight loop in larger structures that is difficult to optimize.
#
# Furthermore, it seems wise to call numpy.dot on as large of an array
# as possible, since numpy can shell out to BLAS to handle the
# real heavy lifting.
shortest_vectors = np.zeros(
(len(supercell_fracs), len(primitive_fracs), 27, 3),
dtype='double', order='C')
multiplicity = np.zeros((len(supercell_fracs), len(primitive_fracs)),
dtype='intc', order='C')
import phonopy._phonopy as phonoc
phonoc.gsv_set_smallest_vectors(
shortest_vectors,
multiplicity,
supercell_fracs,
primitive_fracs,
lattice_points,
np.array(reduced_bases.T, dtype='double', order='C'),
np.array(trans_mat_inv.T, dtype='intc', order='C'),
symprec)
# # For every atom in the supercell and every atom in the primitive cell,
# # we want 27 images of the vector between them.
# #
# # 'None' is used to insert trivial axes to make these arrays broadcast.
# #
# # shape: (size_super, size_prim, 27, 3)
# candidate_fracs = (
# supercell_fracs[:, None, None, :] # shape: (size_super, 1, 1, 3)
# - primitive_fracs[None, :, None, :] # shape: (1, size_prim, 1, 3)
# + lattice_points[None, None, :, :] # shape: (1, 1, 27, 3)
# )
# # To compute the lengths, we want cartesian positions.
# #
# # Conveniently, calling 'numpy.dot' between a 4D array and a 2D array
# # does vector-matrix multiplication on each row vector in the last axis
# # of the 4D array.
# #
# # shape: (size_super, size_prim, 27)
# lengths = np.array(np.sqrt(
# np.sum(np.dot(candidate_fracs, reduced_bases)**2, axis=-1)),
# dtype='double', order='C')
# # Create the output, initially consisting of all candidate vectors scaled
# # by the primitive cell.
# #
# # shape: (size_super, size_prim, 27, 3)
# candidate_vectors = np.array(np.dot(candidate_fracs, trans_mat_inv),
# dtype='double', order='C')
# # The last final bits are done in C.
# #
# # We will gather the shortest ones from each list of 27 vectors.
# shortest_vectors = np.zeros_like(candidate_vectors,
# dtype='double', order='C')
# multiplicity = np.zeros(shortest_vectors.shape[:2], dtype='intc',
# order='C')
# import phonopy._phonopy as phonoc
# phonoc.gsv_copy_smallest_vectors(shortest_vectors,
# multiplicity,
# candidate_vectors,
# lengths,
# symprec)
return shortest_vectors, multiplicity | [
"def",
"get_smallest_vectors",
"(",
"supercell_bases",
",",
"supercell_pos",
",",
"primitive_pos",
",",
"symprec",
"=",
"1e-5",
")",
":",
"reduced_bases",
"=",
"get_reduced_bases",
"(",
"supercell_bases",
",",
"method",
"=",
"'delaunay'",
",",
"tolerance",
"=",
"s... | Find shortest atomic pair vectors
Note
----
Shortest vectors from an atom in primitive cell to an atom in
supercell in the fractional coordinates of primitive cell. If an
atom in supercell is on the border centered at an atom in
primitive and there are multiple vectors that have the same
distance (up to tolerance) and different directions, several
shortest vectors are stored.
In fact, this method is not limited to search shortest vectors between
sueprcell atoms and primitive cell atoms, but can be used to measure
shortest vectors between atoms in periodic supercell lattice frame.
Parameters
----------
supercell_bases : ndarray
Supercell basis vectors as row vectors, (a, b, c)^T. Must be order='C'.
dtype='double'
shape=(3, 3)
supercell_pos : array_like
Atomic positions in fractional coordinates of supercell.
dtype='double'
shape=(size_super, 3)
primitive_pos : array_like
Atomic positions in fractional coordinates of supercell. Note that not
in fractional coodinates of primitive cell.
dtype='double'
shape=(size_prim, 3)
symprec : float, optional, default=1e-5
Tolerance to find equal distances of vectors
Returns
-------
shortest_vectors : ndarray
Shortest vectors in supercell coordinates. The 27 in shape is the
possible maximum number of elements.
dtype='double'
shape=(size_super, size_prim, 27, 3)
multiplicities : ndarray
Number of equidistance shortest vectors
dtype='intc'
shape=(size_super, size_prim) | [
"Find",
"shortest",
"atomic",
"pair",
"vectors"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L595-L741 | train | 222,368 |
atztogo/phonopy | phonopy/structure/cells.py | compute_all_sg_permutations | def compute_all_sg_permutations(positions, # scaled positions
rotations, # scaled
translations, # scaled
lattice, # column vectors
symprec):
"""Compute a permutation for every space group operation.
See 'compute_permutation_for_rotation' for more info.
Output has shape (num_rot, num_pos)
"""
out = [] # Finally the shape is fixed as (num_sym, num_pos_of_supercell).
for (sym, t) in zip(rotations, translations):
rotated_positions = np.dot(positions, sym.T) + t
out.append(compute_permutation_for_rotation(positions,
rotated_positions,
lattice,
symprec))
return np.array(out, dtype='intc', order='C') | python | def compute_all_sg_permutations(positions, # scaled positions
rotations, # scaled
translations, # scaled
lattice, # column vectors
symprec):
"""Compute a permutation for every space group operation.
See 'compute_permutation_for_rotation' for more info.
Output has shape (num_rot, num_pos)
"""
out = [] # Finally the shape is fixed as (num_sym, num_pos_of_supercell).
for (sym, t) in zip(rotations, translations):
rotated_positions = np.dot(positions, sym.T) + t
out.append(compute_permutation_for_rotation(positions,
rotated_positions,
lattice,
symprec))
return np.array(out, dtype='intc', order='C') | [
"def",
"compute_all_sg_permutations",
"(",
"positions",
",",
"# scaled positions",
"rotations",
",",
"# scaled",
"translations",
",",
"# scaled",
"lattice",
",",
"# column vectors",
"symprec",
")",
":",
"out",
"=",
"[",
"]",
"# Finally the shape is fixed as (num_sym, num_... | Compute a permutation for every space group operation.
See 'compute_permutation_for_rotation' for more info.
Output has shape (num_rot, num_pos) | [
"Compute",
"a",
"permutation",
"for",
"every",
"space",
"group",
"operation",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L744-L764 | train | 222,369 |
atztogo/phonopy | phonopy/structure/cells.py | compute_permutation_for_rotation | def compute_permutation_for_rotation(positions_a, # scaled positions
positions_b,
lattice, # column vectors
symprec):
"""Get the overall permutation such that
positions_a[perm[i]] == positions_b[i] (modulo the lattice)
or in numpy speak,
positions_a[perm] == positions_b (modulo the lattice)
This version is optimized for the case where positions_a and positions_b
are related by a rotation.
"""
# Sort both sides by some measure which is likely to produce a small
# maximum value of (sorted_rotated_index - sorted_original_index).
# The C code is optimized for this case, reducing an O(n^2)
# search down to ~O(n). (for O(n log n) work overall, including the sort)
#
# We choose distance from the nearest bravais lattice point as our measure.
def sort_by_lattice_distance(fracs):
carts = np.dot(fracs - np.rint(fracs), lattice.T)
perm = np.argsort(np.sum(carts**2, axis=1))
sorted_fracs = np.array(fracs[perm], dtype='double', order='C')
return perm, sorted_fracs
(perm_a, sorted_a) = sort_by_lattice_distance(positions_a)
(perm_b, sorted_b) = sort_by_lattice_distance(positions_b)
# Call the C code on our conditioned inputs.
perm_between = _compute_permutation_c(sorted_a,
sorted_b,
lattice,
symprec)
# Compose all of the permutations for the full permutation.
#
# Note the following properties of permutation arrays:
#
# 1. Inverse: if x[perm] == y then x == y[argsort(perm)]
# 2. Associativity: x[p][q] == x[p[q]]
return perm_a[perm_between][np.argsort(perm_b)] | python | def compute_permutation_for_rotation(positions_a, # scaled positions
positions_b,
lattice, # column vectors
symprec):
"""Get the overall permutation such that
positions_a[perm[i]] == positions_b[i] (modulo the lattice)
or in numpy speak,
positions_a[perm] == positions_b (modulo the lattice)
This version is optimized for the case where positions_a and positions_b
are related by a rotation.
"""
# Sort both sides by some measure which is likely to produce a small
# maximum value of (sorted_rotated_index - sorted_original_index).
# The C code is optimized for this case, reducing an O(n^2)
# search down to ~O(n). (for O(n log n) work overall, including the sort)
#
# We choose distance from the nearest bravais lattice point as our measure.
def sort_by_lattice_distance(fracs):
carts = np.dot(fracs - np.rint(fracs), lattice.T)
perm = np.argsort(np.sum(carts**2, axis=1))
sorted_fracs = np.array(fracs[perm], dtype='double', order='C')
return perm, sorted_fracs
(perm_a, sorted_a) = sort_by_lattice_distance(positions_a)
(perm_b, sorted_b) = sort_by_lattice_distance(positions_b)
# Call the C code on our conditioned inputs.
perm_between = _compute_permutation_c(sorted_a,
sorted_b,
lattice,
symprec)
# Compose all of the permutations for the full permutation.
#
# Note the following properties of permutation arrays:
#
# 1. Inverse: if x[perm] == y then x == y[argsort(perm)]
# 2. Associativity: x[p][q] == x[p[q]]
return perm_a[perm_between][np.argsort(perm_b)] | [
"def",
"compute_permutation_for_rotation",
"(",
"positions_a",
",",
"# scaled positions",
"positions_b",
",",
"lattice",
",",
"# column vectors",
"symprec",
")",
":",
"# Sort both sides by some measure which is likely to produce a small",
"# maximum value of (sorted_rotated_index - sor... | Get the overall permutation such that
positions_a[perm[i]] == positions_b[i] (modulo the lattice)
or in numpy speak,
positions_a[perm] == positions_b (modulo the lattice)
This version is optimized for the case where positions_a and positions_b
are related by a rotation. | [
"Get",
"the",
"overall",
"permutation",
"such",
"that"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L767-L811 | train | 222,370 |
atztogo/phonopy | phonopy/structure/cells.py | _compute_permutation_c | def _compute_permutation_c(positions_a, # scaled positions
positions_b,
lattice, # column vectors
symprec):
"""Version of '_compute_permutation_for_rotation' which just directly
calls the C function, without any conditioning of the data.
Skipping the conditioning step makes this EXTREMELY slow on large
structures.
"""
permutation = np.zeros(shape=(len(positions_a),), dtype='intc')
def permutation_error():
raise ValueError("Input forces are not enough to calculate force constants, "
"or something wrong (e.g. crystal structure does not match).")
try:
import phonopy._phonopy as phonoc
is_found = phonoc.compute_permutation(permutation,
lattice,
positions_a,
positions_b,
symprec)
if not is_found:
permutation_error()
except ImportError:
for i, pos_b in enumerate(positions_b):
diffs = positions_a - pos_b
diffs -= np.rint(diffs)
diffs = np.dot(diffs, lattice.T)
possible_j = np.nonzero(
np.sqrt(np.sum(diffs**2, axis=1)) < symprec)[0]
if len(possible_j) != 1:
permutation_error()
permutation[i] = possible_j[0]
if -1 in permutation:
permutation_error()
return permutation | python | def _compute_permutation_c(positions_a, # scaled positions
positions_b,
lattice, # column vectors
symprec):
"""Version of '_compute_permutation_for_rotation' which just directly
calls the C function, without any conditioning of the data.
Skipping the conditioning step makes this EXTREMELY slow on large
structures.
"""
permutation = np.zeros(shape=(len(positions_a),), dtype='intc')
def permutation_error():
raise ValueError("Input forces are not enough to calculate force constants, "
"or something wrong (e.g. crystal structure does not match).")
try:
import phonopy._phonopy as phonoc
is_found = phonoc.compute_permutation(permutation,
lattice,
positions_a,
positions_b,
symprec)
if not is_found:
permutation_error()
except ImportError:
for i, pos_b in enumerate(positions_b):
diffs = positions_a - pos_b
diffs -= np.rint(diffs)
diffs = np.dot(diffs, lattice.T)
possible_j = np.nonzero(
np.sqrt(np.sum(diffs**2, axis=1)) < symprec)[0]
if len(possible_j) != 1:
permutation_error()
permutation[i] = possible_j[0]
if -1 in permutation:
permutation_error()
return permutation | [
"def",
"_compute_permutation_c",
"(",
"positions_a",
",",
"# scaled positions",
"positions_b",
",",
"lattice",
",",
"# column vectors",
"symprec",
")",
":",
"permutation",
"=",
"np",
".",
"zeros",
"(",
"shape",
"=",
"(",
"len",
"(",
"positions_a",
")",
",",
")... | Version of '_compute_permutation_for_rotation' which just directly
calls the C function, without any conditioning of the data.
Skipping the conditioning step makes this EXTREMELY slow on large
structures. | [
"Version",
"of",
"_compute_permutation_for_rotation",
"which",
"just",
"directly",
"calls",
"the",
"C",
"function",
"without",
"any",
"conditioning",
"of",
"the",
"data",
".",
"Skipping",
"the",
"conditioning",
"step",
"makes",
"this",
"EXTREMELY",
"slow",
"on",
"... | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L814-L858 | train | 222,371 |
atztogo/phonopy | phonopy/structure/cells.py | estimate_supercell_matrix | def estimate_supercell_matrix(spglib_dataset,
max_num_atoms=120):
"""Estimate supercell matrix from conventional cell
Diagonal supercell matrix is estimated from basis vector lengths
and maximum number of atoms to be accepted. Supercell is assumed
to be made from the standardized cell and to be closest to sphere
under keeping lattice symmetry. For triclinic, monoclinic, and
orthorhombic cells, multiplicities for a, b, c are not constrained
by symmetry. For tetragonal and hexagonal cells, multiplicities
for a and b are chosen to be the same, and for cubic cell, those
of a, b, c are the same.
Parameters
----------
spglib_dataset : tuple
Spglib symmetry dataset
max_num_atoms : int, optional
Maximum number of atoms in created supercell to be tolerated.
Returns
-------
list of three integer numbers
Multiplicities for a, b, c basis vectors, respectively.
"""
spg_num = spglib_dataset['number']
num_atoms = len(spglib_dataset['std_types'])
lengths = _get_lattice_parameters(spglib_dataset['std_lattice'])
if spg_num <= 74: # Triclinic, monoclinic, and orthorhombic
multi = _get_multiplicity_abc(num_atoms, lengths, max_num_atoms)
elif spg_num <= 194: # Tetragonal and hexagonal
multi = _get_multiplicity_ac(num_atoms, lengths, max_num_atoms)
else: # Cubic
multi = _get_multiplicity_a(num_atoms, lengths, max_num_atoms)
return multi | python | def estimate_supercell_matrix(spglib_dataset,
max_num_atoms=120):
"""Estimate supercell matrix from conventional cell
Diagonal supercell matrix is estimated from basis vector lengths
and maximum number of atoms to be accepted. Supercell is assumed
to be made from the standardized cell and to be closest to sphere
under keeping lattice symmetry. For triclinic, monoclinic, and
orthorhombic cells, multiplicities for a, b, c are not constrained
by symmetry. For tetragonal and hexagonal cells, multiplicities
for a and b are chosen to be the same, and for cubic cell, those
of a, b, c are the same.
Parameters
----------
spglib_dataset : tuple
Spglib symmetry dataset
max_num_atoms : int, optional
Maximum number of atoms in created supercell to be tolerated.
Returns
-------
list of three integer numbers
Multiplicities for a, b, c basis vectors, respectively.
"""
spg_num = spglib_dataset['number']
num_atoms = len(spglib_dataset['std_types'])
lengths = _get_lattice_parameters(spglib_dataset['std_lattice'])
if spg_num <= 74: # Triclinic, monoclinic, and orthorhombic
multi = _get_multiplicity_abc(num_atoms, lengths, max_num_atoms)
elif spg_num <= 194: # Tetragonal and hexagonal
multi = _get_multiplicity_ac(num_atoms, lengths, max_num_atoms)
else: # Cubic
multi = _get_multiplicity_a(num_atoms, lengths, max_num_atoms)
return multi | [
"def",
"estimate_supercell_matrix",
"(",
"spglib_dataset",
",",
"max_num_atoms",
"=",
"120",
")",
":",
"spg_num",
"=",
"spglib_dataset",
"[",
"'number'",
"]",
"num_atoms",
"=",
"len",
"(",
"spglib_dataset",
"[",
"'std_types'",
"]",
")",
"lengths",
"=",
"_get_lat... | Estimate supercell matrix from conventional cell
Diagonal supercell matrix is estimated from basis vector lengths
and maximum number of atoms to be accepted. Supercell is assumed
to be made from the standardized cell and to be closest to sphere
under keeping lattice symmetry. For triclinic, monoclinic, and
orthorhombic cells, multiplicities for a, b, c are not constrained
by symmetry. For tetragonal and hexagonal cells, multiplicities
for a and b are chosen to be the same, and for cubic cell, those
of a, b, c are the same.
Parameters
----------
spglib_dataset : tuple
Spglib symmetry dataset
max_num_atoms : int, optional
Maximum number of atoms in created supercell to be tolerated.
Returns
-------
list of three integer numbers
Multiplicities for a, b, c basis vectors, respectively. | [
"Estimate",
"supercell",
"matrix",
"from",
"conventional",
"cell"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L1208-L1246 | train | 222,372 |
atztogo/phonopy | phonopy/structure/cells.py | _get_lattice_parameters | def _get_lattice_parameters(lattice):
"""Return basis vector lengths
Parameters
----------
lattice : array_like
Basis vectors given as column vectors
shape=(3, 3), dtype='double'
Returns
-------
ndarray, shape=(3,), dtype='double'
"""
return np.array(np.sqrt(np.dot(lattice.T, lattice).diagonal()),
dtype='double') | python | def _get_lattice_parameters(lattice):
"""Return basis vector lengths
Parameters
----------
lattice : array_like
Basis vectors given as column vectors
shape=(3, 3), dtype='double'
Returns
-------
ndarray, shape=(3,), dtype='double'
"""
return np.array(np.sqrt(np.dot(lattice.T, lattice).diagonal()),
dtype='double') | [
"def",
"_get_lattice_parameters",
"(",
"lattice",
")",
":",
"return",
"np",
".",
"array",
"(",
"np",
".",
"sqrt",
"(",
"np",
".",
"dot",
"(",
"lattice",
".",
"T",
",",
"lattice",
")",
".",
"diagonal",
"(",
")",
")",
",",
"dtype",
"=",
"'double'",
"... | Return basis vector lengths
Parameters
----------
lattice : array_like
Basis vectors given as column vectors
shape=(3, 3), dtype='double'
Returns
-------
ndarray, shape=(3,), dtype='double' | [
"Return",
"basis",
"vector",
"lengths"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L1249-L1265 | train | 222,373 |
atztogo/phonopy | phonopy/structure/cells.py | SNF3x3._second | def _second(self):
"""Find Smith normal form for Right-low 2x2 matrix"""
self._second_one_loop()
A = self._A
if A[2, 1] == 0:
return True
elif A[2, 1] % A[1, 1] == 0:
self._second_finalize()
self._Ps += self._L
self._L = []
return True
else:
return False | python | def _second(self):
"""Find Smith normal form for Right-low 2x2 matrix"""
self._second_one_loop()
A = self._A
if A[2, 1] == 0:
return True
elif A[2, 1] % A[1, 1] == 0:
self._second_finalize()
self._Ps += self._L
self._L = []
return True
else:
return False | [
"def",
"_second",
"(",
"self",
")",
":",
"self",
".",
"_second_one_loop",
"(",
")",
"A",
"=",
"self",
".",
"_A",
"if",
"A",
"[",
"2",
",",
"1",
"]",
"==",
"0",
":",
"return",
"True",
"elif",
"A",
"[",
"2",
",",
"1",
"]",
"%",
"A",
"[",
"1",... | Find Smith normal form for Right-low 2x2 matrix | [
"Find",
"Smith",
"normal",
"form",
"for",
"Right",
"-",
"low",
"2x2",
"matrix"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L1030-L1043 | train | 222,374 |
atztogo/phonopy | phonopy/structure/cells.py | SNF3x3._second_column | def _second_column(self):
"""Right-low 2x2 matrix
Assume elements in first row and column are all zero except for A[0,0].
"""
if self._A[1, 1] == 0 and self._A[2, 1] != 0:
self._swap_rows(1, 2)
if self._A[2, 1] != 0:
self._zero_second_column() | python | def _second_column(self):
"""Right-low 2x2 matrix
Assume elements in first row and column are all zero except for A[0,0].
"""
if self._A[1, 1] == 0 and self._A[2, 1] != 0:
self._swap_rows(1, 2)
if self._A[2, 1] != 0:
self._zero_second_column() | [
"def",
"_second_column",
"(",
"self",
")",
":",
"if",
"self",
".",
"_A",
"[",
"1",
",",
"1",
"]",
"==",
"0",
"and",
"self",
".",
"_A",
"[",
"2",
",",
"1",
"]",
"!=",
"0",
":",
"self",
".",
"_swap_rows",
"(",
"1",
",",
"2",
")",
"if",
"self"... | Right-low 2x2 matrix
Assume elements in first row and column are all zero except for A[0,0]. | [
"Right",
"-",
"low",
"2x2",
"matrix"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L1055-L1066 | train | 222,375 |
atztogo/phonopy | phonopy/structure/cells.py | SNF3x3._swap_rows | def _swap_rows(self, i, j):
"""Swap i and j rows
As the side effect, determinant flips.
"""
L = np.eye(3, dtype='intc')
L[i, i] = 0
L[j, j] = 0
L[i, j] = 1
L[j, i] = 1
self._L.append(L.copy())
self._A = np.dot(L, self._A) | python | def _swap_rows(self, i, j):
"""Swap i and j rows
As the side effect, determinant flips.
"""
L = np.eye(3, dtype='intc')
L[i, i] = 0
L[j, j] = 0
L[i, j] = 1
L[j, i] = 1
self._L.append(L.copy())
self._A = np.dot(L, self._A) | [
"def",
"_swap_rows",
"(",
"self",
",",
"i",
",",
"j",
")",
":",
"L",
"=",
"np",
".",
"eye",
"(",
"3",
",",
"dtype",
"=",
"'intc'",
")",
"L",
"[",
"i",
",",
"i",
"]",
"=",
"0",
"L",
"[",
"j",
",",
"j",
"]",
"=",
"0",
"L",
"[",
"i",
","... | Swap i and j rows
As the side effect, determinant flips. | [
"Swap",
"i",
"and",
"j",
"rows"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L1088-L1101 | train | 222,376 |
atztogo/phonopy | phonopy/structure/cells.py | SNF3x3._flip_sign_row | def _flip_sign_row(self, i):
"""Multiply -1 for all elements in row"""
L = np.eye(3, dtype='intc')
L[i, i] = -1
self._L.append(L.copy())
self._A = np.dot(L, self._A) | python | def _flip_sign_row(self, i):
"""Multiply -1 for all elements in row"""
L = np.eye(3, dtype='intc')
L[i, i] = -1
self._L.append(L.copy())
self._A = np.dot(L, self._A) | [
"def",
"_flip_sign_row",
"(",
"self",
",",
"i",
")",
":",
"L",
"=",
"np",
".",
"eye",
"(",
"3",
",",
"dtype",
"=",
"'intc'",
")",
"L",
"[",
"i",
",",
"i",
"]",
"=",
"-",
"1",
"self",
".",
"_L",
".",
"append",
"(",
"L",
".",
"copy",
"(",
"... | Multiply -1 for all elements in row | [
"Multiply",
"-",
"1",
"for",
"all",
"elements",
"in",
"row"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L1103-L1109 | train | 222,377 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.dataset | def dataset(self, dataset):
"""Set dataset having displacements and optionally forces
Note
----
Elements of the list accessed by 'first_atoms' corresponds to each
displaced supercell. Each displaced supercell contains only one
displacement. dict['first_atoms']['forces'] gives atomic forces in
each displaced supercell.
Parameters
----------
displacement_dataset : dict
There are two dict structures.
Type 1. One atomic displacement in each supercell:
{'natom': number of atoms in supercell,
'first_atoms': [
{'number': atom index of displaced atom,
'displacement': displacement in Cartesian coordinates,
'forces': forces on atoms in supercell},
{...}, ...]}
Type 2. All atomic displacements in each supercell:
{'natom': number of atoms in supercell,
'displacements': ndarray, dtype='double', order='C',
shape=(supercells, natom, 3)
'forces': ndarray, dtype='double',, order='C',
shape=(supercells, natom, 3)}
In type 2, displacements and forces can be given by numpy array
with different shape but that can be reshaped to
(supercells, natom, 3).
"""
if 'displacements' in dataset:
natom = self._supercell.get_number_of_atoms()
if type(dataset['displacements']) is np.ndarray:
if dataset['displacements'].ndim in (1, 2):
d = dataset['displacements'].reshape((-1, natom, 3))
dataset['displacements'] = d
if type(dataset['forces']) is np.ndarray:
if dataset['forces'].ndim in (1, 2):
f = dataset['forces'].reshape((-1, natom, 3))
dataset['forces'] = f
self._displacement_dataset = dataset
self._supercells_with_displacements = None | python | def dataset(self, dataset):
"""Set dataset having displacements and optionally forces
Note
----
Elements of the list accessed by 'first_atoms' corresponds to each
displaced supercell. Each displaced supercell contains only one
displacement. dict['first_atoms']['forces'] gives atomic forces in
each displaced supercell.
Parameters
----------
displacement_dataset : dict
There are two dict structures.
Type 1. One atomic displacement in each supercell:
{'natom': number of atoms in supercell,
'first_atoms': [
{'number': atom index of displaced atom,
'displacement': displacement in Cartesian coordinates,
'forces': forces on atoms in supercell},
{...}, ...]}
Type 2. All atomic displacements in each supercell:
{'natom': number of atoms in supercell,
'displacements': ndarray, dtype='double', order='C',
shape=(supercells, natom, 3)
'forces': ndarray, dtype='double',, order='C',
shape=(supercells, natom, 3)}
In type 2, displacements and forces can be given by numpy array
with different shape but that can be reshaped to
(supercells, natom, 3).
"""
if 'displacements' in dataset:
natom = self._supercell.get_number_of_atoms()
if type(dataset['displacements']) is np.ndarray:
if dataset['displacements'].ndim in (1, 2):
d = dataset['displacements'].reshape((-1, natom, 3))
dataset['displacements'] = d
if type(dataset['forces']) is np.ndarray:
if dataset['forces'].ndim in (1, 2):
f = dataset['forces'].reshape((-1, natom, 3))
dataset['forces'] = f
self._displacement_dataset = dataset
self._supercells_with_displacements = None | [
"def",
"dataset",
"(",
"self",
",",
"dataset",
")",
":",
"if",
"'displacements'",
"in",
"dataset",
":",
"natom",
"=",
"self",
".",
"_supercell",
".",
"get_number_of_atoms",
"(",
")",
"if",
"type",
"(",
"dataset",
"[",
"'displacements'",
"]",
")",
"is",
"... | Set dataset having displacements and optionally forces
Note
----
Elements of the list accessed by 'first_atoms' corresponds to each
displaced supercell. Each displaced supercell contains only one
displacement. dict['first_atoms']['forces'] gives atomic forces in
each displaced supercell.
Parameters
----------
displacement_dataset : dict
There are two dict structures.
Type 1. One atomic displacement in each supercell:
{'natom': number of atoms in supercell,
'first_atoms': [
{'number': atom index of displaced atom,
'displacement': displacement in Cartesian coordinates,
'forces': forces on atoms in supercell},
{...}, ...]}
Type 2. All atomic displacements in each supercell:
{'natom': number of atoms in supercell,
'displacements': ndarray, dtype='double', order='C',
shape=(supercells, natom, 3)
'forces': ndarray, dtype='double',, order='C',
shape=(supercells, natom, 3)}
In type 2, displacements and forces can be given by numpy array
with different shape but that can be reshaped to
(supercells, natom, 3). | [
"Set",
"dataset",
"having",
"displacements",
"and",
"optionally",
"forces"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L448-L492 | train | 222,378 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.forces | def forces(self, sets_of_forces):
"""Set forces in displacement dataset.
Parameters
----------
sets_of_forces : array_like
A set of atomic forces in displaced supercells. The order of
displaced supercells has to match with that in displacement
dataset.
shape=(displaced supercells, atoms in supercell, 3), dtype='double'
[[[f_1x, f_1y, f_1z], [f_2x, f_2y, f_2z], ...], # first supercell
[[f_1x, f_1y, f_1z], [f_2x, f_2y, f_2z], ...], # second supercell
...
]
"""
if 'first_atoms' in self._displacement_dataset:
for disp, forces in zip(self._displacement_dataset['first_atoms'],
sets_of_forces):
disp['forces'] = forces
elif 'forces' in self._displacement_dataset:
forces = np.array(sets_of_forces, dtype='double', order='C')
self._displacement_dataset['forces'] = forces | python | def forces(self, sets_of_forces):
"""Set forces in displacement dataset.
Parameters
----------
sets_of_forces : array_like
A set of atomic forces in displaced supercells. The order of
displaced supercells has to match with that in displacement
dataset.
shape=(displaced supercells, atoms in supercell, 3), dtype='double'
[[[f_1x, f_1y, f_1z], [f_2x, f_2y, f_2z], ...], # first supercell
[[f_1x, f_1y, f_1z], [f_2x, f_2y, f_2z], ...], # second supercell
...
]
"""
if 'first_atoms' in self._displacement_dataset:
for disp, forces in zip(self._displacement_dataset['first_atoms'],
sets_of_forces):
disp['forces'] = forces
elif 'forces' in self._displacement_dataset:
forces = np.array(sets_of_forces, dtype='double', order='C')
self._displacement_dataset['forces'] = forces | [
"def",
"forces",
"(",
"self",
",",
"sets_of_forces",
")",
":",
"if",
"'first_atoms'",
"in",
"self",
".",
"_displacement_dataset",
":",
"for",
"disp",
",",
"forces",
"in",
"zip",
"(",
"self",
".",
"_displacement_dataset",
"[",
"'first_atoms'",
"]",
",",
"sets... | Set forces in displacement dataset.
Parameters
----------
sets_of_forces : array_like
A set of atomic forces in displaced supercells. The order of
displaced supercells has to match with that in displacement
dataset.
shape=(displaced supercells, atoms in supercell, 3), dtype='double'
[[[f_1x, f_1y, f_1z], [f_2x, f_2y, f_2z], ...], # first supercell
[[f_1x, f_1y, f_1z], [f_2x, f_2y, f_2z], ...], # second supercell
...
] | [
"Set",
"forces",
"in",
"displacement",
"dataset",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L498-L522 | train | 222,379 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.force_constants | def force_constants(self, force_constants):
"""Set force constants
Parameters
----------
force_constants : array_like
Force constants matrix. If this is given in own condiguous ndarray
with order='C' and dtype='double', internal copy of data is
avoided. Therefore some computational resources are saved.
shape=(atoms in supercell, atoms in supercell, 3, 3),
dtype='double'
"""
if type(force_constants) is np.ndarray:
fc_shape = force_constants.shape
if fc_shape[0] != fc_shape[1]:
if self._primitive.get_number_of_atoms() != fc_shape[0]:
msg = ("Force constants shape disagrees with crystal "
"structure setting. This may be due to "
"PRIMITIVE_AXIS.")
raise RuntimeError(msg)
self._force_constants = force_constants
if self._primitive.get_masses() is not None:
self._set_dynamical_matrix() | python | def force_constants(self, force_constants):
"""Set force constants
Parameters
----------
force_constants : array_like
Force constants matrix. If this is given in own condiguous ndarray
with order='C' and dtype='double', internal copy of data is
avoided. Therefore some computational resources are saved.
shape=(atoms in supercell, atoms in supercell, 3, 3),
dtype='double'
"""
if type(force_constants) is np.ndarray:
fc_shape = force_constants.shape
if fc_shape[0] != fc_shape[1]:
if self._primitive.get_number_of_atoms() != fc_shape[0]:
msg = ("Force constants shape disagrees with crystal "
"structure setting. This may be due to "
"PRIMITIVE_AXIS.")
raise RuntimeError(msg)
self._force_constants = force_constants
if self._primitive.get_masses() is not None:
self._set_dynamical_matrix() | [
"def",
"force_constants",
"(",
"self",
",",
"force_constants",
")",
":",
"if",
"type",
"(",
"force_constants",
")",
"is",
"np",
".",
"ndarray",
":",
"fc_shape",
"=",
"force_constants",
".",
"shape",
"if",
"fc_shape",
"[",
"0",
"]",
"!=",
"fc_shape",
"[",
... | Set force constants
Parameters
----------
force_constants : array_like
Force constants matrix. If this is given in own condiguous ndarray
with order='C' and dtype='double', internal copy of data is
avoided. Therefore some computational resources are saved.
shape=(atoms in supercell, atoms in supercell, 3, 3),
dtype='double' | [
"Set",
"force",
"constants"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L528-L553 | train | 222,380 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.generate_displacements | def generate_displacements(self,
distance=0.01,
is_plusminus='auto',
is_diagonal=True,
is_trigonal=False):
"""Generate displacement dataset"""
displacement_directions = get_least_displacements(
self._symmetry,
is_plusminus=is_plusminus,
is_diagonal=is_diagonal,
is_trigonal=is_trigonal,
log_level=self._log_level)
displacement_dataset = directions_to_displacement_dataset(
displacement_directions,
distance,
self._supercell)
self.set_displacement_dataset(displacement_dataset) | python | def generate_displacements(self,
distance=0.01,
is_plusminus='auto',
is_diagonal=True,
is_trigonal=False):
"""Generate displacement dataset"""
displacement_directions = get_least_displacements(
self._symmetry,
is_plusminus=is_plusminus,
is_diagonal=is_diagonal,
is_trigonal=is_trigonal,
log_level=self._log_level)
displacement_dataset = directions_to_displacement_dataset(
displacement_directions,
distance,
self._supercell)
self.set_displacement_dataset(displacement_dataset) | [
"def",
"generate_displacements",
"(",
"self",
",",
"distance",
"=",
"0.01",
",",
"is_plusminus",
"=",
"'auto'",
",",
"is_diagonal",
"=",
"True",
",",
"is_trigonal",
"=",
"False",
")",
":",
"displacement_directions",
"=",
"get_least_displacements",
"(",
"self",
"... | Generate displacement dataset | [
"Generate",
"displacement",
"dataset"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L570-L586 | train | 222,381 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.get_dynamical_matrix_at_q | def get_dynamical_matrix_at_q(self, q):
"""Calculate dynamical matrix at a given q-point
Parameters
----------
q: array_like
A q-vector.
shape=(3,), dtype='double'
Returns
-------
dynamical_matrix: ndarray
Dynamical matrix.
shape=(bands, bands), dtype='complex'
"""
self._set_dynamical_matrix()
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._dynamical_matrix.set_dynamical_matrix(q)
return self._dynamical_matrix.get_dynamical_matrix() | python | def get_dynamical_matrix_at_q(self, q):
"""Calculate dynamical matrix at a given q-point
Parameters
----------
q: array_like
A q-vector.
shape=(3,), dtype='double'
Returns
-------
dynamical_matrix: ndarray
Dynamical matrix.
shape=(bands, bands), dtype='complex'
"""
self._set_dynamical_matrix()
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._dynamical_matrix.set_dynamical_matrix(q)
return self._dynamical_matrix.get_dynamical_matrix() | [
"def",
"get_dynamical_matrix_at_q",
"(",
"self",
",",
"q",
")",
":",
"self",
".",
"_set_dynamical_matrix",
"(",
")",
"if",
"self",
".",
"_dynamical_matrix",
"is",
"None",
":",
"msg",
"=",
"(",
"\"Dynamical matrix has not yet built.\"",
")",
"raise",
"RuntimeError"... | Calculate dynamical matrix at a given q-point
Parameters
----------
q: array_like
A q-vector.
shape=(3,), dtype='double'
Returns
-------
dynamical_matrix: ndarray
Dynamical matrix.
shape=(bands, bands), dtype='complex' | [
"Calculate",
"dynamical",
"matrix",
"at",
"a",
"given",
"q",
"-",
"point"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L652-L675 | train | 222,382 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.get_frequencies | def get_frequencies(self, q):
"""Calculate phonon frequencies at a given q-point
Parameters
----------
q: array_like
A q-vector.
shape=(3,), dtype='double'
Returns
-------
frequencies: ndarray
Phonon frequencies.
shape=(bands, ), dtype='double'
"""
self._set_dynamical_matrix()
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._dynamical_matrix.set_dynamical_matrix(q)
dm = self._dynamical_matrix.get_dynamical_matrix()
frequencies = []
for eig in np.linalg.eigvalsh(dm).real:
if eig < 0:
frequencies.append(-np.sqrt(-eig))
else:
frequencies.append(np.sqrt(eig))
return np.array(frequencies) * self._factor | python | def get_frequencies(self, q):
"""Calculate phonon frequencies at a given q-point
Parameters
----------
q: array_like
A q-vector.
shape=(3,), dtype='double'
Returns
-------
frequencies: ndarray
Phonon frequencies.
shape=(bands, ), dtype='double'
"""
self._set_dynamical_matrix()
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._dynamical_matrix.set_dynamical_matrix(q)
dm = self._dynamical_matrix.get_dynamical_matrix()
frequencies = []
for eig in np.linalg.eigvalsh(dm).real:
if eig < 0:
frequencies.append(-np.sqrt(-eig))
else:
frequencies.append(np.sqrt(eig))
return np.array(frequencies) * self._factor | [
"def",
"get_frequencies",
"(",
"self",
",",
"q",
")",
":",
"self",
".",
"_set_dynamical_matrix",
"(",
")",
"if",
"self",
".",
"_dynamical_matrix",
"is",
"None",
":",
"msg",
"=",
"(",
"\"Dynamical matrix has not yet built.\"",
")",
"raise",
"RuntimeError",
"(",
... | Calculate phonon frequencies at a given q-point
Parameters
----------
q: array_like
A q-vector.
shape=(3,), dtype='double'
Returns
-------
frequencies: ndarray
Phonon frequencies.
shape=(bands, ), dtype='double' | [
"Calculate",
"phonon",
"frequencies",
"at",
"a",
"given",
"q",
"-",
"point"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L677-L707 | train | 222,383 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.get_frequencies_with_eigenvectors | def get_frequencies_with_eigenvectors(self, q):
"""Calculate phonon frequencies and eigenvectors at a given q-point
Parameters
----------
q: array_like
A q-vector.
shape=(3,)
Returns
-------
(frequencies, eigenvectors)
frequencies: ndarray
Phonon frequencies
shape=(bands, ), dtype='double', order='C'
eigenvectors: ndarray
Phonon eigenvectors
shape=(bands, bands), dtype='complex', order='C'
"""
self._set_dynamical_matrix()
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._dynamical_matrix.set_dynamical_matrix(q)
dm = self._dynamical_matrix.get_dynamical_matrix()
frequencies = []
eigvals, eigenvectors = np.linalg.eigh(dm)
frequencies = []
for eig in eigvals:
if eig < 0:
frequencies.append(-np.sqrt(-eig))
else:
frequencies.append(np.sqrt(eig))
return np.array(frequencies) * self._factor, eigenvectors | python | def get_frequencies_with_eigenvectors(self, q):
"""Calculate phonon frequencies and eigenvectors at a given q-point
Parameters
----------
q: array_like
A q-vector.
shape=(3,)
Returns
-------
(frequencies, eigenvectors)
frequencies: ndarray
Phonon frequencies
shape=(bands, ), dtype='double', order='C'
eigenvectors: ndarray
Phonon eigenvectors
shape=(bands, bands), dtype='complex', order='C'
"""
self._set_dynamical_matrix()
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._dynamical_matrix.set_dynamical_matrix(q)
dm = self._dynamical_matrix.get_dynamical_matrix()
frequencies = []
eigvals, eigenvectors = np.linalg.eigh(dm)
frequencies = []
for eig in eigvals:
if eig < 0:
frequencies.append(-np.sqrt(-eig))
else:
frequencies.append(np.sqrt(eig))
return np.array(frequencies) * self._factor, eigenvectors | [
"def",
"get_frequencies_with_eigenvectors",
"(",
"self",
",",
"q",
")",
":",
"self",
".",
"_set_dynamical_matrix",
"(",
")",
"if",
"self",
".",
"_dynamical_matrix",
"is",
"None",
":",
"msg",
"=",
"(",
"\"Dynamical matrix has not yet built.\"",
")",
"raise",
"Runti... | Calculate phonon frequencies and eigenvectors at a given q-point
Parameters
----------
q: array_like
A q-vector.
shape=(3,)
Returns
-------
(frequencies, eigenvectors)
frequencies: ndarray
Phonon frequencies
shape=(bands, ), dtype='double', order='C'
eigenvectors: ndarray
Phonon eigenvectors
shape=(bands, bands), dtype='complex', order='C' | [
"Calculate",
"phonon",
"frequencies",
"and",
"eigenvectors",
"at",
"a",
"given",
"q",
"-",
"point"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L709-L746 | train | 222,384 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.run_band_structure | def run_band_structure(self,
paths,
with_eigenvectors=False,
with_group_velocities=False,
is_band_connection=False,
path_connections=None,
labels=None,
is_legacy_plot=False):
"""Run phonon band structure calculation.
Parameters
----------
paths : List of array_like
Sets of qpoints that can be passed to phonopy.set_band_structure().
Numbers of qpoints can be different.
shape of each array_like : (qpoints, 3)
with_eigenvectors : bool, optional
Flag whether eigenvectors are calculated or not. Default is False.
with_group_velocities : bool, optional
Flag whether group velocities are calculated or not. Default is
False.
is_band_connection : bool, optional
Flag whether each band is connected or not. This is achieved by
comparing similarity of eigenvectors of neghboring poins. Sometimes
this fails. Default is False.
path_connections : List of bool, optional
This is only used in graphical plot of band structure and gives
whether each path is connected to the next path or not,
i.e., if False, there is a jump of q-points. Number of elements is
the same at that of paths. Default is None.
labels : List of str, optional
This is only used in graphical plot of band structure and gives
labels of end points of each path. The number of labels is equal
to (2 - np.array(path_connections)).sum().
is_legacy_plot: bool, optional
This makes the old style band structure plot. Default is False.
"""
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
if with_group_velocities:
if self._group_velocity is None:
self._set_group_velocity()
group_velocity = self._group_velocity
else:
group_velocity = None
self._band_structure = BandStructure(
paths,
self._dynamical_matrix,
with_eigenvectors=with_eigenvectors,
is_band_connection=is_band_connection,
group_velocity=group_velocity,
path_connections=path_connections,
labels=labels,
is_legacy_plot=is_legacy_plot,
factor=self._factor) | python | def run_band_structure(self,
paths,
with_eigenvectors=False,
with_group_velocities=False,
is_band_connection=False,
path_connections=None,
labels=None,
is_legacy_plot=False):
"""Run phonon band structure calculation.
Parameters
----------
paths : List of array_like
Sets of qpoints that can be passed to phonopy.set_band_structure().
Numbers of qpoints can be different.
shape of each array_like : (qpoints, 3)
with_eigenvectors : bool, optional
Flag whether eigenvectors are calculated or not. Default is False.
with_group_velocities : bool, optional
Flag whether group velocities are calculated or not. Default is
False.
is_band_connection : bool, optional
Flag whether each band is connected or not. This is achieved by
comparing similarity of eigenvectors of neghboring poins. Sometimes
this fails. Default is False.
path_connections : List of bool, optional
This is only used in graphical plot of band structure and gives
whether each path is connected to the next path or not,
i.e., if False, there is a jump of q-points. Number of elements is
the same at that of paths. Default is None.
labels : List of str, optional
This is only used in graphical plot of band structure and gives
labels of end points of each path. The number of labels is equal
to (2 - np.array(path_connections)).sum().
is_legacy_plot: bool, optional
This makes the old style band structure plot. Default is False.
"""
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
if with_group_velocities:
if self._group_velocity is None:
self._set_group_velocity()
group_velocity = self._group_velocity
else:
group_velocity = None
self._band_structure = BandStructure(
paths,
self._dynamical_matrix,
with_eigenvectors=with_eigenvectors,
is_band_connection=is_band_connection,
group_velocity=group_velocity,
path_connections=path_connections,
labels=labels,
is_legacy_plot=is_legacy_plot,
factor=self._factor) | [
"def",
"run_band_structure",
"(",
"self",
",",
"paths",
",",
"with_eigenvectors",
"=",
"False",
",",
"with_group_velocities",
"=",
"False",
",",
"is_band_connection",
"=",
"False",
",",
"path_connections",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"is_legacy... | Run phonon band structure calculation.
Parameters
----------
paths : List of array_like
Sets of qpoints that can be passed to phonopy.set_band_structure().
Numbers of qpoints can be different.
shape of each array_like : (qpoints, 3)
with_eigenvectors : bool, optional
Flag whether eigenvectors are calculated or not. Default is False.
with_group_velocities : bool, optional
Flag whether group velocities are calculated or not. Default is
False.
is_band_connection : bool, optional
Flag whether each band is connected or not. This is achieved by
comparing similarity of eigenvectors of neghboring poins. Sometimes
this fails. Default is False.
path_connections : List of bool, optional
This is only used in graphical plot of band structure and gives
whether each path is connected to the next path or not,
i.e., if False, there is a jump of q-points. Number of elements is
the same at that of paths. Default is None.
labels : List of str, optional
This is only used in graphical plot of band structure and gives
labels of end points of each path. The number of labels is equal
to (2 - np.array(path_connections)).sum().
is_legacy_plot: bool, optional
This makes the old style band structure plot. Default is False. | [
"Run",
"phonon",
"band",
"structure",
"calculation",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L749-L808 | train | 222,385 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.init_mesh | def init_mesh(self,
mesh=100.0,
shift=None,
is_time_reversal=True,
is_mesh_symmetry=True,
with_eigenvectors=False,
with_group_velocities=False,
is_gamma_center=False,
use_iter_mesh=False):
"""Initialize mesh sampling phonon calculation without starting to run.
Phonon calculation starts explicitly with calling Mesh.run() or
implicitly with accessing getters of Mesh instance, e.g.,
Mesh.frequencies.
Parameters
----------
mesh: array_like or float, optional
Mesh numbers along a, b, c axes when array_like object is given.
dtype='intc', shape=(3,)
When float value is given, uniform mesh is generated following
VASP convention by
N = max(1, nint(l * |a|^*))
where 'nint' is the function to return the nearest integer. In this
case, it is forced to set is_gamma_center=True.
Default value is 100.0.
shift: array_like, optional
Mesh shifts along a*, b*, c* axes with respect to neighboring grid
points from the original mesh (Monkhorst-Pack or Gamma center).
0.5 gives half grid shift. Normally 0 or 0.5 is given.
Otherwise q-points symmetry search is not performed.
Default is None (no additional shift).
dtype='double', shape=(3, )
is_time_reversal: bool, optional
Time reversal symmetry is considered in symmetry search. By this,
inversion symmetry is always included. Default is True.
is_mesh_symmetry: bool, optional
Wheather symmetry search is done or not. Default is True
with_eigenvectors: bool, optional
Eigenvectors are stored by setting True. Default False.
with_group_velocities : bool, optional
Group velocities are calculated by setting True. Default is
False.
is_gamma_center: bool, default False
Uniform mesh grids are generated centring at Gamma point but not
the Monkhorst-Pack scheme. When type(mesh) is float, this parameter
setting is ignored and it is forced to set is_gamma_center=True.
use_iter_mesh: bool
Use IterMesh instead of Mesh class not to store phonon properties
in its instance to save memory consumption. This is used with
ThermalDisplacements and ThermalDisplacementMatrices.
Default is False.
"""
if self._dynamical_matrix is None:
msg = "Dynamical matrix has not yet built."
raise RuntimeError(msg)
_mesh = np.array(mesh)
mesh_nums = None
if _mesh.shape:
if _mesh.shape == (3,):
mesh_nums = mesh
_is_gamma_center = is_gamma_center
else:
if self._primitive_symmetry is not None:
rots = self._primitive_symmetry.get_pointgroup_operations()
mesh_nums = length2mesh(mesh,
self._primitive.get_cell(),
rotations=rots)
else:
mesh_nums = length2mesh(mesh, self._primitive.get_cell())
_is_gamma_center = True
if mesh_nums is None:
msg = "mesh has inappropriate type."
raise TypeError(msg)
if with_group_velocities:
if self._group_velocity is None:
self._set_group_velocity()
group_velocity = self._group_velocity
else:
group_velocity = None
if use_iter_mesh:
self._mesh = IterMesh(
self._dynamical_matrix,
mesh,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=with_eigenvectors,
is_gamma_center=is_gamma_center,
rotations=self._primitive_symmetry.get_pointgroup_operations(),
factor=self._factor)
else:
self._mesh = Mesh(
self._dynamical_matrix,
mesh_nums,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=with_eigenvectors,
is_gamma_center=_is_gamma_center,
group_velocity=group_velocity,
rotations=self._primitive_symmetry.get_pointgroup_operations(),
factor=self._factor,
use_lapack_solver=self._use_lapack_solver) | python | def init_mesh(self,
mesh=100.0,
shift=None,
is_time_reversal=True,
is_mesh_symmetry=True,
with_eigenvectors=False,
with_group_velocities=False,
is_gamma_center=False,
use_iter_mesh=False):
"""Initialize mesh sampling phonon calculation without starting to run.
Phonon calculation starts explicitly with calling Mesh.run() or
implicitly with accessing getters of Mesh instance, e.g.,
Mesh.frequencies.
Parameters
----------
mesh: array_like or float, optional
Mesh numbers along a, b, c axes when array_like object is given.
dtype='intc', shape=(3,)
When float value is given, uniform mesh is generated following
VASP convention by
N = max(1, nint(l * |a|^*))
where 'nint' is the function to return the nearest integer. In this
case, it is forced to set is_gamma_center=True.
Default value is 100.0.
shift: array_like, optional
Mesh shifts along a*, b*, c* axes with respect to neighboring grid
points from the original mesh (Monkhorst-Pack or Gamma center).
0.5 gives half grid shift. Normally 0 or 0.5 is given.
Otherwise q-points symmetry search is not performed.
Default is None (no additional shift).
dtype='double', shape=(3, )
is_time_reversal: bool, optional
Time reversal symmetry is considered in symmetry search. By this,
inversion symmetry is always included. Default is True.
is_mesh_symmetry: bool, optional
Wheather symmetry search is done or not. Default is True
with_eigenvectors: bool, optional
Eigenvectors are stored by setting True. Default False.
with_group_velocities : bool, optional
Group velocities are calculated by setting True. Default is
False.
is_gamma_center: bool, default False
Uniform mesh grids are generated centring at Gamma point but not
the Monkhorst-Pack scheme. When type(mesh) is float, this parameter
setting is ignored and it is forced to set is_gamma_center=True.
use_iter_mesh: bool
Use IterMesh instead of Mesh class not to store phonon properties
in its instance to save memory consumption. This is used with
ThermalDisplacements and ThermalDisplacementMatrices.
Default is False.
"""
if self._dynamical_matrix is None:
msg = "Dynamical matrix has not yet built."
raise RuntimeError(msg)
_mesh = np.array(mesh)
mesh_nums = None
if _mesh.shape:
if _mesh.shape == (3,):
mesh_nums = mesh
_is_gamma_center = is_gamma_center
else:
if self._primitive_symmetry is not None:
rots = self._primitive_symmetry.get_pointgroup_operations()
mesh_nums = length2mesh(mesh,
self._primitive.get_cell(),
rotations=rots)
else:
mesh_nums = length2mesh(mesh, self._primitive.get_cell())
_is_gamma_center = True
if mesh_nums is None:
msg = "mesh has inappropriate type."
raise TypeError(msg)
if with_group_velocities:
if self._group_velocity is None:
self._set_group_velocity()
group_velocity = self._group_velocity
else:
group_velocity = None
if use_iter_mesh:
self._mesh = IterMesh(
self._dynamical_matrix,
mesh,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=with_eigenvectors,
is_gamma_center=is_gamma_center,
rotations=self._primitive_symmetry.get_pointgroup_operations(),
factor=self._factor)
else:
self._mesh = Mesh(
self._dynamical_matrix,
mesh_nums,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=with_eigenvectors,
is_gamma_center=_is_gamma_center,
group_velocity=group_velocity,
rotations=self._primitive_symmetry.get_pointgroup_operations(),
factor=self._factor,
use_lapack_solver=self._use_lapack_solver) | [
"def",
"init_mesh",
"(",
"self",
",",
"mesh",
"=",
"100.0",
",",
"shift",
"=",
"None",
",",
"is_time_reversal",
"=",
"True",
",",
"is_mesh_symmetry",
"=",
"True",
",",
"with_eigenvectors",
"=",
"False",
",",
"with_group_velocities",
"=",
"False",
",",
"is_ga... | Initialize mesh sampling phonon calculation without starting to run.
Phonon calculation starts explicitly with calling Mesh.run() or
implicitly with accessing getters of Mesh instance, e.g.,
Mesh.frequencies.
Parameters
----------
mesh: array_like or float, optional
Mesh numbers along a, b, c axes when array_like object is given.
dtype='intc', shape=(3,)
When float value is given, uniform mesh is generated following
VASP convention by
N = max(1, nint(l * |a|^*))
where 'nint' is the function to return the nearest integer. In this
case, it is forced to set is_gamma_center=True.
Default value is 100.0.
shift: array_like, optional
Mesh shifts along a*, b*, c* axes with respect to neighboring grid
points from the original mesh (Monkhorst-Pack or Gamma center).
0.5 gives half grid shift. Normally 0 or 0.5 is given.
Otherwise q-points symmetry search is not performed.
Default is None (no additional shift).
dtype='double', shape=(3, )
is_time_reversal: bool, optional
Time reversal symmetry is considered in symmetry search. By this,
inversion symmetry is always included. Default is True.
is_mesh_symmetry: bool, optional
Wheather symmetry search is done or not. Default is True
with_eigenvectors: bool, optional
Eigenvectors are stored by setting True. Default False.
with_group_velocities : bool, optional
Group velocities are calculated by setting True. Default is
False.
is_gamma_center: bool, default False
Uniform mesh grids are generated centring at Gamma point but not
the Monkhorst-Pack scheme. When type(mesh) is float, this parameter
setting is ignored and it is forced to set is_gamma_center=True.
use_iter_mesh: bool
Use IterMesh instead of Mesh class not to store phonon properties
in its instance to save memory consumption. This is used with
ThermalDisplacements and ThermalDisplacementMatrices.
Default is False. | [
"Initialize",
"mesh",
"sampling",
"phonon",
"calculation",
"without",
"starting",
"to",
"run",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L974-L1082 | train | 222,386 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.run_mesh | def run_mesh(self,
mesh=100.0,
shift=None,
is_time_reversal=True,
is_mesh_symmetry=True,
with_eigenvectors=False,
with_group_velocities=False,
is_gamma_center=False):
"""Run mesh sampling phonon calculation.
See the parameter details in Phonopy.init_mesh().
"""
self.init_mesh(mesh=mesh,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=with_eigenvectors,
with_group_velocities=with_group_velocities,
is_gamma_center=is_gamma_center)
self._mesh.run() | python | def run_mesh(self,
mesh=100.0,
shift=None,
is_time_reversal=True,
is_mesh_symmetry=True,
with_eigenvectors=False,
with_group_velocities=False,
is_gamma_center=False):
"""Run mesh sampling phonon calculation.
See the parameter details in Phonopy.init_mesh().
"""
self.init_mesh(mesh=mesh,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=with_eigenvectors,
with_group_velocities=with_group_velocities,
is_gamma_center=is_gamma_center)
self._mesh.run() | [
"def",
"run_mesh",
"(",
"self",
",",
"mesh",
"=",
"100.0",
",",
"shift",
"=",
"None",
",",
"is_time_reversal",
"=",
"True",
",",
"is_mesh_symmetry",
"=",
"True",
",",
"with_eigenvectors",
"=",
"False",
",",
"with_group_velocities",
"=",
"False",
",",
"is_gam... | Run mesh sampling phonon calculation.
See the parameter details in Phonopy.init_mesh(). | [
"Run",
"mesh",
"sampling",
"phonon",
"calculation",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1084-L1105 | train | 222,387 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.set_mesh | def set_mesh(self,
mesh,
shift=None,
is_time_reversal=True,
is_mesh_symmetry=True,
is_eigenvectors=False,
is_gamma_center=False,
run_immediately=True):
"""Phonon calculations on sampling mesh grids
Parameters
----------
mesh: array_like
Mesh numbers along a, b, c axes.
dtype='intc'
shape=(3,)
shift: array_like, optional, default None (no shift)
Mesh shifts along a*, b*, c* axes with respect to neighboring grid
points from the original mesh (Monkhorst-Pack or Gamma center).
0.5 gives half grid shift. Normally 0 or 0.5 is given.
Otherwise q-points symmetry search is not performed.
dtype='double'
shape=(3, )
is_time_reversal: bool, optional, default True
Time reversal symmetry is considered in symmetry search. By this,
inversion symmetry is always included.
is_mesh_symmetry: bool, optional, default True
Wheather symmetry search is done or not.
is_eigenvectors: bool, optional, default False
Eigenvectors are stored by setting True.
is_gamma_center: bool, default False
Uniform mesh grids are generated centring at Gamma point but not
the Monkhorst-Pack scheme.
run_immediately: bool, default True
With True, phonon calculations are performed immediately, which is
usual usage.
"""
warnings.warn("Phonopy.set_mesh is deprecated. "
"Use Phonopy.run_mesh.", DeprecationWarning)
if self._group_velocity is None:
with_group_velocities = False
else:
with_group_velocities = True
if run_immediately:
self.run_mesh(mesh,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=is_eigenvectors,
with_group_velocities=with_group_velocities,
is_gamma_center=is_gamma_center)
else:
self.init_mesh(mesh,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=is_eigenvectors,
with_group_velocities=with_group_velocities,
is_gamma_center=is_gamma_center) | python | def set_mesh(self,
mesh,
shift=None,
is_time_reversal=True,
is_mesh_symmetry=True,
is_eigenvectors=False,
is_gamma_center=False,
run_immediately=True):
"""Phonon calculations on sampling mesh grids
Parameters
----------
mesh: array_like
Mesh numbers along a, b, c axes.
dtype='intc'
shape=(3,)
shift: array_like, optional, default None (no shift)
Mesh shifts along a*, b*, c* axes with respect to neighboring grid
points from the original mesh (Monkhorst-Pack or Gamma center).
0.5 gives half grid shift. Normally 0 or 0.5 is given.
Otherwise q-points symmetry search is not performed.
dtype='double'
shape=(3, )
is_time_reversal: bool, optional, default True
Time reversal symmetry is considered in symmetry search. By this,
inversion symmetry is always included.
is_mesh_symmetry: bool, optional, default True
Wheather symmetry search is done or not.
is_eigenvectors: bool, optional, default False
Eigenvectors are stored by setting True.
is_gamma_center: bool, default False
Uniform mesh grids are generated centring at Gamma point but not
the Monkhorst-Pack scheme.
run_immediately: bool, default True
With True, phonon calculations are performed immediately, which is
usual usage.
"""
warnings.warn("Phonopy.set_mesh is deprecated. "
"Use Phonopy.run_mesh.", DeprecationWarning)
if self._group_velocity is None:
with_group_velocities = False
else:
with_group_velocities = True
if run_immediately:
self.run_mesh(mesh,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=is_eigenvectors,
with_group_velocities=with_group_velocities,
is_gamma_center=is_gamma_center)
else:
self.init_mesh(mesh,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=is_eigenvectors,
with_group_velocities=with_group_velocities,
is_gamma_center=is_gamma_center) | [
"def",
"set_mesh",
"(",
"self",
",",
"mesh",
",",
"shift",
"=",
"None",
",",
"is_time_reversal",
"=",
"True",
",",
"is_mesh_symmetry",
"=",
"True",
",",
"is_eigenvectors",
"=",
"False",
",",
"is_gamma_center",
"=",
"False",
",",
"run_immediately",
"=",
"True... | Phonon calculations on sampling mesh grids
Parameters
----------
mesh: array_like
Mesh numbers along a, b, c axes.
dtype='intc'
shape=(3,)
shift: array_like, optional, default None (no shift)
Mesh shifts along a*, b*, c* axes with respect to neighboring grid
points from the original mesh (Monkhorst-Pack or Gamma center).
0.5 gives half grid shift. Normally 0 or 0.5 is given.
Otherwise q-points symmetry search is not performed.
dtype='double'
shape=(3, )
is_time_reversal: bool, optional, default True
Time reversal symmetry is considered in symmetry search. By this,
inversion symmetry is always included.
is_mesh_symmetry: bool, optional, default True
Wheather symmetry search is done or not.
is_eigenvectors: bool, optional, default False
Eigenvectors are stored by setting True.
is_gamma_center: bool, default False
Uniform mesh grids are generated centring at Gamma point but not
the Monkhorst-Pack scheme.
run_immediately: bool, default True
With True, phonon calculations are performed immediately, which is
usual usage. | [
"Phonon",
"calculations",
"on",
"sampling",
"mesh",
"grids"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1107-L1168 | train | 222,388 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.get_mesh_dict | def get_mesh_dict(self):
"""Returns calculated mesh sampling phonons
Returns
-------
dict
keys: qpoints, weights, frequencies, eigenvectors, and
group_velocities
Each value for the corresponding key is explained as below.
qpoints: ndarray
q-points in reduced coordinates of reciprocal lattice
dtype='double'
shape=(ir-grid points, 3)
weights: ndarray
Geometric q-point weights. Its sum is the number of grid
points.
dtype='intc'
shape=(ir-grid points,)
frequencies: ndarray
Phonon frequencies at ir-grid points. Imaginary frequenies are
represented by negative real numbers.
dtype='double'
shape=(ir-grid points, bands)
eigenvectors: ndarray
Phonon eigenvectors at ir-grid points. See the data structure
at np.linalg.eigh.
dtype='complex'
shape=(ir-grid points, bands, bands)
group_velocities: ndarray
Phonon group velocities at ir-grid points.
dtype='double'
shape=(ir-grid points, bands, 3)
"""
if self._mesh is None:
msg = ("run_mesh has to be done.")
raise RuntimeError(msg)
retdict = {'qpoints': self._mesh.qpoints,
'weights': self._mesh.weights,
'frequencies': self._mesh.frequencies,
'eigenvectors': self._mesh.eigenvectors,
'group_velocities': self._mesh.group_velocities}
return retdict | python | def get_mesh_dict(self):
"""Returns calculated mesh sampling phonons
Returns
-------
dict
keys: qpoints, weights, frequencies, eigenvectors, and
group_velocities
Each value for the corresponding key is explained as below.
qpoints: ndarray
q-points in reduced coordinates of reciprocal lattice
dtype='double'
shape=(ir-grid points, 3)
weights: ndarray
Geometric q-point weights. Its sum is the number of grid
points.
dtype='intc'
shape=(ir-grid points,)
frequencies: ndarray
Phonon frequencies at ir-grid points. Imaginary frequenies are
represented by negative real numbers.
dtype='double'
shape=(ir-grid points, bands)
eigenvectors: ndarray
Phonon eigenvectors at ir-grid points. See the data structure
at np.linalg.eigh.
dtype='complex'
shape=(ir-grid points, bands, bands)
group_velocities: ndarray
Phonon group velocities at ir-grid points.
dtype='double'
shape=(ir-grid points, bands, 3)
"""
if self._mesh is None:
msg = ("run_mesh has to be done.")
raise RuntimeError(msg)
retdict = {'qpoints': self._mesh.qpoints,
'weights': self._mesh.weights,
'frequencies': self._mesh.frequencies,
'eigenvectors': self._mesh.eigenvectors,
'group_velocities': self._mesh.group_velocities}
return retdict | [
"def",
"get_mesh_dict",
"(",
"self",
")",
":",
"if",
"self",
".",
"_mesh",
"is",
"None",
":",
"msg",
"=",
"(",
"\"run_mesh has to be done.\"",
")",
"raise",
"RuntimeError",
"(",
"msg",
")",
"retdict",
"=",
"{",
"'qpoints'",
":",
"self",
".",
"_mesh",
"."... | Returns calculated mesh sampling phonons
Returns
-------
dict
keys: qpoints, weights, frequencies, eigenvectors, and
group_velocities
Each value for the corresponding key is explained as below.
qpoints: ndarray
q-points in reduced coordinates of reciprocal lattice
dtype='double'
shape=(ir-grid points, 3)
weights: ndarray
Geometric q-point weights. Its sum is the number of grid
points.
dtype='intc'
shape=(ir-grid points,)
frequencies: ndarray
Phonon frequencies at ir-grid points. Imaginary frequenies are
represented by negative real numbers.
dtype='double'
shape=(ir-grid points, bands)
eigenvectors: ndarray
Phonon eigenvectors at ir-grid points. See the data structure
at np.linalg.eigh.
dtype='complex'
shape=(ir-grid points, bands, bands)
group_velocities: ndarray
Phonon group velocities at ir-grid points.
dtype='double'
shape=(ir-grid points, bands, 3) | [
"Returns",
"calculated",
"mesh",
"sampling",
"phonons"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1170-L1216 | train | 222,389 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.set_iter_mesh | def set_iter_mesh(self,
mesh,
shift=None,
is_time_reversal=True,
is_mesh_symmetry=True,
is_eigenvectors=False,
is_gamma_center=False):
"""Create an IterMesh instancer
Attributes
----------
See set_mesh method.
"""
warnings.warn("Phonopy.set_iter_mesh is deprecated. "
"Use Phonopy.run_mesh with use_iter_mesh=True.",
DeprecationWarning)
self.run_mesh(mesh=mesh,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=is_eigenvectors,
is_gamma_center=is_gamma_center,
use_iter_mesh=True) | python | def set_iter_mesh(self,
mesh,
shift=None,
is_time_reversal=True,
is_mesh_symmetry=True,
is_eigenvectors=False,
is_gamma_center=False):
"""Create an IterMesh instancer
Attributes
----------
See set_mesh method.
"""
warnings.warn("Phonopy.set_iter_mesh is deprecated. "
"Use Phonopy.run_mesh with use_iter_mesh=True.",
DeprecationWarning)
self.run_mesh(mesh=mesh,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=is_eigenvectors,
is_gamma_center=is_gamma_center,
use_iter_mesh=True) | [
"def",
"set_iter_mesh",
"(",
"self",
",",
"mesh",
",",
"shift",
"=",
"None",
",",
"is_time_reversal",
"=",
"True",
",",
"is_mesh_symmetry",
"=",
"True",
",",
"is_eigenvectors",
"=",
"False",
",",
"is_gamma_center",
"=",
"False",
")",
":",
"warnings",
".",
... | Create an IterMesh instancer
Attributes
----------
See set_mesh method. | [
"Create",
"an",
"IterMesh",
"instancer"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1252-L1277 | train | 222,390 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.run_qpoints | def run_qpoints(self,
q_points,
with_eigenvectors=False,
with_group_velocities=False,
with_dynamical_matrices=False,
nac_q_direction=None):
"""Phonon calculations on q-points.
Parameters
----------
q_points: array_like or float, optional
q-points in reduced coordinates.
dtype='double', shape=(q-points, 3)
with_eigenvectors: bool, optional
Eigenvectors are stored by setting True. Default False.
with_group_velocities : bool, optional
Group velocities are calculated by setting True. Default is False.
with_dynamical_matrices : bool, optional
Calculated dynamical matrices are stored by setting True.
Default is False.
nac_q_direction : array_like
q=(0,0,0) is replaced by q=epsilon * nac_q_direction where epsilon
is infinitsimal for non-analytical term correction. This is used,
e.g., to observe LO-TO splitting,
"""
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
if with_group_velocities:
if self._group_velocity is None:
self._set_group_velocity()
group_velocity = self._group_velocity
else:
group_velocity = None
self._qpoints = QpointsPhonon(
np.reshape(q_points, (-1, 3)),
self._dynamical_matrix,
nac_q_direction=nac_q_direction,
with_eigenvectors=with_eigenvectors,
group_velocity=group_velocity,
with_dynamical_matrices=with_dynamical_matrices,
factor=self._factor) | python | def run_qpoints(self,
q_points,
with_eigenvectors=False,
with_group_velocities=False,
with_dynamical_matrices=False,
nac_q_direction=None):
"""Phonon calculations on q-points.
Parameters
----------
q_points: array_like or float, optional
q-points in reduced coordinates.
dtype='double', shape=(q-points, 3)
with_eigenvectors: bool, optional
Eigenvectors are stored by setting True. Default False.
with_group_velocities : bool, optional
Group velocities are calculated by setting True. Default is False.
with_dynamical_matrices : bool, optional
Calculated dynamical matrices are stored by setting True.
Default is False.
nac_q_direction : array_like
q=(0,0,0) is replaced by q=epsilon * nac_q_direction where epsilon
is infinitsimal for non-analytical term correction. This is used,
e.g., to observe LO-TO splitting,
"""
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
if with_group_velocities:
if self._group_velocity is None:
self._set_group_velocity()
group_velocity = self._group_velocity
else:
group_velocity = None
self._qpoints = QpointsPhonon(
np.reshape(q_points, (-1, 3)),
self._dynamical_matrix,
nac_q_direction=nac_q_direction,
with_eigenvectors=with_eigenvectors,
group_velocity=group_velocity,
with_dynamical_matrices=with_dynamical_matrices,
factor=self._factor) | [
"def",
"run_qpoints",
"(",
"self",
",",
"q_points",
",",
"with_eigenvectors",
"=",
"False",
",",
"with_group_velocities",
"=",
"False",
",",
"with_dynamical_matrices",
"=",
"False",
",",
"nac_q_direction",
"=",
"None",
")",
":",
"if",
"self",
".",
"_dynamical_ma... | Phonon calculations on q-points.
Parameters
----------
q_points: array_like or float, optional
q-points in reduced coordinates.
dtype='double', shape=(q-points, 3)
with_eigenvectors: bool, optional
Eigenvectors are stored by setting True. Default False.
with_group_velocities : bool, optional
Group velocities are calculated by setting True. Default is False.
with_dynamical_matrices : bool, optional
Calculated dynamical matrices are stored by setting True.
Default is False.
nac_q_direction : array_like
q=(0,0,0) is replaced by q=epsilon * nac_q_direction where epsilon
is infinitsimal for non-analytical term correction. This is used,
e.g., to observe LO-TO splitting, | [
"Phonon",
"calculations",
"on",
"q",
"-",
"points",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1349-L1394 | train | 222,391 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.run_total_dos | def run_total_dos(self,
sigma=None,
freq_min=None,
freq_max=None,
freq_pitch=None,
use_tetrahedron_method=True):
"""Calculate total DOS from phonons on sampling mesh.
Parameters
----------
sigma : float, optional
Smearing width for smearing method. Default is None
freq_min, freq_max, freq_pitch : float, optional
Minimum and maximum frequencies in which range DOS is computed
with the specified interval (freq_pitch).
Defaults are None and they are automatically determined.
use_tetrahedron_method : float, optional
Use tetrahedron method when this is True. When sigma is set,
smearing method is used.
"""
if self._mesh is None:
msg = "run_mesh has to be done before DOS calculation."
raise RuntimeError(msg)
total_dos = TotalDos(self._mesh,
sigma=sigma,
use_tetrahedron_method=use_tetrahedron_method)
total_dos.set_draw_area(freq_min, freq_max, freq_pitch)
total_dos.run()
self._total_dos = total_dos | python | def run_total_dos(self,
sigma=None,
freq_min=None,
freq_max=None,
freq_pitch=None,
use_tetrahedron_method=True):
"""Calculate total DOS from phonons on sampling mesh.
Parameters
----------
sigma : float, optional
Smearing width for smearing method. Default is None
freq_min, freq_max, freq_pitch : float, optional
Minimum and maximum frequencies in which range DOS is computed
with the specified interval (freq_pitch).
Defaults are None and they are automatically determined.
use_tetrahedron_method : float, optional
Use tetrahedron method when this is True. When sigma is set,
smearing method is used.
"""
if self._mesh is None:
msg = "run_mesh has to be done before DOS calculation."
raise RuntimeError(msg)
total_dos = TotalDos(self._mesh,
sigma=sigma,
use_tetrahedron_method=use_tetrahedron_method)
total_dos.set_draw_area(freq_min, freq_max, freq_pitch)
total_dos.run()
self._total_dos = total_dos | [
"def",
"run_total_dos",
"(",
"self",
",",
"sigma",
"=",
"None",
",",
"freq_min",
"=",
"None",
",",
"freq_max",
"=",
"None",
",",
"freq_pitch",
"=",
"None",
",",
"use_tetrahedron_method",
"=",
"True",
")",
":",
"if",
"self",
".",
"_mesh",
"is",
"None",
... | Calculate total DOS from phonons on sampling mesh.
Parameters
----------
sigma : float, optional
Smearing width for smearing method. Default is None
freq_min, freq_max, freq_pitch : float, optional
Minimum and maximum frequencies in which range DOS is computed
with the specified interval (freq_pitch).
Defaults are None and they are automatically determined.
use_tetrahedron_method : float, optional
Use tetrahedron method when this is True. When sigma is set,
smearing method is used. | [
"Calculate",
"total",
"DOS",
"from",
"phonons",
"on",
"sampling",
"mesh",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1436-L1466 | train | 222,392 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.get_total_DOS | def get_total_DOS(self):
"""Return frequency points and total DOS as a tuple.
Returns
-------
A tuple with (frequency_points, total_dos).
frequency_points: ndarray
shape=(frequency_sampling_points, ), dtype='double'
total_dos:
shape=(frequency_sampling_points, ), dtype='double'
"""
warnings.warn("Phonopy.get_total_DOS is deprecated. "
"Use Phonopy.get_total_dos_dict.", DeprecationWarning)
dos = self.get_total_dos_dict()
return dos['frequency_points'], dos['total_dos'] | python | def get_total_DOS(self):
"""Return frequency points and total DOS as a tuple.
Returns
-------
A tuple with (frequency_points, total_dos).
frequency_points: ndarray
shape=(frequency_sampling_points, ), dtype='double'
total_dos:
shape=(frequency_sampling_points, ), dtype='double'
"""
warnings.warn("Phonopy.get_total_DOS is deprecated. "
"Use Phonopy.get_total_dos_dict.", DeprecationWarning)
dos = self.get_total_dos_dict()
return dos['frequency_points'], dos['total_dos'] | [
"def",
"get_total_DOS",
"(",
"self",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Phonopy.get_total_DOS is deprecated. \"",
"\"Use Phonopy.get_total_dos_dict.\"",
",",
"DeprecationWarning",
")",
"dos",
"=",
"self",
".",
"get_total_dos_dict",
"(",
")",
"return",
"dos",
"... | Return frequency points and total DOS as a tuple.
Returns
-------
A tuple with (frequency_points, total_dos).
frequency_points: ndarray
shape=(frequency_sampling_points, ), dtype='double'
total_dos:
shape=(frequency_sampling_points, ), dtype='double' | [
"Return",
"frequency",
"points",
"and",
"total",
"DOS",
"as",
"a",
"tuple",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1519-L1538 | train | 222,393 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.run_projected_dos | def run_projected_dos(self,
sigma=None,
freq_min=None,
freq_max=None,
freq_pitch=None,
use_tetrahedron_method=True,
direction=None,
xyz_projection=False):
"""Calculate projected DOS from phonons on sampling mesh.
Parameters
----------
sigma : float, optional
Smearing width for smearing method. Default is None
freq_min, freq_max, freq_pitch : float, optional
Minimum and maximum frequencies in which range DOS is computed
with the specified interval (freq_pitch).
Defaults are None and they are automatically determined.
use_tetrahedron_method : float, optional
Use tetrahedron method when this is True. When sigma is set,
smearing method is used.
direction : array_like, optional
Specific projection direction. This is specified three values
along basis vectors or the primitive cell. Default is None,
i.e., no projection.
xyz_projection : bool, optional
This determines whether projected along Cartesian directions or
not. Default is False, i.e., no projection.
"""
self._pdos = None
if self._mesh is None:
msg = "run_mesh has to be done before PDOS calculation."
raise RuntimeError(msg)
if not self._mesh.with_eigenvectors:
msg = "run_mesh has to be called with with_eigenvectors=True."
raise RuntimeError(msg)
if np.prod(self._mesh.mesh_numbers) != len(self._mesh.ir_grid_points):
msg = "run_mesh has to be done with is_mesh_symmetry=False."
raise RuntimeError(msg)
if direction is not None:
direction_cart = np.dot(direction, self._primitive.get_cell())
else:
direction_cart = None
self._pdos = PartialDos(self._mesh,
sigma=sigma,
use_tetrahedron_method=use_tetrahedron_method,
direction=direction_cart,
xyz_projection=xyz_projection)
self._pdos.set_draw_area(freq_min, freq_max, freq_pitch)
self._pdos.run() | python | def run_projected_dos(self,
sigma=None,
freq_min=None,
freq_max=None,
freq_pitch=None,
use_tetrahedron_method=True,
direction=None,
xyz_projection=False):
"""Calculate projected DOS from phonons on sampling mesh.
Parameters
----------
sigma : float, optional
Smearing width for smearing method. Default is None
freq_min, freq_max, freq_pitch : float, optional
Minimum and maximum frequencies in which range DOS is computed
with the specified interval (freq_pitch).
Defaults are None and they are automatically determined.
use_tetrahedron_method : float, optional
Use tetrahedron method when this is True. When sigma is set,
smearing method is used.
direction : array_like, optional
Specific projection direction. This is specified three values
along basis vectors or the primitive cell. Default is None,
i.e., no projection.
xyz_projection : bool, optional
This determines whether projected along Cartesian directions or
not. Default is False, i.e., no projection.
"""
self._pdos = None
if self._mesh is None:
msg = "run_mesh has to be done before PDOS calculation."
raise RuntimeError(msg)
if not self._mesh.with_eigenvectors:
msg = "run_mesh has to be called with with_eigenvectors=True."
raise RuntimeError(msg)
if np.prod(self._mesh.mesh_numbers) != len(self._mesh.ir_grid_points):
msg = "run_mesh has to be done with is_mesh_symmetry=False."
raise RuntimeError(msg)
if direction is not None:
direction_cart = np.dot(direction, self._primitive.get_cell())
else:
direction_cart = None
self._pdos = PartialDos(self._mesh,
sigma=sigma,
use_tetrahedron_method=use_tetrahedron_method,
direction=direction_cart,
xyz_projection=xyz_projection)
self._pdos.set_draw_area(freq_min, freq_max, freq_pitch)
self._pdos.run() | [
"def",
"run_projected_dos",
"(",
"self",
",",
"sigma",
"=",
"None",
",",
"freq_min",
"=",
"None",
",",
"freq_max",
"=",
"None",
",",
"freq_pitch",
"=",
"None",
",",
"use_tetrahedron_method",
"=",
"True",
",",
"direction",
"=",
"None",
",",
"xyz_projection",
... | Calculate projected DOS from phonons on sampling mesh.
Parameters
----------
sigma : float, optional
Smearing width for smearing method. Default is None
freq_min, freq_max, freq_pitch : float, optional
Minimum and maximum frequencies in which range DOS is computed
with the specified interval (freq_pitch).
Defaults are None and they are automatically determined.
use_tetrahedron_method : float, optional
Use tetrahedron method when this is True. When sigma is set,
smearing method is used.
direction : array_like, optional
Specific projection direction. This is specified three values
along basis vectors or the primitive cell. Default is None,
i.e., no projection.
xyz_projection : bool, optional
This determines whether projected along Cartesian directions or
not. Default is False, i.e., no projection. | [
"Calculate",
"projected",
"DOS",
"from",
"phonons",
"on",
"sampling",
"mesh",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1578-L1633 | train | 222,394 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.get_partial_DOS | def get_partial_DOS(self):
"""Return frequency points and partial DOS as a tuple.
Projection is done to atoms and may be also done along directions
depending on the parameters at run_partial_dos.
Returns
-------
A tuple with (frequency_points, partial_dos).
frequency_points: ndarray
shape=(frequency_sampling_points, ), dtype='double'
partial_dos:
shape=(frequency_sampling_points, projections), dtype='double'
"""
warnings.warn("Phonopy.get_partial_DOS is deprecated. "
"Use Phonopy.get_projected_dos_dict.",
DeprecationWarning)
pdos = self.get_projected_dos_dict()
return pdos['frequency_points'], pdos['projected_dos'] | python | def get_partial_DOS(self):
"""Return frequency points and partial DOS as a tuple.
Projection is done to atoms and may be also done along directions
depending on the parameters at run_partial_dos.
Returns
-------
A tuple with (frequency_points, partial_dos).
frequency_points: ndarray
shape=(frequency_sampling_points, ), dtype='double'
partial_dos:
shape=(frequency_sampling_points, projections), dtype='double'
"""
warnings.warn("Phonopy.get_partial_DOS is deprecated. "
"Use Phonopy.get_projected_dos_dict.",
DeprecationWarning)
pdos = self.get_projected_dos_dict()
return pdos['frequency_points'], pdos['projected_dos'] | [
"def",
"get_partial_DOS",
"(",
"self",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Phonopy.get_partial_DOS is deprecated. \"",
"\"Use Phonopy.get_projected_dos_dict.\"",
",",
"DeprecationWarning",
")",
"pdos",
"=",
"self",
".",
"get_projected_dos_dict",
"(",
")",
"return",... | Return frequency points and partial DOS as a tuple.
Projection is done to atoms and may be also done along directions
depending on the parameters at run_partial_dos.
Returns
-------
A tuple with (frequency_points, partial_dos).
frequency_points: ndarray
shape=(frequency_sampling_points, ), dtype='double'
partial_dos:
shape=(frequency_sampling_points, projections), dtype='double' | [
"Return",
"frequency",
"points",
"and",
"partial",
"DOS",
"as",
"a",
"tuple",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1695-L1717 | train | 222,395 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.plot_projected_dos | def plot_projected_dos(self, pdos_indices=None, legend=None):
"""Plot projected DOS
Parameters
----------
pdos_indices : list of list, optional
Sets of indices of atoms whose projected DOS are summed over.
The indices start with 0. An example is as follwos:
pdos_indices=[[0, 1], [2, 3, 4, 5]]
Default is None, which means
pdos_indices=[[i] for i in range(natom)]
legend : list of instances such as str or int, optional
The str(instance) are shown in legend.
It has to be len(pdos_indices)==len(legend). Default is None.
When None, legend is not shown.
"""
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.xaxis.set_ticks_position('both')
ax.yaxis.set_ticks_position('both')
ax.xaxis.set_tick_params(which='both', direction='in')
ax.yaxis.set_tick_params(which='both', direction='in')
self._pdos.plot(ax,
indices=pdos_indices,
legend=legend,
draw_grid=False)
ax.set_ylim((0, None))
return plt | python | def plot_projected_dos(self, pdos_indices=None, legend=None):
"""Plot projected DOS
Parameters
----------
pdos_indices : list of list, optional
Sets of indices of atoms whose projected DOS are summed over.
The indices start with 0. An example is as follwos:
pdos_indices=[[0, 1], [2, 3, 4, 5]]
Default is None, which means
pdos_indices=[[i] for i in range(natom)]
legend : list of instances such as str or int, optional
The str(instance) are shown in legend.
It has to be len(pdos_indices)==len(legend). Default is None.
When None, legend is not shown.
"""
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.xaxis.set_ticks_position('both')
ax.yaxis.set_ticks_position('both')
ax.xaxis.set_tick_params(which='both', direction='in')
ax.yaxis.set_tick_params(which='both', direction='in')
self._pdos.plot(ax,
indices=pdos_indices,
legend=legend,
draw_grid=False)
ax.set_ylim((0, None))
return plt | [
"def",
"plot_projected_dos",
"(",
"self",
",",
"pdos_indices",
"=",
"None",
",",
"legend",
"=",
"None",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
")",
"ax",
".",
"xaxis",
".",
"s... | Plot projected DOS
Parameters
----------
pdos_indices : list of list, optional
Sets of indices of atoms whose projected DOS are summed over.
The indices start with 0. An example is as follwos:
pdos_indices=[[0, 1], [2, 3, 4, 5]]
Default is None, which means
pdos_indices=[[i] for i in range(natom)]
legend : list of instances such as str or int, optional
The str(instance) are shown in legend.
It has to be len(pdos_indices)==len(legend). Default is None.
When None, legend is not shown. | [
"Plot",
"projected",
"DOS"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1727-L1760 | train | 222,396 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.run_thermal_properties | def run_thermal_properties(self,
t_min=0,
t_max=1000,
t_step=10,
temperatures=None,
is_projection=False,
band_indices=None,
cutoff_frequency=None,
pretend_real=False):
"""Calculate thermal properties at constant volume
Parameters
----------
t_min, t_max, t_step : float, optional
Minimum and maximum temperatures and the interval in this
temperature range. Default values are 0, 1000, and 10.
temperatures : array_like, optional
Temperature points where thermal properties are calculated.
When this is set, t_min, t_max, and t_step are ignored.
"""
if self._mesh is None:
msg = ("run_mesh has to be done before"
"run_thermal_properties.")
raise RuntimeError(msg)
tp = ThermalProperties(self._mesh,
is_projection=is_projection,
band_indices=band_indices,
cutoff_frequency=cutoff_frequency,
pretend_real=pretend_real)
if temperatures is None:
tp.set_temperature_range(t_step=t_step,
t_max=t_max,
t_min=t_min)
else:
tp.set_temperatures(temperatures)
tp.run()
self._thermal_properties = tp | python | def run_thermal_properties(self,
t_min=0,
t_max=1000,
t_step=10,
temperatures=None,
is_projection=False,
band_indices=None,
cutoff_frequency=None,
pretend_real=False):
"""Calculate thermal properties at constant volume
Parameters
----------
t_min, t_max, t_step : float, optional
Minimum and maximum temperatures and the interval in this
temperature range. Default values are 0, 1000, and 10.
temperatures : array_like, optional
Temperature points where thermal properties are calculated.
When this is set, t_min, t_max, and t_step are ignored.
"""
if self._mesh is None:
msg = ("run_mesh has to be done before"
"run_thermal_properties.")
raise RuntimeError(msg)
tp = ThermalProperties(self._mesh,
is_projection=is_projection,
band_indices=band_indices,
cutoff_frequency=cutoff_frequency,
pretend_real=pretend_real)
if temperatures is None:
tp.set_temperature_range(t_step=t_step,
t_max=t_max,
t_min=t_min)
else:
tp.set_temperatures(temperatures)
tp.run()
self._thermal_properties = tp | [
"def",
"run_thermal_properties",
"(",
"self",
",",
"t_min",
"=",
"0",
",",
"t_max",
"=",
"1000",
",",
"t_step",
"=",
"10",
",",
"temperatures",
"=",
"None",
",",
"is_projection",
"=",
"False",
",",
"band_indices",
"=",
"None",
",",
"cutoff_frequency",
"=",... | Calculate thermal properties at constant volume
Parameters
----------
t_min, t_max, t_step : float, optional
Minimum and maximum temperatures and the interval in this
temperature range. Default values are 0, 1000, and 10.
temperatures : array_like, optional
Temperature points where thermal properties are calculated.
When this is set, t_min, t_max, and t_step are ignored. | [
"Calculate",
"thermal",
"properties",
"at",
"constant",
"volume"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1772-L1810 | train | 222,397 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.get_thermal_properties | def get_thermal_properties(self):
"""Return thermal properties
Returns
-------
(temperatures, free energy, entropy, heat capacity)
"""
warnings.warn("Phonopy.get_thermal_properties is deprecated. "
"Use Phonopy.get_thermal_properties_dict.",
DeprecationWarning)
tp = self.get_thermal_properties_dict()
return (tp['temperatures'],
tp['free_energy'],
tp['entropy'],
tp['heat_capacity']) | python | def get_thermal_properties(self):
"""Return thermal properties
Returns
-------
(temperatures, free energy, entropy, heat capacity)
"""
warnings.warn("Phonopy.get_thermal_properties is deprecated. "
"Use Phonopy.get_thermal_properties_dict.",
DeprecationWarning)
tp = self.get_thermal_properties_dict()
return (tp['temperatures'],
tp['free_energy'],
tp['entropy'],
tp['heat_capacity']) | [
"def",
"get_thermal_properties",
"(",
"self",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Phonopy.get_thermal_properties is deprecated. \"",
"\"Use Phonopy.get_thermal_properties_dict.\"",
",",
"DeprecationWarning",
")",
"tp",
"=",
"self",
".",
"get_thermal_properties_dict",
"... | Return thermal properties
Returns
-------
(temperatures, free energy, entropy, heat capacity) | [
"Return",
"thermal",
"properties"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1856-L1872 | train | 222,398 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.run_thermal_displacements | def run_thermal_displacements(self,
t_min=0,
t_max=1000,
t_step=10,
temperatures=None,
direction=None,
freq_min=None,
freq_max=None):
"""Prepare thermal displacements calculation
Parameters
----------
t_min, t_max, t_step : float, optional
Minimum and maximum temperatures and the interval in this
temperature range. Default valuues are 0, 1000, and 10.
temperatures : array_like, optional
Temperature points where thermal properties are calculated.
When this is set, t_min, t_max, and t_step are ignored.
direction : array_like, optional
Projection direction in reduced coordinates. Default is None,
i.e., no projection.
dtype=float, shape=(3,)
freq_min, freq_max : float, optional
Phonon frequencies larger than freq_min and smaller than
freq_max are included. Default is None, i.e., all phonons.
"""
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
if self._mesh is None:
msg = ("run_mesh has to be done.")
raise RuntimeError(msg)
mesh_nums = self._mesh.mesh_numbers
ir_grid_points = self._mesh.ir_grid_points
if not self._mesh.with_eigenvectors:
msg = ("run_mesh has to be done with with_eigenvectors=True.")
raise RuntimeError(msg)
if np.prod(mesh_nums) != len(ir_grid_points):
msg = ("run_mesh has to be done with is_mesh_symmetry=False.")
raise RuntimeError(msg)
if direction is not None:
projection_direction = np.dot(direction,
self._primitive.get_cell())
td = ThermalDisplacements(
self._mesh,
projection_direction=projection_direction,
freq_min=freq_min,
freq_max=freq_max)
else:
td = ThermalDisplacements(self._mesh,
freq_min=freq_min,
freq_max=freq_max)
if temperatures is None:
td.set_temperature_range(t_min, t_max, t_step)
else:
td.set_temperatures(temperatures)
td.run()
self._thermal_displacements = td | python | def run_thermal_displacements(self,
t_min=0,
t_max=1000,
t_step=10,
temperatures=None,
direction=None,
freq_min=None,
freq_max=None):
"""Prepare thermal displacements calculation
Parameters
----------
t_min, t_max, t_step : float, optional
Minimum and maximum temperatures and the interval in this
temperature range. Default valuues are 0, 1000, and 10.
temperatures : array_like, optional
Temperature points where thermal properties are calculated.
When this is set, t_min, t_max, and t_step are ignored.
direction : array_like, optional
Projection direction in reduced coordinates. Default is None,
i.e., no projection.
dtype=float, shape=(3,)
freq_min, freq_max : float, optional
Phonon frequencies larger than freq_min and smaller than
freq_max are included. Default is None, i.e., all phonons.
"""
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
if self._mesh is None:
msg = ("run_mesh has to be done.")
raise RuntimeError(msg)
mesh_nums = self._mesh.mesh_numbers
ir_grid_points = self._mesh.ir_grid_points
if not self._mesh.with_eigenvectors:
msg = ("run_mesh has to be done with with_eigenvectors=True.")
raise RuntimeError(msg)
if np.prod(mesh_nums) != len(ir_grid_points):
msg = ("run_mesh has to be done with is_mesh_symmetry=False.")
raise RuntimeError(msg)
if direction is not None:
projection_direction = np.dot(direction,
self._primitive.get_cell())
td = ThermalDisplacements(
self._mesh,
projection_direction=projection_direction,
freq_min=freq_min,
freq_max=freq_max)
else:
td = ThermalDisplacements(self._mesh,
freq_min=freq_min,
freq_max=freq_max)
if temperatures is None:
td.set_temperature_range(t_min, t_max, t_step)
else:
td.set_temperatures(temperatures)
td.run()
self._thermal_displacements = td | [
"def",
"run_thermal_displacements",
"(",
"self",
",",
"t_min",
"=",
"0",
",",
"t_max",
"=",
"1000",
",",
"t_step",
"=",
"10",
",",
"temperatures",
"=",
"None",
",",
"direction",
"=",
"None",
",",
"freq_min",
"=",
"None",
",",
"freq_max",
"=",
"None",
"... | Prepare thermal displacements calculation
Parameters
----------
t_min, t_max, t_step : float, optional
Minimum and maximum temperatures and the interval in this
temperature range. Default valuues are 0, 1000, and 10.
temperatures : array_like, optional
Temperature points where thermal properties are calculated.
When this is set, t_min, t_max, and t_step are ignored.
direction : array_like, optional
Projection direction in reduced coordinates. Default is None,
i.e., no projection.
dtype=float, shape=(3,)
freq_min, freq_max : float, optional
Phonon frequencies larger than freq_min and smaller than
freq_max are included. Default is None, i.e., all phonons. | [
"Prepare",
"thermal",
"displacements",
"calculation"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1897-L1959 | train | 222,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.