id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
227,500 | 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 |
227,501 | 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 |
227,502 | 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 |
227,503 | 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 |
227,504 | 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 |
227,505 | 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 |
227,506 | 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 |
227,507 | 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",
"==",
"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"
] | 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 |
227,508 | 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 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",
"]",
")",
")"
] | 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 |
227,509 | 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",
"==",
"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'",
")"
] | 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 |
227,510 | 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",
",",
"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",
")"
] | 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 |
227,511 | 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\"",
")",
")",
"# 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",
")"
] | 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 |
227,512 | 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",
"(",
")",
"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"
] | 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 |
227,513 | 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",
":",
"return",
"spg",
".",
"delaunay_reduce",
"(",
"lattice",
",",
"eps",
"=",
"tolerance",
")"
] | 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 |
227,514 | 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",
"=",
"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"
] | 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 |
227,515 | 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_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'",
")"
] | 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 |
227,516 | 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 - 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",
")",
"]"
] | 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 |
227,517 | 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",
")",
",",
")",
",",
"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"
] | 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",
"large",
"structures",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L814-L858 |
227,518 | 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_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"
] | 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 |
227,519 | 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 |
227,520 | 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",
",",
"1",
"]",
"==",
"0",
":",
"self",
".",
"_second_finalize",
"(",
")",
"self",
".",
"_Ps",
"+=",
"self",
".",
"_L",
"self",
".",
"_L",
"=",
"[",
"]",
"return",
"True",
"else",
":",
"return",
"False"
] | 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 |
227,521 | 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",
".",
"_A",
"[",
"2",
",",
"1",
"]",
"!=",
"0",
":",
"self",
".",
"_zero_second_column",
"(",
")"
] | 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 |
227,522 | 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",
",",
"j",
"]",
"=",
"1",
"L",
"[",
"j",
",",
"i",
"]",
"=",
"1",
"self",
".",
"_L",
".",
"append",
"(",
"L",
".",
"copy",
"(",
")",
")",
"self",
".",
"_A",
"=",
"np",
".",
"dot",
"(",
"L",
",",
"self",
".",
"_A",
")"
] | 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 |
227,523 | 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",
"(",
")",
")",
"self",
".",
"_A",
"=",
"np",
".",
"dot",
"(",
"L",
",",
"self",
".",
"_A",
")"
] | 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 |
227,524 | 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",
"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"
] | 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 |
227,525 | 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_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"
] | 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 |
227,526 | 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",
"[",
"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",
"(",
")"
] | 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 |
227,527 | 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",
".",
"_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",
")"
] | Generate displacement dataset | [
"Generate",
"displacement",
"dataset"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L570-L586 |
227,528 | 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",
"(",
"msg",
")",
"self",
".",
"_dynamical_matrix",
".",
"set_dynamical_matrix",
"(",
"q",
")",
"return",
"self",
".",
"_dynamical_matrix",
".",
"get_dynamical_matrix",
"(",
")"
] | 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 |
227,529 | 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",
"(",
"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"
] | 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 |
227,530 | 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",
"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"
] | 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 |
227,531 | 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_plot",
"=",
"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",
")"
] | 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 |
227,532 | 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_gamma_center",
"=",
"False",
",",
"use_iter_mesh",
"=",
"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",
")"
] | 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 |
227,533 | 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_gamma_center",
"=",
"False",
")",
":",
"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",
"(",
")"
] | 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 |
227,534 | 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",
")",
":",
"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",
")"
] | 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 |
227,535 | 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",
".",
"qpoints",
",",
"'weights'",
":",
"self",
".",
"_mesh",
".",
"weights",
",",
"'frequencies'",
":",
"self",
".",
"_mesh",
".",
"frequencies",
",",
"'eigenvectors'",
":",
"self",
".",
"_mesh",
".",
"eigenvectors",
",",
"'group_velocities'",
":",
"self",
".",
"_mesh",
".",
"group_velocities",
"}",
"return",
"retdict"
] | 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 |
227,536 | 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",
".",
"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",
")"
] | 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 |
227,537 | 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_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",
")"
] | 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 |
227,538 | 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",
":",
"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"
] | 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 |
227,539 | 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",
"[",
"'frequency_points'",
"]",
",",
"dos",
"[",
"'total_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 |
227,540 | 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",
"=",
"False",
")",
":",
"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",
"(",
")"
] | 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 |
227,541 | 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",
"pdos",
"[",
"'frequency_points'",
"]",
",",
"pdos",
"[",
"'projected_dos'",
"]"
] | 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 |
227,542 | 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",
".",
"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"
] | 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 |
227,543 | 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",
"=",
"None",
",",
"pretend_real",
"=",
"False",
")",
":",
"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"
] | 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 |
227,544 | 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",
"(",
"tp",
"[",
"'temperatures'",
"]",
",",
"tp",
"[",
"'free_energy'",
"]",
",",
"tp",
"[",
"'entropy'",
"]",
",",
"tp",
"[",
"'heat_capacity'",
"]",
")"
] | 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 |
227,545 | 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",
")",
":",
"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"
] | 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 |
227,546 | atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.run_thermal_displacement_matrices | def run_thermal_displacement_matrices(self,
t_min=0,
t_max=1000,
t_step=10,
temperatures=None,
freq_min=None,
freq_max=None):
"""Prepare thermal displacement matrices
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.
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.
temperatures : array_like, optional
Temperature points where thermal properties are calculated.
When this is set, t_min, t_max, and t_step are ignored.
Default is None.
"""
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)
tdm = ThermalDisplacementMatrices(
self._mesh,
freq_min=freq_min,
freq_max=freq_max,
lattice=self._primitive.get_cell().T)
if temperatures is None:
tdm.set_temperature_range(t_min, t_max, t_step)
else:
tdm.set_temperatures(temperatures)
tdm.run()
self._thermal_displacement_matrices = tdm | python | def run_thermal_displacement_matrices(self,
t_min=0,
t_max=1000,
t_step=10,
temperatures=None,
freq_min=None,
freq_max=None):
"""Prepare thermal displacement matrices
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.
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.
temperatures : array_like, optional
Temperature points where thermal properties are calculated.
When this is set, t_min, t_max, and t_step are ignored.
Default is None.
"""
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)
tdm = ThermalDisplacementMatrices(
self._mesh,
freq_min=freq_min,
freq_max=freq_max,
lattice=self._primitive.get_cell().T)
if temperatures is None:
tdm.set_temperature_range(t_min, t_max, t_step)
else:
tdm.set_temperatures(temperatures)
tdm.run()
self._thermal_displacement_matrices = tdm | [
"def",
"run_thermal_displacement_matrices",
"(",
"self",
",",
"t_min",
"=",
"0",
",",
"t_max",
"=",
"1000",
",",
"t_step",
"=",
"10",
",",
"temperatures",
"=",
"None",
",",
"freq_min",
"=",
"None",
",",
"freq_max",
"=",
"None",
")",
":",
"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",
")",
"tdm",
"=",
"ThermalDisplacementMatrices",
"(",
"self",
".",
"_mesh",
",",
"freq_min",
"=",
"freq_min",
",",
"freq_max",
"=",
"freq_max",
",",
"lattice",
"=",
"self",
".",
"_primitive",
".",
"get_cell",
"(",
")",
".",
"T",
")",
"if",
"temperatures",
"is",
"None",
":",
"tdm",
".",
"set_temperature_range",
"(",
"t_min",
",",
"t_max",
",",
"t_step",
")",
"else",
":",
"tdm",
".",
"set_temperatures",
"(",
"temperatures",
")",
"tdm",
".",
"run",
"(",
")",
"self",
".",
"_thermal_displacement_matrices",
"=",
"tdm"
] | Prepare thermal displacement matrices
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.
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.
temperatures : array_like, optional
Temperature points where thermal properties are calculated.
When this is set, t_min, t_max, and t_step are ignored.
Default is None. | [
"Prepare",
"thermal",
"displacement",
"matrices"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L2016-L2066 |
227,547 | atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.set_modulations | def set_modulations(self,
dimension,
phonon_modes,
delta_q=None,
derivative_order=None,
nac_q_direction=None):
"""Generate atomic displacements of phonon modes.
The design of this feature is not very satisfactory, and thus API.
Therefore it should be reconsidered someday in the fugure.
Parameters
----------
dimension : array_like
Supercell dimension with respect to the primitive cell.
dtype='intc', shape=(3, ), (3, 3), (9, )
phonon_modes : list of phonon mode settings
Each element of the outer list gives one phonon mode information:
[q-point, band index (int), amplitude (float), phase (float)]
In each list of the phonon mode information, the first element is
a list that represents q-point in reduced coordinates. The second,
third, and fourth elements show the band index starting with 0,
amplitude, and phase factor, respectively.
"""
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._modulation = Modulation(self._dynamical_matrix,
dimension,
phonon_modes,
delta_q=delta_q,
derivative_order=derivative_order,
nac_q_direction=nac_q_direction,
factor=self._factor)
self._modulation.run() | python | def set_modulations(self,
dimension,
phonon_modes,
delta_q=None,
derivative_order=None,
nac_q_direction=None):
"""Generate atomic displacements of phonon modes.
The design of this feature is not very satisfactory, and thus API.
Therefore it should be reconsidered someday in the fugure.
Parameters
----------
dimension : array_like
Supercell dimension with respect to the primitive cell.
dtype='intc', shape=(3, ), (3, 3), (9, )
phonon_modes : list of phonon mode settings
Each element of the outer list gives one phonon mode information:
[q-point, band index (int), amplitude (float), phase (float)]
In each list of the phonon mode information, the first element is
a list that represents q-point in reduced coordinates. The second,
third, and fourth elements show the band index starting with 0,
amplitude, and phase factor, respectively.
"""
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._modulation = Modulation(self._dynamical_matrix,
dimension,
phonon_modes,
delta_q=delta_q,
derivative_order=derivative_order,
nac_q_direction=nac_q_direction,
factor=self._factor)
self._modulation.run() | [
"def",
"set_modulations",
"(",
"self",
",",
"dimension",
",",
"phonon_modes",
",",
"delta_q",
"=",
"None",
",",
"derivative_order",
"=",
"None",
",",
"nac_q_direction",
"=",
"None",
")",
":",
"if",
"self",
".",
"_dynamical_matrix",
"is",
"None",
":",
"msg",
"=",
"(",
"\"Dynamical matrix has not yet built.\"",
")",
"raise",
"RuntimeError",
"(",
"msg",
")",
"self",
".",
"_modulation",
"=",
"Modulation",
"(",
"self",
".",
"_dynamical_matrix",
",",
"dimension",
",",
"phonon_modes",
",",
"delta_q",
"=",
"delta_q",
",",
"derivative_order",
"=",
"derivative_order",
",",
"nac_q_direction",
"=",
"nac_q_direction",
",",
"factor",
"=",
"self",
".",
"_factor",
")",
"self",
".",
"_modulation",
".",
"run",
"(",
")"
] | Generate atomic displacements of phonon modes.
The design of this feature is not very satisfactory, and thus API.
Therefore it should be reconsidered someday in the fugure.
Parameters
----------
dimension : array_like
Supercell dimension with respect to the primitive cell.
dtype='intc', shape=(3, ), (3, 3), (9, )
phonon_modes : list of phonon mode settings
Each element of the outer list gives one phonon mode information:
[q-point, band index (int), amplitude (float), phase (float)]
In each list of the phonon mode information, the first element is
a list that represents q-point in reduced coordinates. The second,
third, and fourth elements show the band index starting with 0,
amplitude, and phase factor, respectively. | [
"Generate",
"atomic",
"displacements",
"of",
"phonon",
"modes",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L2204-L2242 |
227,548 | atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.set_irreps | def set_irreps(self,
q,
is_little_cogroup=False,
nac_q_direction=None,
degeneracy_tolerance=1e-4):
"""Identify ir-reps of phonon modes.
The design of this API is not very satisfactory and is expceted
to be redesined in the next major versions once the use case
of the API for ir-reps feature becomes clearer.
"""
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._irreps = IrReps(
self._dynamical_matrix,
q,
is_little_cogroup=is_little_cogroup,
nac_q_direction=nac_q_direction,
factor=self._factor,
symprec=self._symprec,
degeneracy_tolerance=degeneracy_tolerance,
log_level=self._log_level)
return self._irreps.run() | python | def set_irreps(self,
q,
is_little_cogroup=False,
nac_q_direction=None,
degeneracy_tolerance=1e-4):
"""Identify ir-reps of phonon modes.
The design of this API is not very satisfactory and is expceted
to be redesined in the next major versions once the use case
of the API for ir-reps feature becomes clearer.
"""
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._irreps = IrReps(
self._dynamical_matrix,
q,
is_little_cogroup=is_little_cogroup,
nac_q_direction=nac_q_direction,
factor=self._factor,
symprec=self._symprec,
degeneracy_tolerance=degeneracy_tolerance,
log_level=self._log_level)
return self._irreps.run() | [
"def",
"set_irreps",
"(",
"self",
",",
"q",
",",
"is_little_cogroup",
"=",
"False",
",",
"nac_q_direction",
"=",
"None",
",",
"degeneracy_tolerance",
"=",
"1e-4",
")",
":",
"if",
"self",
".",
"_dynamical_matrix",
"is",
"None",
":",
"msg",
"=",
"(",
"\"Dynamical matrix has not yet built.\"",
")",
"raise",
"RuntimeError",
"(",
"msg",
")",
"self",
".",
"_irreps",
"=",
"IrReps",
"(",
"self",
".",
"_dynamical_matrix",
",",
"q",
",",
"is_little_cogroup",
"=",
"is_little_cogroup",
",",
"nac_q_direction",
"=",
"nac_q_direction",
",",
"factor",
"=",
"self",
".",
"_factor",
",",
"symprec",
"=",
"self",
".",
"_symprec",
",",
"degeneracy_tolerance",
"=",
"degeneracy_tolerance",
",",
"log_level",
"=",
"self",
".",
"_log_level",
")",
"return",
"self",
".",
"_irreps",
".",
"run",
"(",
")"
] | Identify ir-reps of phonon modes.
The design of this API is not very satisfactory and is expceted
to be redesined in the next major versions once the use case
of the API for ir-reps feature becomes clearer. | [
"Identify",
"ir",
"-",
"reps",
"of",
"phonon",
"modes",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L2267-L2294 |
227,549 | atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.init_dynamic_structure_factor | def init_dynamic_structure_factor(self,
Qpoints,
T,
atomic_form_factor_func=None,
scattering_lengths=None,
freq_min=None,
freq_max=None):
"""Initialize dynamic structure factor calculation.
*******************************************************************
This is still an experimental feature. API can be changed without
notification.
*******************************************************************
Need to call DynamicStructureFactor.run() to start calculation.
Parameters
----------
Qpoints: array_like
Q-points in any Brillouin zone.
dtype='double'
shape=(qpoints, 3)
T: float
Temperature in K.
atomic_form_factor_func: Function object
Function that returns atomic form factor (``func`` below):
f_params = {'Na': [3.148690, 2.594987, 4.073989, 6.046925,
0.767888, 0.070139, 0.995612, 14.1226457,
0.968249, 0.217037, 0.045300],
'Cl': [1.061802, 0.144727, 7.139886, 1.171795,
6.524271, 19.467656, 2.355626, 60.320301,
35.829404, 0.000436, -34.916604],b|
def get_func_AFF(f_params):
def func(symbol, Q):
return atomic_form_factor_WK1995(Q, f_params[symbol])
return func
scattering_lengths: dictionary
Coherent scattering lengths averaged over isotopes and spins.
Supposed for INS. For example, {'Na': 3.63, 'Cl': 9.5770}.
freq_min, freq_min: float
Minimum and maximum phonon frequencies to determine whether
phonons are included in the calculation.
"""
if self._mesh is None:
msg = ("run_mesh has to be done before initializing dynamic"
"structure factor.")
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)
self._dynamic_structure_factor = DynamicStructureFactor(
self._mesh,
Qpoints,
T,
atomic_form_factor_func=atomic_form_factor_func,
scattering_lengths=scattering_lengths,
freq_min=freq_min,
freq_max=freq_max) | python | def init_dynamic_structure_factor(self,
Qpoints,
T,
atomic_form_factor_func=None,
scattering_lengths=None,
freq_min=None,
freq_max=None):
"""Initialize dynamic structure factor calculation.
*******************************************************************
This is still an experimental feature. API can be changed without
notification.
*******************************************************************
Need to call DynamicStructureFactor.run() to start calculation.
Parameters
----------
Qpoints: array_like
Q-points in any Brillouin zone.
dtype='double'
shape=(qpoints, 3)
T: float
Temperature in K.
atomic_form_factor_func: Function object
Function that returns atomic form factor (``func`` below):
f_params = {'Na': [3.148690, 2.594987, 4.073989, 6.046925,
0.767888, 0.070139, 0.995612, 14.1226457,
0.968249, 0.217037, 0.045300],
'Cl': [1.061802, 0.144727, 7.139886, 1.171795,
6.524271, 19.467656, 2.355626, 60.320301,
35.829404, 0.000436, -34.916604],b|
def get_func_AFF(f_params):
def func(symbol, Q):
return atomic_form_factor_WK1995(Q, f_params[symbol])
return func
scattering_lengths: dictionary
Coherent scattering lengths averaged over isotopes and spins.
Supposed for INS. For example, {'Na': 3.63, 'Cl': 9.5770}.
freq_min, freq_min: float
Minimum and maximum phonon frequencies to determine whether
phonons are included in the calculation.
"""
if self._mesh is None:
msg = ("run_mesh has to be done before initializing dynamic"
"structure factor.")
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)
self._dynamic_structure_factor = DynamicStructureFactor(
self._mesh,
Qpoints,
T,
atomic_form_factor_func=atomic_form_factor_func,
scattering_lengths=scattering_lengths,
freq_min=freq_min,
freq_max=freq_max) | [
"def",
"init_dynamic_structure_factor",
"(",
"self",
",",
"Qpoints",
",",
"T",
",",
"atomic_form_factor_func",
"=",
"None",
",",
"scattering_lengths",
"=",
"None",
",",
"freq_min",
"=",
"None",
",",
"freq_max",
"=",
"None",
")",
":",
"if",
"self",
".",
"_mesh",
"is",
"None",
":",
"msg",
"=",
"(",
"\"run_mesh has to be done before initializing dynamic\"",
"\"structure factor.\"",
")",
"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",
")",
"self",
".",
"_dynamic_structure_factor",
"=",
"DynamicStructureFactor",
"(",
"self",
".",
"_mesh",
",",
"Qpoints",
",",
"T",
",",
"atomic_form_factor_func",
"=",
"atomic_form_factor_func",
",",
"scattering_lengths",
"=",
"scattering_lengths",
",",
"freq_min",
"=",
"freq_min",
",",
"freq_max",
"=",
"freq_max",
")"
] | Initialize dynamic structure factor calculation.
*******************************************************************
This is still an experimental feature. API can be changed without
notification.
*******************************************************************
Need to call DynamicStructureFactor.run() to start calculation.
Parameters
----------
Qpoints: array_like
Q-points in any Brillouin zone.
dtype='double'
shape=(qpoints, 3)
T: float
Temperature in K.
atomic_form_factor_func: Function object
Function that returns atomic form factor (``func`` below):
f_params = {'Na': [3.148690, 2.594987, 4.073989, 6.046925,
0.767888, 0.070139, 0.995612, 14.1226457,
0.968249, 0.217037, 0.045300],
'Cl': [1.061802, 0.144727, 7.139886, 1.171795,
6.524271, 19.467656, 2.355626, 60.320301,
35.829404, 0.000436, -34.916604],b|
def get_func_AFF(f_params):
def func(symbol, Q):
return atomic_form_factor_WK1995(Q, f_params[symbol])
return func
scattering_lengths: dictionary
Coherent scattering lengths averaged over isotopes and spins.
Supposed for INS. For example, {'Na': 3.63, 'Cl': 9.5770}.
freq_min, freq_min: float
Minimum and maximum phonon frequencies to determine whether
phonons are included in the calculation. | [
"Initialize",
"dynamic",
"structure",
"factor",
"calculation",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L2378-L2445 |
227,550 | atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.run_dynamic_structure_factor | def run_dynamic_structure_factor(self,
Qpoints,
T,
atomic_form_factor_func=None,
scattering_lengths=None,
freq_min=None,
freq_max=None):
"""Run dynamic structure factor calculation
See the detail of parameters at
Phonopy.init_dynamic_structure_factor().
"""
self.init_dynamic_structure_factor(
Qpoints,
T,
atomic_form_factor_func=atomic_form_factor_func,
scattering_lengths=scattering_lengths,
freq_min=freq_min,
freq_max=freq_max)
self._dynamic_structure_factor.run() | python | def run_dynamic_structure_factor(self,
Qpoints,
T,
atomic_form_factor_func=None,
scattering_lengths=None,
freq_min=None,
freq_max=None):
"""Run dynamic structure factor calculation
See the detail of parameters at
Phonopy.init_dynamic_structure_factor().
"""
self.init_dynamic_structure_factor(
Qpoints,
T,
atomic_form_factor_func=atomic_form_factor_func,
scattering_lengths=scattering_lengths,
freq_min=freq_min,
freq_max=freq_max)
self._dynamic_structure_factor.run() | [
"def",
"run_dynamic_structure_factor",
"(",
"self",
",",
"Qpoints",
",",
"T",
",",
"atomic_form_factor_func",
"=",
"None",
",",
"scattering_lengths",
"=",
"None",
",",
"freq_min",
"=",
"None",
",",
"freq_max",
"=",
"None",
")",
":",
"self",
".",
"init_dynamic_structure_factor",
"(",
"Qpoints",
",",
"T",
",",
"atomic_form_factor_func",
"=",
"atomic_form_factor_func",
",",
"scattering_lengths",
"=",
"scattering_lengths",
",",
"freq_min",
"=",
"freq_min",
",",
"freq_max",
"=",
"freq_max",
")",
"self",
".",
"_dynamic_structure_factor",
".",
"run",
"(",
")"
] | Run dynamic structure factor calculation
See the detail of parameters at
Phonopy.init_dynamic_structure_factor(). | [
"Run",
"dynamic",
"structure",
"factor",
"calculation"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L2447-L2468 |
227,551 | atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.save | def save(self,
filename="phonopy_params.yaml",
settings=None):
"""Save parameters in Phonopy instants into file.
Parameters
----------
filename: str, optional
File name. Default is "phonopy_params.yaml"
settings: dict, optional
It is described which parameters are written out. Only
the settings expected to be updated from the following
default settings are needed to be set in the dictionary.
The possible parameters and their default settings are:
{'force_sets': True,
'displacements': True,
'force_constants': False,
'born_effective_charge': True,
'dielectric_constant': True}
"""
phpy_yaml = PhonopyYaml(calculator=self._calculator,
settings=settings)
phpy_yaml.set_phonon_info(self)
with open(filename, 'w') as w:
w.write(str(phpy_yaml)) | python | def save(self,
filename="phonopy_params.yaml",
settings=None):
"""Save parameters in Phonopy instants into file.
Parameters
----------
filename: str, optional
File name. Default is "phonopy_params.yaml"
settings: dict, optional
It is described which parameters are written out. Only
the settings expected to be updated from the following
default settings are needed to be set in the dictionary.
The possible parameters and their default settings are:
{'force_sets': True,
'displacements': True,
'force_constants': False,
'born_effective_charge': True,
'dielectric_constant': True}
"""
phpy_yaml = PhonopyYaml(calculator=self._calculator,
settings=settings)
phpy_yaml.set_phonon_info(self)
with open(filename, 'w') as w:
w.write(str(phpy_yaml)) | [
"def",
"save",
"(",
"self",
",",
"filename",
"=",
"\"phonopy_params.yaml\"",
",",
"settings",
"=",
"None",
")",
":",
"phpy_yaml",
"=",
"PhonopyYaml",
"(",
"calculator",
"=",
"self",
".",
"_calculator",
",",
"settings",
"=",
"settings",
")",
"phpy_yaml",
".",
"set_phonon_info",
"(",
"self",
")",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"w",
":",
"w",
".",
"write",
"(",
"str",
"(",
"phpy_yaml",
")",
")"
] | Save parameters in Phonopy instants into file.
Parameters
----------
filename: str, optional
File name. Default is "phonopy_params.yaml"
settings: dict, optional
It is described which parameters are written out. Only
the settings expected to be updated from the following
default settings are needed to be set in the dictionary.
The possible parameters and their default settings are:
{'force_sets': True,
'displacements': True,
'force_constants': False,
'born_effective_charge': True,
'dielectric_constant': True} | [
"Save",
"parameters",
"in",
"Phonopy",
"instants",
"into",
"file",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L2520-L2545 |
227,552 | atztogo/phonopy | phonopy/phonon/mesh.py | length2mesh | def length2mesh(length, lattice, rotations=None):
"""Convert length to mesh for q-point sampling
This conversion for each reciprocal axis follows VASP convention by
N = max(1, int(l * |a|^* + 0.5))
'int' means rounding down, not rounding to nearest integer.
Parameters
----------
length : float
Length having the unit of direct space length.
lattice : array_like
Basis vectors of primitive cell in row vectors.
dtype='double', shape=(3, 3)
rotations: array_like, optional
Rotation matrices in real space. When given, mesh numbers that are
symmetrically reasonable are returned. Default is None.
dtype='intc', shape=(rotations, 3, 3)
Returns
-------
array_like
dtype=int, shape=(3,)
"""
rec_lattice = np.linalg.inv(lattice)
rec_lat_lengths = np.sqrt(np.diagonal(np.dot(rec_lattice.T, rec_lattice)))
mesh_numbers = np.rint(rec_lat_lengths * length).astype(int)
if rotations is not None:
reclat_equiv = get_lattice_vector_equivalence(
[r.T for r in np.array(rotations)])
m = mesh_numbers
mesh_equiv = [m[1] == m[2], m[2] == m[0], m[0] == m[1]]
for i, pair in enumerate(([1, 2], [2, 0], [0, 1])):
if reclat_equiv[i] and not mesh_equiv:
m[pair] = max(m[pair])
return np.maximum(mesh_numbers, [1, 1, 1]) | python | def length2mesh(length, lattice, rotations=None):
"""Convert length to mesh for q-point sampling
This conversion for each reciprocal axis follows VASP convention by
N = max(1, int(l * |a|^* + 0.5))
'int' means rounding down, not rounding to nearest integer.
Parameters
----------
length : float
Length having the unit of direct space length.
lattice : array_like
Basis vectors of primitive cell in row vectors.
dtype='double', shape=(3, 3)
rotations: array_like, optional
Rotation matrices in real space. When given, mesh numbers that are
symmetrically reasonable are returned. Default is None.
dtype='intc', shape=(rotations, 3, 3)
Returns
-------
array_like
dtype=int, shape=(3,)
"""
rec_lattice = np.linalg.inv(lattice)
rec_lat_lengths = np.sqrt(np.diagonal(np.dot(rec_lattice.T, rec_lattice)))
mesh_numbers = np.rint(rec_lat_lengths * length).astype(int)
if rotations is not None:
reclat_equiv = get_lattice_vector_equivalence(
[r.T for r in np.array(rotations)])
m = mesh_numbers
mesh_equiv = [m[1] == m[2], m[2] == m[0], m[0] == m[1]]
for i, pair in enumerate(([1, 2], [2, 0], [0, 1])):
if reclat_equiv[i] and not mesh_equiv:
m[pair] = max(m[pair])
return np.maximum(mesh_numbers, [1, 1, 1]) | [
"def",
"length2mesh",
"(",
"length",
",",
"lattice",
",",
"rotations",
"=",
"None",
")",
":",
"rec_lattice",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"lattice",
")",
"rec_lat_lengths",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"diagonal",
"(",
"np",
".",
"dot",
"(",
"rec_lattice",
".",
"T",
",",
"rec_lattice",
")",
")",
")",
"mesh_numbers",
"=",
"np",
".",
"rint",
"(",
"rec_lat_lengths",
"*",
"length",
")",
".",
"astype",
"(",
"int",
")",
"if",
"rotations",
"is",
"not",
"None",
":",
"reclat_equiv",
"=",
"get_lattice_vector_equivalence",
"(",
"[",
"r",
".",
"T",
"for",
"r",
"in",
"np",
".",
"array",
"(",
"rotations",
")",
"]",
")",
"m",
"=",
"mesh_numbers",
"mesh_equiv",
"=",
"[",
"m",
"[",
"1",
"]",
"==",
"m",
"[",
"2",
"]",
",",
"m",
"[",
"2",
"]",
"==",
"m",
"[",
"0",
"]",
",",
"m",
"[",
"0",
"]",
"==",
"m",
"[",
"1",
"]",
"]",
"for",
"i",
",",
"pair",
"in",
"enumerate",
"(",
"(",
"[",
"1",
",",
"2",
"]",
",",
"[",
"2",
",",
"0",
"]",
",",
"[",
"0",
",",
"1",
"]",
")",
")",
":",
"if",
"reclat_equiv",
"[",
"i",
"]",
"and",
"not",
"mesh_equiv",
":",
"m",
"[",
"pair",
"]",
"=",
"max",
"(",
"m",
"[",
"pair",
"]",
")",
"return",
"np",
".",
"maximum",
"(",
"mesh_numbers",
",",
"[",
"1",
",",
"1",
",",
"1",
"]",
")"
] | Convert length to mesh for q-point sampling
This conversion for each reciprocal axis follows VASP convention by
N = max(1, int(l * |a|^* + 0.5))
'int' means rounding down, not rounding to nearest integer.
Parameters
----------
length : float
Length having the unit of direct space length.
lattice : array_like
Basis vectors of primitive cell in row vectors.
dtype='double', shape=(3, 3)
rotations: array_like, optional
Rotation matrices in real space. When given, mesh numbers that are
symmetrically reasonable are returned. Default is None.
dtype='intc', shape=(rotations, 3, 3)
Returns
-------
array_like
dtype=int, shape=(3,) | [
"Convert",
"length",
"to",
"mesh",
"for",
"q",
"-",
"point",
"sampling"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/phonon/mesh.py#L41-L80 |
227,553 | atztogo/phonopy | phonopy/phonon/thermal_displacement.py | ThermalMotion._get_population | def _get_population(self, freq, t): # freq in THz
"""Return phonon population number
Three types of combinations of array inputs are possible.
- single freq and single t
- single freq and len(t) > 1
- len(freq) > 1 and single t
"""
condition = t > 1.0
if type(condition) == bool or type(condition) == np.bool_:
if condition:
return 1.0 / (np.exp(freq * THzToEv / (Kb * t)) - 1)
else:
return 0.0
else:
vals = np.zeros(len(t), dtype='double')
vals[condition] = 1.0 / (
np.exp(freq * THzToEv / (Kb * t[condition])) - 1)
return vals | python | def _get_population(self, freq, t): # freq in THz
"""Return phonon population number
Three types of combinations of array inputs are possible.
- single freq and single t
- single freq and len(t) > 1
- len(freq) > 1 and single t
"""
condition = t > 1.0
if type(condition) == bool or type(condition) == np.bool_:
if condition:
return 1.0 / (np.exp(freq * THzToEv / (Kb * t)) - 1)
else:
return 0.0
else:
vals = np.zeros(len(t), dtype='double')
vals[condition] = 1.0 / (
np.exp(freq * THzToEv / (Kb * t[condition])) - 1)
return vals | [
"def",
"_get_population",
"(",
"self",
",",
"freq",
",",
"t",
")",
":",
"# freq in THz",
"condition",
"=",
"t",
">",
"1.0",
"if",
"type",
"(",
"condition",
")",
"==",
"bool",
"or",
"type",
"(",
"condition",
")",
"==",
"np",
".",
"bool_",
":",
"if",
"condition",
":",
"return",
"1.0",
"/",
"(",
"np",
".",
"exp",
"(",
"freq",
"*",
"THzToEv",
"/",
"(",
"Kb",
"*",
"t",
")",
")",
"-",
"1",
")",
"else",
":",
"return",
"0.0",
"else",
":",
"vals",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"t",
")",
",",
"dtype",
"=",
"'double'",
")",
"vals",
"[",
"condition",
"]",
"=",
"1.0",
"/",
"(",
"np",
".",
"exp",
"(",
"freq",
"*",
"THzToEv",
"/",
"(",
"Kb",
"*",
"t",
"[",
"condition",
"]",
")",
")",
"-",
"1",
")",
"return",
"vals"
] | Return phonon population number
Three types of combinations of array inputs are possible.
- single freq and single t
- single freq and len(t) > 1
- len(freq) > 1 and single t | [
"Return",
"phonon",
"population",
"number"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/phonon/thermal_displacement.py#L101-L120 |
227,554 | atztogo/phonopy | phonopy/phonon/thermal_displacement.py | ThermalDisplacements._project_eigenvectors | def _project_eigenvectors(self):
"""Eigenvectors are projected along Cartesian direction"""
self._p_eigenvectors = []
for vecs_q in self._eigenvectors:
p_vecs_q = []
for vecs in vecs_q.T:
p_vecs_q.append(np.dot(vecs.reshape(-1, 3),
self._projection_direction))
self._p_eigenvectors.append(np.transpose(p_vecs_q))
self._p_eigenvectors = np.array(self._p_eigenvectors) | python | def _project_eigenvectors(self):
"""Eigenvectors are projected along Cartesian direction"""
self._p_eigenvectors = []
for vecs_q in self._eigenvectors:
p_vecs_q = []
for vecs in vecs_q.T:
p_vecs_q.append(np.dot(vecs.reshape(-1, 3),
self._projection_direction))
self._p_eigenvectors.append(np.transpose(p_vecs_q))
self._p_eigenvectors = np.array(self._p_eigenvectors) | [
"def",
"_project_eigenvectors",
"(",
"self",
")",
":",
"self",
".",
"_p_eigenvectors",
"=",
"[",
"]",
"for",
"vecs_q",
"in",
"self",
".",
"_eigenvectors",
":",
"p_vecs_q",
"=",
"[",
"]",
"for",
"vecs",
"in",
"vecs_q",
".",
"T",
":",
"p_vecs_q",
".",
"append",
"(",
"np",
".",
"dot",
"(",
"vecs",
".",
"reshape",
"(",
"-",
"1",
",",
"3",
")",
",",
"self",
".",
"_projection_direction",
")",
")",
"self",
".",
"_p_eigenvectors",
".",
"append",
"(",
"np",
".",
"transpose",
"(",
"p_vecs_q",
")",
")",
"self",
".",
"_p_eigenvectors",
"=",
"np",
".",
"array",
"(",
"self",
".",
"_p_eigenvectors",
")"
] | Eigenvectors are projected along Cartesian direction | [
"Eigenvectors",
"are",
"projected",
"along",
"Cartesian",
"direction"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/phonon/thermal_displacement.py#L226-L236 |
227,555 | atztogo/phonopy | phonopy/structure/spglib.py | get_symmetry | def get_symmetry(cell, symprec=1e-5, angle_tolerance=-1.0):
"""This gives crystal symmetry operations from a crystal structure.
Args:
cell: Crystal structrue given either in Atoms object or tuple.
In the case given by a tuple, it has to follow the form below,
(Lattice parameters in a 3x3 array (see the detail below),
Fractional atomic positions in an Nx3 array,
Integer numbers to distinguish species in a length N array,
(optional) Collinear magnetic moments in a length N array),
where N is the number of atoms.
Lattice parameters are given in the form:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
symprec:
float: Symmetry search tolerance in the unit of length.
angle_tolerance:
float: Symmetry search tolerance in the unit of angle deg.
If the value is negative, an internally optimized routine
is used to judge symmetry.
Return:
A dictionary: Rotation parts and translation parts. Dictionary keys:
'rotations': Gives the numpy 'intc' array of the rotation matrices.
'translations': Gives the numpy 'double' array of fractional
translations with respect to a, b, c axes.
"""
_set_no_error()
lattice, positions, numbers, magmoms = _expand_cell(cell)
if lattice is None:
return None
multi = 48 * len(positions)
rotation = np.zeros((multi, 3, 3), dtype='intc')
translation = np.zeros((multi, 3), dtype='double')
# Get symmetry operations
if magmoms is None:
dataset = get_symmetry_dataset(cell,
symprec=symprec,
angle_tolerance=angle_tolerance)
if dataset is None:
return None
else:
return {'rotations': dataset['rotations'],
'translations': dataset['translations'],
'equivalent_atoms': dataset['equivalent_atoms']}
else:
equivalent_atoms = np.zeros(len(magmoms), dtype='intc')
num_sym = spg.symmetry_with_collinear_spin(rotation,
translation,
equivalent_atoms,
lattice,
positions,
numbers,
magmoms,
symprec,
angle_tolerance)
_set_error_message()
if num_sym == 0:
return None
else:
return {'rotations': np.array(rotation[:num_sym],
dtype='intc', order='C'),
'translations': np.array(translation[:num_sym],
dtype='double', order='C'),
'equivalent_atoms': equivalent_atoms} | python | def get_symmetry(cell, symprec=1e-5, angle_tolerance=-1.0):
"""This gives crystal symmetry operations from a crystal structure.
Args:
cell: Crystal structrue given either in Atoms object or tuple.
In the case given by a tuple, it has to follow the form below,
(Lattice parameters in a 3x3 array (see the detail below),
Fractional atomic positions in an Nx3 array,
Integer numbers to distinguish species in a length N array,
(optional) Collinear magnetic moments in a length N array),
where N is the number of atoms.
Lattice parameters are given in the form:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
symprec:
float: Symmetry search tolerance in the unit of length.
angle_tolerance:
float: Symmetry search tolerance in the unit of angle deg.
If the value is negative, an internally optimized routine
is used to judge symmetry.
Return:
A dictionary: Rotation parts and translation parts. Dictionary keys:
'rotations': Gives the numpy 'intc' array of the rotation matrices.
'translations': Gives the numpy 'double' array of fractional
translations with respect to a, b, c axes.
"""
_set_no_error()
lattice, positions, numbers, magmoms = _expand_cell(cell)
if lattice is None:
return None
multi = 48 * len(positions)
rotation = np.zeros((multi, 3, 3), dtype='intc')
translation = np.zeros((multi, 3), dtype='double')
# Get symmetry operations
if magmoms is None:
dataset = get_symmetry_dataset(cell,
symprec=symprec,
angle_tolerance=angle_tolerance)
if dataset is None:
return None
else:
return {'rotations': dataset['rotations'],
'translations': dataset['translations'],
'equivalent_atoms': dataset['equivalent_atoms']}
else:
equivalent_atoms = np.zeros(len(magmoms), dtype='intc')
num_sym = spg.symmetry_with_collinear_spin(rotation,
translation,
equivalent_atoms,
lattice,
positions,
numbers,
magmoms,
symprec,
angle_tolerance)
_set_error_message()
if num_sym == 0:
return None
else:
return {'rotations': np.array(rotation[:num_sym],
dtype='intc', order='C'),
'translations': np.array(translation[:num_sym],
dtype='double', order='C'),
'equivalent_atoms': equivalent_atoms} | [
"def",
"get_symmetry",
"(",
"cell",
",",
"symprec",
"=",
"1e-5",
",",
"angle_tolerance",
"=",
"-",
"1.0",
")",
":",
"_set_no_error",
"(",
")",
"lattice",
",",
"positions",
",",
"numbers",
",",
"magmoms",
"=",
"_expand_cell",
"(",
"cell",
")",
"if",
"lattice",
"is",
"None",
":",
"return",
"None",
"multi",
"=",
"48",
"*",
"len",
"(",
"positions",
")",
"rotation",
"=",
"np",
".",
"zeros",
"(",
"(",
"multi",
",",
"3",
",",
"3",
")",
",",
"dtype",
"=",
"'intc'",
")",
"translation",
"=",
"np",
".",
"zeros",
"(",
"(",
"multi",
",",
"3",
")",
",",
"dtype",
"=",
"'double'",
")",
"# Get symmetry operations",
"if",
"magmoms",
"is",
"None",
":",
"dataset",
"=",
"get_symmetry_dataset",
"(",
"cell",
",",
"symprec",
"=",
"symprec",
",",
"angle_tolerance",
"=",
"angle_tolerance",
")",
"if",
"dataset",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",
"{",
"'rotations'",
":",
"dataset",
"[",
"'rotations'",
"]",
",",
"'translations'",
":",
"dataset",
"[",
"'translations'",
"]",
",",
"'equivalent_atoms'",
":",
"dataset",
"[",
"'equivalent_atoms'",
"]",
"}",
"else",
":",
"equivalent_atoms",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"magmoms",
")",
",",
"dtype",
"=",
"'intc'",
")",
"num_sym",
"=",
"spg",
".",
"symmetry_with_collinear_spin",
"(",
"rotation",
",",
"translation",
",",
"equivalent_atoms",
",",
"lattice",
",",
"positions",
",",
"numbers",
",",
"magmoms",
",",
"symprec",
",",
"angle_tolerance",
")",
"_set_error_message",
"(",
")",
"if",
"num_sym",
"==",
"0",
":",
"return",
"None",
"else",
":",
"return",
"{",
"'rotations'",
":",
"np",
".",
"array",
"(",
"rotation",
"[",
":",
"num_sym",
"]",
",",
"dtype",
"=",
"'intc'",
",",
"order",
"=",
"'C'",
")",
",",
"'translations'",
":",
"np",
".",
"array",
"(",
"translation",
"[",
":",
"num_sym",
"]",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
",",
"'equivalent_atoms'",
":",
"equivalent_atoms",
"}"
] | This gives crystal symmetry operations from a crystal structure.
Args:
cell: Crystal structrue given either in Atoms object or tuple.
In the case given by a tuple, it has to follow the form below,
(Lattice parameters in a 3x3 array (see the detail below),
Fractional atomic positions in an Nx3 array,
Integer numbers to distinguish species in a length N array,
(optional) Collinear magnetic moments in a length N array),
where N is the number of atoms.
Lattice parameters are given in the form:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
symprec:
float: Symmetry search tolerance in the unit of length.
angle_tolerance:
float: Symmetry search tolerance in the unit of angle deg.
If the value is negative, an internally optimized routine
is used to judge symmetry.
Return:
A dictionary: Rotation parts and translation parts. Dictionary keys:
'rotations': Gives the numpy 'intc' array of the rotation matrices.
'translations': Gives the numpy 'double' array of fractional
translations with respect to a, b, c axes. | [
"This",
"gives",
"crystal",
"symmetry",
"operations",
"from",
"a",
"crystal",
"structure",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L51-L120 |
227,556 | atztogo/phonopy | phonopy/structure/spglib.py | get_symmetry_dataset | def get_symmetry_dataset(cell,
symprec=1e-5,
angle_tolerance=-1.0,
hall_number=0):
"""Search symmetry dataset from an input cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
hall_number: If a serial number of Hall symbol (>0) is given,
the database corresponding to the Hall symbol is made.
Return:
A dictionary is returned. Dictionary keys:
number (int): International space group number
international (str): International symbol
hall (str): Hall symbol
choice (str): Centring, origin, basis vector setting
transformation_matrix (3x3 float):
Transformation matrix from input lattice to standardized
lattice:
L^original = L^standardized * Tmat
origin shift (3 float):
Origin shift from standardized to input origin
rotations (3x3 int), translations (float vector):
Rotation matrices and translation vectors. Space group
operations are obtained by
[(r,t) for r, t in zip(rotations, translations)]
wyckoffs (n char): Wyckoff letters
equivalent_atoms (n int): Symmetrically equivalent atoms
mapping_to_primitive (n int):
Original cell atom index mapping to primivie cell atom index
Idealized standardized unit cell:
std_lattice (3x3 float, row vectors),
std_positions (Nx3 float), std_types (N int)
std_rotation_matrix:
Rigid rotation matrix to rotate from standardized basis
vectors to idealized standardized basis vectors
L^idealized = R * L^standardized
std_mapping_to_primitive (m int):
std_positions index mapping to those of primivie cell atoms
pointgroup (str): Pointgroup symbol
If it fails, None is returned.
"""
_set_no_error()
lattice, positions, numbers, _ = _expand_cell(cell)
if lattice is None:
return None
spg_ds = spg.dataset(lattice, positions, numbers, hall_number,
symprec, angle_tolerance)
if spg_ds is None:
_set_error_message()
return None
keys = ('number',
'hall_number',
'international',
'hall',
'choice',
'transformation_matrix',
'origin_shift',
'rotations',
'translations',
'wyckoffs',
'site_symmetry_symbols',
'equivalent_atoms',
'mapping_to_primitive',
'std_lattice',
'std_types',
'std_positions',
'std_rotation_matrix',
'std_mapping_to_primitive',
# 'pointgroup_number',
'pointgroup')
dataset = {}
for key, data in zip(keys, spg_ds):
dataset[key] = data
dataset['international'] = dataset['international'].strip()
dataset['hall'] = dataset['hall'].strip()
dataset['choice'] = dataset['choice'].strip()
dataset['transformation_matrix'] = np.array(
dataset['transformation_matrix'], dtype='double', order='C')
dataset['origin_shift'] = np.array(dataset['origin_shift'], dtype='double')
dataset['rotations'] = np.array(dataset['rotations'],
dtype='intc', order='C')
dataset['translations'] = np.array(dataset['translations'],
dtype='double', order='C')
letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
dataset['wyckoffs'] = [letters[x] for x in dataset['wyckoffs']]
dataset['site_symmetry_symbols'] = [
s.strip() for s in dataset['site_symmetry_symbols']]
dataset['equivalent_atoms'] = np.array(dataset['equivalent_atoms'],
dtype='intc')
dataset['mapping_to_primitive'] = np.array(dataset['mapping_to_primitive'],
dtype='intc')
dataset['std_lattice'] = np.array(np.transpose(dataset['std_lattice']),
dtype='double', order='C')
dataset['std_types'] = np.array(dataset['std_types'], dtype='intc')
dataset['std_positions'] = np.array(dataset['std_positions'],
dtype='double', order='C')
dataset['std_rotation_matrix'] = np.array(dataset['std_rotation_matrix'],
dtype='double', order='C')
dataset['std_mapping_to_primitive'] = np.array(
dataset['std_mapping_to_primitive'], dtype='intc')
dataset['pointgroup'] = dataset['pointgroup'].strip()
_set_error_message()
return dataset | python | def get_symmetry_dataset(cell,
symprec=1e-5,
angle_tolerance=-1.0,
hall_number=0):
"""Search symmetry dataset from an input cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
hall_number: If a serial number of Hall symbol (>0) is given,
the database corresponding to the Hall symbol is made.
Return:
A dictionary is returned. Dictionary keys:
number (int): International space group number
international (str): International symbol
hall (str): Hall symbol
choice (str): Centring, origin, basis vector setting
transformation_matrix (3x3 float):
Transformation matrix from input lattice to standardized
lattice:
L^original = L^standardized * Tmat
origin shift (3 float):
Origin shift from standardized to input origin
rotations (3x3 int), translations (float vector):
Rotation matrices and translation vectors. Space group
operations are obtained by
[(r,t) for r, t in zip(rotations, translations)]
wyckoffs (n char): Wyckoff letters
equivalent_atoms (n int): Symmetrically equivalent atoms
mapping_to_primitive (n int):
Original cell atom index mapping to primivie cell atom index
Idealized standardized unit cell:
std_lattice (3x3 float, row vectors),
std_positions (Nx3 float), std_types (N int)
std_rotation_matrix:
Rigid rotation matrix to rotate from standardized basis
vectors to idealized standardized basis vectors
L^idealized = R * L^standardized
std_mapping_to_primitive (m int):
std_positions index mapping to those of primivie cell atoms
pointgroup (str): Pointgroup symbol
If it fails, None is returned.
"""
_set_no_error()
lattice, positions, numbers, _ = _expand_cell(cell)
if lattice is None:
return None
spg_ds = spg.dataset(lattice, positions, numbers, hall_number,
symprec, angle_tolerance)
if spg_ds is None:
_set_error_message()
return None
keys = ('number',
'hall_number',
'international',
'hall',
'choice',
'transformation_matrix',
'origin_shift',
'rotations',
'translations',
'wyckoffs',
'site_symmetry_symbols',
'equivalent_atoms',
'mapping_to_primitive',
'std_lattice',
'std_types',
'std_positions',
'std_rotation_matrix',
'std_mapping_to_primitive',
# 'pointgroup_number',
'pointgroup')
dataset = {}
for key, data in zip(keys, spg_ds):
dataset[key] = data
dataset['international'] = dataset['international'].strip()
dataset['hall'] = dataset['hall'].strip()
dataset['choice'] = dataset['choice'].strip()
dataset['transformation_matrix'] = np.array(
dataset['transformation_matrix'], dtype='double', order='C')
dataset['origin_shift'] = np.array(dataset['origin_shift'], dtype='double')
dataset['rotations'] = np.array(dataset['rotations'],
dtype='intc', order='C')
dataset['translations'] = np.array(dataset['translations'],
dtype='double', order='C')
letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
dataset['wyckoffs'] = [letters[x] for x in dataset['wyckoffs']]
dataset['site_symmetry_symbols'] = [
s.strip() for s in dataset['site_symmetry_symbols']]
dataset['equivalent_atoms'] = np.array(dataset['equivalent_atoms'],
dtype='intc')
dataset['mapping_to_primitive'] = np.array(dataset['mapping_to_primitive'],
dtype='intc')
dataset['std_lattice'] = np.array(np.transpose(dataset['std_lattice']),
dtype='double', order='C')
dataset['std_types'] = np.array(dataset['std_types'], dtype='intc')
dataset['std_positions'] = np.array(dataset['std_positions'],
dtype='double', order='C')
dataset['std_rotation_matrix'] = np.array(dataset['std_rotation_matrix'],
dtype='double', order='C')
dataset['std_mapping_to_primitive'] = np.array(
dataset['std_mapping_to_primitive'], dtype='intc')
dataset['pointgroup'] = dataset['pointgroup'].strip()
_set_error_message()
return dataset | [
"def",
"get_symmetry_dataset",
"(",
"cell",
",",
"symprec",
"=",
"1e-5",
",",
"angle_tolerance",
"=",
"-",
"1.0",
",",
"hall_number",
"=",
"0",
")",
":",
"_set_no_error",
"(",
")",
"lattice",
",",
"positions",
",",
"numbers",
",",
"_",
"=",
"_expand_cell",
"(",
"cell",
")",
"if",
"lattice",
"is",
"None",
":",
"return",
"None",
"spg_ds",
"=",
"spg",
".",
"dataset",
"(",
"lattice",
",",
"positions",
",",
"numbers",
",",
"hall_number",
",",
"symprec",
",",
"angle_tolerance",
")",
"if",
"spg_ds",
"is",
"None",
":",
"_set_error_message",
"(",
")",
"return",
"None",
"keys",
"=",
"(",
"'number'",
",",
"'hall_number'",
",",
"'international'",
",",
"'hall'",
",",
"'choice'",
",",
"'transformation_matrix'",
",",
"'origin_shift'",
",",
"'rotations'",
",",
"'translations'",
",",
"'wyckoffs'",
",",
"'site_symmetry_symbols'",
",",
"'equivalent_atoms'",
",",
"'mapping_to_primitive'",
",",
"'std_lattice'",
",",
"'std_types'",
",",
"'std_positions'",
",",
"'std_rotation_matrix'",
",",
"'std_mapping_to_primitive'",
",",
"# 'pointgroup_number',",
"'pointgroup'",
")",
"dataset",
"=",
"{",
"}",
"for",
"key",
",",
"data",
"in",
"zip",
"(",
"keys",
",",
"spg_ds",
")",
":",
"dataset",
"[",
"key",
"]",
"=",
"data",
"dataset",
"[",
"'international'",
"]",
"=",
"dataset",
"[",
"'international'",
"]",
".",
"strip",
"(",
")",
"dataset",
"[",
"'hall'",
"]",
"=",
"dataset",
"[",
"'hall'",
"]",
".",
"strip",
"(",
")",
"dataset",
"[",
"'choice'",
"]",
"=",
"dataset",
"[",
"'choice'",
"]",
".",
"strip",
"(",
")",
"dataset",
"[",
"'transformation_matrix'",
"]",
"=",
"np",
".",
"array",
"(",
"dataset",
"[",
"'transformation_matrix'",
"]",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"dataset",
"[",
"'origin_shift'",
"]",
"=",
"np",
".",
"array",
"(",
"dataset",
"[",
"'origin_shift'",
"]",
",",
"dtype",
"=",
"'double'",
")",
"dataset",
"[",
"'rotations'",
"]",
"=",
"np",
".",
"array",
"(",
"dataset",
"[",
"'rotations'",
"]",
",",
"dtype",
"=",
"'intc'",
",",
"order",
"=",
"'C'",
")",
"dataset",
"[",
"'translations'",
"]",
"=",
"np",
".",
"array",
"(",
"dataset",
"[",
"'translations'",
"]",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"letters",
"=",
"\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"",
"dataset",
"[",
"'wyckoffs'",
"]",
"=",
"[",
"letters",
"[",
"x",
"]",
"for",
"x",
"in",
"dataset",
"[",
"'wyckoffs'",
"]",
"]",
"dataset",
"[",
"'site_symmetry_symbols'",
"]",
"=",
"[",
"s",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"dataset",
"[",
"'site_symmetry_symbols'",
"]",
"]",
"dataset",
"[",
"'equivalent_atoms'",
"]",
"=",
"np",
".",
"array",
"(",
"dataset",
"[",
"'equivalent_atoms'",
"]",
",",
"dtype",
"=",
"'intc'",
")",
"dataset",
"[",
"'mapping_to_primitive'",
"]",
"=",
"np",
".",
"array",
"(",
"dataset",
"[",
"'mapping_to_primitive'",
"]",
",",
"dtype",
"=",
"'intc'",
")",
"dataset",
"[",
"'std_lattice'",
"]",
"=",
"np",
".",
"array",
"(",
"np",
".",
"transpose",
"(",
"dataset",
"[",
"'std_lattice'",
"]",
")",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"dataset",
"[",
"'std_types'",
"]",
"=",
"np",
".",
"array",
"(",
"dataset",
"[",
"'std_types'",
"]",
",",
"dtype",
"=",
"'intc'",
")",
"dataset",
"[",
"'std_positions'",
"]",
"=",
"np",
".",
"array",
"(",
"dataset",
"[",
"'std_positions'",
"]",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"dataset",
"[",
"'std_rotation_matrix'",
"]",
"=",
"np",
".",
"array",
"(",
"dataset",
"[",
"'std_rotation_matrix'",
"]",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"dataset",
"[",
"'std_mapping_to_primitive'",
"]",
"=",
"np",
".",
"array",
"(",
"dataset",
"[",
"'std_mapping_to_primitive'",
"]",
",",
"dtype",
"=",
"'intc'",
")",
"dataset",
"[",
"'pointgroup'",
"]",
"=",
"dataset",
"[",
"'pointgroup'",
"]",
".",
"strip",
"(",
")",
"_set_error_message",
"(",
")",
"return",
"dataset"
] | Search symmetry dataset from an input cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
hall_number: If a serial number of Hall symbol (>0) is given,
the database corresponding to the Hall symbol is made.
Return:
A dictionary is returned. Dictionary keys:
number (int): International space group number
international (str): International symbol
hall (str): Hall symbol
choice (str): Centring, origin, basis vector setting
transformation_matrix (3x3 float):
Transformation matrix from input lattice to standardized
lattice:
L^original = L^standardized * Tmat
origin shift (3 float):
Origin shift from standardized to input origin
rotations (3x3 int), translations (float vector):
Rotation matrices and translation vectors. Space group
operations are obtained by
[(r,t) for r, t in zip(rotations, translations)]
wyckoffs (n char): Wyckoff letters
equivalent_atoms (n int): Symmetrically equivalent atoms
mapping_to_primitive (n int):
Original cell atom index mapping to primivie cell atom index
Idealized standardized unit cell:
std_lattice (3x3 float, row vectors),
std_positions (Nx3 float), std_types (N int)
std_rotation_matrix:
Rigid rotation matrix to rotate from standardized basis
vectors to idealized standardized basis vectors
L^idealized = R * L^standardized
std_mapping_to_primitive (m int):
std_positions index mapping to those of primivie cell atoms
pointgroup (str): Pointgroup symbol
If it fails, None is returned. | [
"Search",
"symmetry",
"dataset",
"from",
"an",
"input",
"cell",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L123-L235 |
227,557 | atztogo/phonopy | phonopy/structure/spglib.py | get_spacegroup | def get_spacegroup(cell, symprec=1e-5, angle_tolerance=-1.0, symbol_type=0):
"""Return space group in international table symbol and number as a string.
If it fails, None is returned.
"""
_set_no_error()
dataset = get_symmetry_dataset(cell,
symprec=symprec,
angle_tolerance=angle_tolerance)
if dataset is None:
return None
spg_type = get_spacegroup_type(dataset['hall_number'])
if symbol_type == 1:
return "%s (%d)" % (spg_type['schoenflies'], dataset['number'])
else:
return "%s (%d)" % (spg_type['international_short'], dataset['number']) | python | def get_spacegroup(cell, symprec=1e-5, angle_tolerance=-1.0, symbol_type=0):
"""Return space group in international table symbol and number as a string.
If it fails, None is returned.
"""
_set_no_error()
dataset = get_symmetry_dataset(cell,
symprec=symprec,
angle_tolerance=angle_tolerance)
if dataset is None:
return None
spg_type = get_spacegroup_type(dataset['hall_number'])
if symbol_type == 1:
return "%s (%d)" % (spg_type['schoenflies'], dataset['number'])
else:
return "%s (%d)" % (spg_type['international_short'], dataset['number']) | [
"def",
"get_spacegroup",
"(",
"cell",
",",
"symprec",
"=",
"1e-5",
",",
"angle_tolerance",
"=",
"-",
"1.0",
",",
"symbol_type",
"=",
"0",
")",
":",
"_set_no_error",
"(",
")",
"dataset",
"=",
"get_symmetry_dataset",
"(",
"cell",
",",
"symprec",
"=",
"symprec",
",",
"angle_tolerance",
"=",
"angle_tolerance",
")",
"if",
"dataset",
"is",
"None",
":",
"return",
"None",
"spg_type",
"=",
"get_spacegroup_type",
"(",
"dataset",
"[",
"'hall_number'",
"]",
")",
"if",
"symbol_type",
"==",
"1",
":",
"return",
"\"%s (%d)\"",
"%",
"(",
"spg_type",
"[",
"'schoenflies'",
"]",
",",
"dataset",
"[",
"'number'",
"]",
")",
"else",
":",
"return",
"\"%s (%d)\"",
"%",
"(",
"spg_type",
"[",
"'international_short'",
"]",
",",
"dataset",
"[",
"'number'",
"]",
")"
] | Return space group in international table symbol and number as a string.
If it fails, None is returned. | [
"Return",
"space",
"group",
"in",
"international",
"table",
"symbol",
"and",
"number",
"as",
"a",
"string",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L238-L255 |
227,558 | atztogo/phonopy | phonopy/structure/spglib.py | get_hall_number_from_symmetry | def get_hall_number_from_symmetry(rotations, translations, symprec=1e-5):
"""Hall number is obtained from a set of symmetry operations.
If it fails, None is returned.
"""
r = np.array(rotations, dtype='intc', order='C')
t = np.array(translations, dtype='double', order='C')
hall_number = spg.hall_number_from_symmetry(r, t, symprec)
return hall_number | python | def get_hall_number_from_symmetry(rotations, translations, symprec=1e-5):
"""Hall number is obtained from a set of symmetry operations.
If it fails, None is returned.
"""
r = np.array(rotations, dtype='intc', order='C')
t = np.array(translations, dtype='double', order='C')
hall_number = spg.hall_number_from_symmetry(r, t, symprec)
return hall_number | [
"def",
"get_hall_number_from_symmetry",
"(",
"rotations",
",",
"translations",
",",
"symprec",
"=",
"1e-5",
")",
":",
"r",
"=",
"np",
".",
"array",
"(",
"rotations",
",",
"dtype",
"=",
"'intc'",
",",
"order",
"=",
"'C'",
")",
"t",
"=",
"np",
".",
"array",
"(",
"translations",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"hall_number",
"=",
"spg",
".",
"hall_number_from_symmetry",
"(",
"r",
",",
"t",
",",
"symprec",
")",
"return",
"hall_number"
] | Hall number is obtained from a set of symmetry operations.
If it fails, None is returned. | [
"Hall",
"number",
"is",
"obtained",
"from",
"a",
"set",
"of",
"symmetry",
"operations",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L258-L267 |
227,559 | atztogo/phonopy | phonopy/structure/spglib.py | get_spacegroup_type | def get_spacegroup_type(hall_number):
"""Translate Hall number to space group type information.
If it fails, None is returned.
"""
_set_no_error()
keys = ('number',
'international_short',
'international_full',
'international',
'schoenflies',
'hall_symbol',
'choice',
'pointgroup_schoenflies',
'pointgroup_international',
'arithmetic_crystal_class_number',
'arithmetic_crystal_class_symbol')
spg_type_list = spg.spacegroup_type(hall_number)
_set_error_message()
if spg_type_list is not None:
spg_type = dict(zip(keys, spg_type_list))
for key in spg_type:
if key != 'number' and key != 'arithmetic_crystal_class_number':
spg_type[key] = spg_type[key].strip()
return spg_type
else:
return None | python | def get_spacegroup_type(hall_number):
"""Translate Hall number to space group type information.
If it fails, None is returned.
"""
_set_no_error()
keys = ('number',
'international_short',
'international_full',
'international',
'schoenflies',
'hall_symbol',
'choice',
'pointgroup_schoenflies',
'pointgroup_international',
'arithmetic_crystal_class_number',
'arithmetic_crystal_class_symbol')
spg_type_list = spg.spacegroup_type(hall_number)
_set_error_message()
if spg_type_list is not None:
spg_type = dict(zip(keys, spg_type_list))
for key in spg_type:
if key != 'number' and key != 'arithmetic_crystal_class_number':
spg_type[key] = spg_type[key].strip()
return spg_type
else:
return None | [
"def",
"get_spacegroup_type",
"(",
"hall_number",
")",
":",
"_set_no_error",
"(",
")",
"keys",
"=",
"(",
"'number'",
",",
"'international_short'",
",",
"'international_full'",
",",
"'international'",
",",
"'schoenflies'",
",",
"'hall_symbol'",
",",
"'choice'",
",",
"'pointgroup_schoenflies'",
",",
"'pointgroup_international'",
",",
"'arithmetic_crystal_class_number'",
",",
"'arithmetic_crystal_class_symbol'",
")",
"spg_type_list",
"=",
"spg",
".",
"spacegroup_type",
"(",
"hall_number",
")",
"_set_error_message",
"(",
")",
"if",
"spg_type_list",
"is",
"not",
"None",
":",
"spg_type",
"=",
"dict",
"(",
"zip",
"(",
"keys",
",",
"spg_type_list",
")",
")",
"for",
"key",
"in",
"spg_type",
":",
"if",
"key",
"!=",
"'number'",
"and",
"key",
"!=",
"'arithmetic_crystal_class_number'",
":",
"spg_type",
"[",
"key",
"]",
"=",
"spg_type",
"[",
"key",
"]",
".",
"strip",
"(",
")",
"return",
"spg_type",
"else",
":",
"return",
"None"
] | Translate Hall number to space group type information.
If it fails, None is returned. | [
"Translate",
"Hall",
"number",
"to",
"space",
"group",
"type",
"information",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L270-L298 |
227,560 | atztogo/phonopy | phonopy/structure/spglib.py | get_pointgroup | def get_pointgroup(rotations):
"""Return point group in international table symbol and number.
The symbols are mapped to the numbers as follows:
1 "1 "
2 "-1 "
3 "2 "
4 "m "
5 "2/m "
6 "222 "
7 "mm2 "
8 "mmm "
9 "4 "
10 "-4 "
11 "4/m "
12 "422 "
13 "4mm "
14 "-42m "
15 "4/mmm"
16 "3 "
17 "-3 "
18 "32 "
19 "3m "
20 "-3m "
21 "6 "
22 "-6 "
23 "6/m "
24 "622 "
25 "6mm "
26 "-62m "
27 "6/mmm"
28 "23 "
29 "m-3 "
30 "432 "
31 "-43m "
32 "m-3m "
"""
_set_no_error()
# (symbol, pointgroup_number, transformation_matrix)
pointgroup = spg.pointgroup(np.array(rotations, dtype='intc', order='C'))
_set_error_message()
return pointgroup | python | def get_pointgroup(rotations):
"""Return point group in international table symbol and number.
The symbols are mapped to the numbers as follows:
1 "1 "
2 "-1 "
3 "2 "
4 "m "
5 "2/m "
6 "222 "
7 "mm2 "
8 "mmm "
9 "4 "
10 "-4 "
11 "4/m "
12 "422 "
13 "4mm "
14 "-42m "
15 "4/mmm"
16 "3 "
17 "-3 "
18 "32 "
19 "3m "
20 "-3m "
21 "6 "
22 "-6 "
23 "6/m "
24 "622 "
25 "6mm "
26 "-62m "
27 "6/mmm"
28 "23 "
29 "m-3 "
30 "432 "
31 "-43m "
32 "m-3m "
"""
_set_no_error()
# (symbol, pointgroup_number, transformation_matrix)
pointgroup = spg.pointgroup(np.array(rotations, dtype='intc', order='C'))
_set_error_message()
return pointgroup | [
"def",
"get_pointgroup",
"(",
"rotations",
")",
":",
"_set_no_error",
"(",
")",
"# (symbol, pointgroup_number, transformation_matrix)",
"pointgroup",
"=",
"spg",
".",
"pointgroup",
"(",
"np",
".",
"array",
"(",
"rotations",
",",
"dtype",
"=",
"'intc'",
",",
"order",
"=",
"'C'",
")",
")",
"_set_error_message",
"(",
")",
"return",
"pointgroup"
] | Return point group in international table symbol and number.
The symbols are mapped to the numbers as follows:
1 "1 "
2 "-1 "
3 "2 "
4 "m "
5 "2/m "
6 "222 "
7 "mm2 "
8 "mmm "
9 "4 "
10 "-4 "
11 "4/m "
12 "422 "
13 "4mm "
14 "-42m "
15 "4/mmm"
16 "3 "
17 "-3 "
18 "32 "
19 "3m "
20 "-3m "
21 "6 "
22 "-6 "
23 "6/m "
24 "622 "
25 "6mm "
26 "-62m "
27 "6/mmm"
28 "23 "
29 "m-3 "
30 "432 "
31 "-43m "
32 "m-3m " | [
"Return",
"point",
"group",
"in",
"international",
"table",
"symbol",
"and",
"number",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L301-L343 |
227,561 | atztogo/phonopy | phonopy/structure/spglib.py | standardize_cell | def standardize_cell(cell,
to_primitive=False,
no_idealize=False,
symprec=1e-5,
angle_tolerance=-1.0):
"""Return standardized cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
to_primitive:
bool: If True, the standardized primitive cell is created.
no_idealize:
bool: If True, it is disabled to idealize lengths and angles of
basis vectors and positions of atoms according to crystal
symmetry.
Return:
The standardized unit cell or primitive cell is returned by a tuple of
(lattice, positions, numbers).
If it fails, None is returned.
"""
_set_no_error()
lattice, _positions, _numbers, _ = _expand_cell(cell)
if lattice is None:
return None
# Atomic positions have to be specified by scaled positions for spglib.
num_atom = len(_positions)
positions = np.zeros((num_atom * 4, 3), dtype='double', order='C')
positions[:num_atom] = _positions
numbers = np.zeros(num_atom * 4, dtype='intc')
numbers[:num_atom] = _numbers
num_atom_std = spg.standardize_cell(lattice,
positions,
numbers,
num_atom,
to_primitive * 1,
no_idealize * 1,
symprec,
angle_tolerance)
_set_error_message()
if num_atom_std > 0:
return (np.array(lattice.T, dtype='double', order='C'),
np.array(positions[:num_atom_std], dtype='double', order='C'),
np.array(numbers[:num_atom_std], dtype='intc'))
else:
return None | python | def standardize_cell(cell,
to_primitive=False,
no_idealize=False,
symprec=1e-5,
angle_tolerance=-1.0):
"""Return standardized cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
to_primitive:
bool: If True, the standardized primitive cell is created.
no_idealize:
bool: If True, it is disabled to idealize lengths and angles of
basis vectors and positions of atoms according to crystal
symmetry.
Return:
The standardized unit cell or primitive cell is returned by a tuple of
(lattice, positions, numbers).
If it fails, None is returned.
"""
_set_no_error()
lattice, _positions, _numbers, _ = _expand_cell(cell)
if lattice is None:
return None
# Atomic positions have to be specified by scaled positions for spglib.
num_atom = len(_positions)
positions = np.zeros((num_atom * 4, 3), dtype='double', order='C')
positions[:num_atom] = _positions
numbers = np.zeros(num_atom * 4, dtype='intc')
numbers[:num_atom] = _numbers
num_atom_std = spg.standardize_cell(lattice,
positions,
numbers,
num_atom,
to_primitive * 1,
no_idealize * 1,
symprec,
angle_tolerance)
_set_error_message()
if num_atom_std > 0:
return (np.array(lattice.T, dtype='double', order='C'),
np.array(positions[:num_atom_std], dtype='double', order='C'),
np.array(numbers[:num_atom_std], dtype='intc'))
else:
return None | [
"def",
"standardize_cell",
"(",
"cell",
",",
"to_primitive",
"=",
"False",
",",
"no_idealize",
"=",
"False",
",",
"symprec",
"=",
"1e-5",
",",
"angle_tolerance",
"=",
"-",
"1.0",
")",
":",
"_set_no_error",
"(",
")",
"lattice",
",",
"_positions",
",",
"_numbers",
",",
"_",
"=",
"_expand_cell",
"(",
"cell",
")",
"if",
"lattice",
"is",
"None",
":",
"return",
"None",
"# Atomic positions have to be specified by scaled positions for spglib.",
"num_atom",
"=",
"len",
"(",
"_positions",
")",
"positions",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_atom",
"*",
"4",
",",
"3",
")",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"positions",
"[",
":",
"num_atom",
"]",
"=",
"_positions",
"numbers",
"=",
"np",
".",
"zeros",
"(",
"num_atom",
"*",
"4",
",",
"dtype",
"=",
"'intc'",
")",
"numbers",
"[",
":",
"num_atom",
"]",
"=",
"_numbers",
"num_atom_std",
"=",
"spg",
".",
"standardize_cell",
"(",
"lattice",
",",
"positions",
",",
"numbers",
",",
"num_atom",
",",
"to_primitive",
"*",
"1",
",",
"no_idealize",
"*",
"1",
",",
"symprec",
",",
"angle_tolerance",
")",
"_set_error_message",
"(",
")",
"if",
"num_atom_std",
">",
"0",
":",
"return",
"(",
"np",
".",
"array",
"(",
"lattice",
".",
"T",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
",",
"np",
".",
"array",
"(",
"positions",
"[",
":",
"num_atom_std",
"]",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
",",
"np",
".",
"array",
"(",
"numbers",
"[",
":",
"num_atom_std",
"]",
",",
"dtype",
"=",
"'intc'",
")",
")",
"else",
":",
"return",
"None"
] | Return standardized cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
to_primitive:
bool: If True, the standardized primitive cell is created.
no_idealize:
bool: If True, it is disabled to idealize lengths and angles of
basis vectors and positions of atoms according to crystal
symmetry.
Return:
The standardized unit cell or primitive cell is returned by a tuple of
(lattice, positions, numbers).
If it fails, None is returned. | [
"Return",
"standardized",
"cell",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L346-L394 |
227,562 | atztogo/phonopy | phonopy/structure/spglib.py | find_primitive | def find_primitive(cell, symprec=1e-5, angle_tolerance=-1.0):
"""Primitive cell is searched in the input cell.
The primitive cell is returned by a tuple of (lattice, positions, numbers).
If it fails, None is returned.
"""
_set_no_error()
lattice, positions, numbers, _ = _expand_cell(cell)
if lattice is None:
return None
num_atom_prim = spg.primitive(lattice,
positions,
numbers,
symprec,
angle_tolerance)
_set_error_message()
if num_atom_prim > 0:
return (np.array(lattice.T, dtype='double', order='C'),
np.array(positions[:num_atom_prim], dtype='double', order='C'),
np.array(numbers[:num_atom_prim], dtype='intc'))
else:
return None | python | def find_primitive(cell, symprec=1e-5, angle_tolerance=-1.0):
"""Primitive cell is searched in the input cell.
The primitive cell is returned by a tuple of (lattice, positions, numbers).
If it fails, None is returned.
"""
_set_no_error()
lattice, positions, numbers, _ = _expand_cell(cell)
if lattice is None:
return None
num_atom_prim = spg.primitive(lattice,
positions,
numbers,
symprec,
angle_tolerance)
_set_error_message()
if num_atom_prim > 0:
return (np.array(lattice.T, dtype='double', order='C'),
np.array(positions[:num_atom_prim], dtype='double', order='C'),
np.array(numbers[:num_atom_prim], dtype='intc'))
else:
return None | [
"def",
"find_primitive",
"(",
"cell",
",",
"symprec",
"=",
"1e-5",
",",
"angle_tolerance",
"=",
"-",
"1.0",
")",
":",
"_set_no_error",
"(",
")",
"lattice",
",",
"positions",
",",
"numbers",
",",
"_",
"=",
"_expand_cell",
"(",
"cell",
")",
"if",
"lattice",
"is",
"None",
":",
"return",
"None",
"num_atom_prim",
"=",
"spg",
".",
"primitive",
"(",
"lattice",
",",
"positions",
",",
"numbers",
",",
"symprec",
",",
"angle_tolerance",
")",
"_set_error_message",
"(",
")",
"if",
"num_atom_prim",
">",
"0",
":",
"return",
"(",
"np",
".",
"array",
"(",
"lattice",
".",
"T",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
",",
"np",
".",
"array",
"(",
"positions",
"[",
":",
"num_atom_prim",
"]",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
",",
"np",
".",
"array",
"(",
"numbers",
"[",
":",
"num_atom_prim",
"]",
",",
"dtype",
"=",
"'intc'",
")",
")",
"else",
":",
"return",
"None"
] | Primitive cell is searched in the input cell.
The primitive cell is returned by a tuple of (lattice, positions, numbers).
If it fails, None is returned. | [
"Primitive",
"cell",
"is",
"searched",
"in",
"the",
"input",
"cell",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L432-L456 |
227,563 | atztogo/phonopy | phonopy/structure/spglib.py | get_symmetry_from_database | def get_symmetry_from_database(hall_number):
"""Return symmetry operations corresponding to a Hall symbol.
The Hall symbol is given by the serial number in between 1 and 530.
The symmetry operations are given by a dictionary whose keys are
'rotations' and 'translations'.
If it fails, None is returned.
"""
_set_no_error()
rotations = np.zeros((192, 3, 3), dtype='intc')
translations = np.zeros((192, 3), dtype='double')
num_sym = spg.symmetry_from_database(rotations, translations, hall_number)
_set_error_message()
if num_sym is None:
return None
else:
return {'rotations':
np.array(rotations[:num_sym], dtype='intc', order='C'),
'translations':
np.array(translations[:num_sym], dtype='double', order='C')} | python | def get_symmetry_from_database(hall_number):
"""Return symmetry operations corresponding to a Hall symbol.
The Hall symbol is given by the serial number in between 1 and 530.
The symmetry operations are given by a dictionary whose keys are
'rotations' and 'translations'.
If it fails, None is returned.
"""
_set_no_error()
rotations = np.zeros((192, 3, 3), dtype='intc')
translations = np.zeros((192, 3), dtype='double')
num_sym = spg.symmetry_from_database(rotations, translations, hall_number)
_set_error_message()
if num_sym is None:
return None
else:
return {'rotations':
np.array(rotations[:num_sym], dtype='intc', order='C'),
'translations':
np.array(translations[:num_sym], dtype='double', order='C')} | [
"def",
"get_symmetry_from_database",
"(",
"hall_number",
")",
":",
"_set_no_error",
"(",
")",
"rotations",
"=",
"np",
".",
"zeros",
"(",
"(",
"192",
",",
"3",
",",
"3",
")",
",",
"dtype",
"=",
"'intc'",
")",
"translations",
"=",
"np",
".",
"zeros",
"(",
"(",
"192",
",",
"3",
")",
",",
"dtype",
"=",
"'double'",
")",
"num_sym",
"=",
"spg",
".",
"symmetry_from_database",
"(",
"rotations",
",",
"translations",
",",
"hall_number",
")",
"_set_error_message",
"(",
")",
"if",
"num_sym",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",
"{",
"'rotations'",
":",
"np",
".",
"array",
"(",
"rotations",
"[",
":",
"num_sym",
"]",
",",
"dtype",
"=",
"'intc'",
",",
"order",
"=",
"'C'",
")",
",",
"'translations'",
":",
"np",
".",
"array",
"(",
"translations",
"[",
":",
"num_sym",
"]",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"}"
] | Return symmetry operations corresponding to a Hall symbol.
The Hall symbol is given by the serial number in between 1 and 530.
The symmetry operations are given by a dictionary whose keys are
'rotations' and 'translations'.
If it fails, None is returned. | [
"Return",
"symmetry",
"operations",
"corresponding",
"to",
"a",
"Hall",
"symbol",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L459-L480 |
227,564 | atztogo/phonopy | phonopy/structure/spglib.py | get_grid_point_from_address | def get_grid_point_from_address(grid_address, mesh):
"""Return grid point index by tranlating grid address"""
_set_no_error()
return spg.grid_point_from_address(np.array(grid_address, dtype='intc'),
np.array(mesh, dtype='intc')) | python | def get_grid_point_from_address(grid_address, mesh):
"""Return grid point index by tranlating grid address"""
_set_no_error()
return spg.grid_point_from_address(np.array(grid_address, dtype='intc'),
np.array(mesh, dtype='intc')) | [
"def",
"get_grid_point_from_address",
"(",
"grid_address",
",",
"mesh",
")",
":",
"_set_no_error",
"(",
")",
"return",
"spg",
".",
"grid_point_from_address",
"(",
"np",
".",
"array",
"(",
"grid_address",
",",
"dtype",
"=",
"'intc'",
")",
",",
"np",
".",
"array",
"(",
"mesh",
",",
"dtype",
"=",
"'intc'",
")",
")"
] | Return grid point index by tranlating grid address | [
"Return",
"grid",
"point",
"index",
"by",
"tranlating",
"grid",
"address"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L486-L491 |
227,565 | atztogo/phonopy | phonopy/structure/spglib.py | get_ir_reciprocal_mesh | def get_ir_reciprocal_mesh(mesh,
cell,
is_shift=None,
is_time_reversal=True,
symprec=1e-5,
is_dense=False):
"""Return k-points mesh and k-point map to the irreducible k-points.
The symmetry is serched from the input cell.
Parameters
----------
mesh : array_like
Uniform sampling mesh numbers.
dtype='intc', shape=(3,)
cell : spglib cell tuple
Crystal structure.
is_shift : array_like, optional
[0, 0, 0] gives Gamma center mesh and value 1 gives half mesh shift.
Default is None which equals to [0, 0, 0].
dtype='intc', shape=(3,)
is_time_reversal : bool, optional
Whether time reversal symmetry is included or not. Default is True.
symprec : float, optional
Symmetry tolerance in distance. Default is 1e-5.
is_dense : bool, optional
grid_mapping_table is returned with dtype='uintp' if True. Otherwise
its dtype='intc'. Default is False.
Returns
-------
grid_mapping_table : ndarray
Grid point mapping table to ir-gird-points.
dtype='intc' or 'uintp', shape=(prod(mesh),)
grid_address : ndarray
Address of all grid points.
dtype='intc', shspe=(prod(mesh), 3)
"""
_set_no_error()
lattice, positions, numbers, _ = _expand_cell(cell)
if lattice is None:
return None
if is_dense:
dtype = 'uintp'
else:
dtype = 'intc'
grid_mapping_table = np.zeros(np.prod(mesh), dtype=dtype)
grid_address = np.zeros((np.prod(mesh), 3), dtype='intc')
if is_shift is None:
is_shift = [0, 0, 0]
if spg.ir_reciprocal_mesh(
grid_address,
grid_mapping_table,
np.array(mesh, dtype='intc'),
np.array(is_shift, dtype='intc'),
is_time_reversal * 1,
lattice,
positions,
numbers,
symprec) > 0:
return grid_mapping_table, grid_address
else:
return None | python | def get_ir_reciprocal_mesh(mesh,
cell,
is_shift=None,
is_time_reversal=True,
symprec=1e-5,
is_dense=False):
"""Return k-points mesh and k-point map to the irreducible k-points.
The symmetry is serched from the input cell.
Parameters
----------
mesh : array_like
Uniform sampling mesh numbers.
dtype='intc', shape=(3,)
cell : spglib cell tuple
Crystal structure.
is_shift : array_like, optional
[0, 0, 0] gives Gamma center mesh and value 1 gives half mesh shift.
Default is None which equals to [0, 0, 0].
dtype='intc', shape=(3,)
is_time_reversal : bool, optional
Whether time reversal symmetry is included or not. Default is True.
symprec : float, optional
Symmetry tolerance in distance. Default is 1e-5.
is_dense : bool, optional
grid_mapping_table is returned with dtype='uintp' if True. Otherwise
its dtype='intc'. Default is False.
Returns
-------
grid_mapping_table : ndarray
Grid point mapping table to ir-gird-points.
dtype='intc' or 'uintp', shape=(prod(mesh),)
grid_address : ndarray
Address of all grid points.
dtype='intc', shspe=(prod(mesh), 3)
"""
_set_no_error()
lattice, positions, numbers, _ = _expand_cell(cell)
if lattice is None:
return None
if is_dense:
dtype = 'uintp'
else:
dtype = 'intc'
grid_mapping_table = np.zeros(np.prod(mesh), dtype=dtype)
grid_address = np.zeros((np.prod(mesh), 3), dtype='intc')
if is_shift is None:
is_shift = [0, 0, 0]
if spg.ir_reciprocal_mesh(
grid_address,
grid_mapping_table,
np.array(mesh, dtype='intc'),
np.array(is_shift, dtype='intc'),
is_time_reversal * 1,
lattice,
positions,
numbers,
symprec) > 0:
return grid_mapping_table, grid_address
else:
return None | [
"def",
"get_ir_reciprocal_mesh",
"(",
"mesh",
",",
"cell",
",",
"is_shift",
"=",
"None",
",",
"is_time_reversal",
"=",
"True",
",",
"symprec",
"=",
"1e-5",
",",
"is_dense",
"=",
"False",
")",
":",
"_set_no_error",
"(",
")",
"lattice",
",",
"positions",
",",
"numbers",
",",
"_",
"=",
"_expand_cell",
"(",
"cell",
")",
"if",
"lattice",
"is",
"None",
":",
"return",
"None",
"if",
"is_dense",
":",
"dtype",
"=",
"'uintp'",
"else",
":",
"dtype",
"=",
"'intc'",
"grid_mapping_table",
"=",
"np",
".",
"zeros",
"(",
"np",
".",
"prod",
"(",
"mesh",
")",
",",
"dtype",
"=",
"dtype",
")",
"grid_address",
"=",
"np",
".",
"zeros",
"(",
"(",
"np",
".",
"prod",
"(",
"mesh",
")",
",",
"3",
")",
",",
"dtype",
"=",
"'intc'",
")",
"if",
"is_shift",
"is",
"None",
":",
"is_shift",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
"if",
"spg",
".",
"ir_reciprocal_mesh",
"(",
"grid_address",
",",
"grid_mapping_table",
",",
"np",
".",
"array",
"(",
"mesh",
",",
"dtype",
"=",
"'intc'",
")",
",",
"np",
".",
"array",
"(",
"is_shift",
",",
"dtype",
"=",
"'intc'",
")",
",",
"is_time_reversal",
"*",
"1",
",",
"lattice",
",",
"positions",
",",
"numbers",
",",
"symprec",
")",
">",
"0",
":",
"return",
"grid_mapping_table",
",",
"grid_address",
"else",
":",
"return",
"None"
] | Return k-points mesh and k-point map to the irreducible k-points.
The symmetry is serched from the input cell.
Parameters
----------
mesh : array_like
Uniform sampling mesh numbers.
dtype='intc', shape=(3,)
cell : spglib cell tuple
Crystal structure.
is_shift : array_like, optional
[0, 0, 0] gives Gamma center mesh and value 1 gives half mesh shift.
Default is None which equals to [0, 0, 0].
dtype='intc', shape=(3,)
is_time_reversal : bool, optional
Whether time reversal symmetry is included or not. Default is True.
symprec : float, optional
Symmetry tolerance in distance. Default is 1e-5.
is_dense : bool, optional
grid_mapping_table is returned with dtype='uintp' if True. Otherwise
its dtype='intc'. Default is False.
Returns
-------
grid_mapping_table : ndarray
Grid point mapping table to ir-gird-points.
dtype='intc' or 'uintp', shape=(prod(mesh),)
grid_address : ndarray
Address of all grid points.
dtype='intc', shspe=(prod(mesh), 3) | [
"Return",
"k",
"-",
"points",
"mesh",
"and",
"k",
"-",
"point",
"map",
"to",
"the",
"irreducible",
"k",
"-",
"points",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L494-L559 |
227,566 | atztogo/phonopy | phonopy/structure/spglib.py | get_stabilized_reciprocal_mesh | def get_stabilized_reciprocal_mesh(mesh,
rotations,
is_shift=None,
is_time_reversal=True,
qpoints=None,
is_dense=False):
"""Return k-point map to the irreducible k-points and k-point grid points.
The symmetry is searched from the input rotation matrices in real space.
Parameters
----------
mesh : array_like
Uniform sampling mesh numbers.
dtype='intc', shape=(3,)
rotations : array_like
Rotation matrices with respect to real space basis vectors.
dtype='intc', shape=(rotations, 3)
is_shift : array_like
[0, 0, 0] gives Gamma center mesh and value 1 gives half mesh shift.
dtype='intc', shape=(3,)
is_time_reversal : bool
Time reversal symmetry is included or not.
qpoints : array_like
q-points used as stabilizer(s) given in reciprocal space with respect
to reciprocal basis vectors.
dtype='double', shape=(qpoints ,3) or (3,)
is_dense : bool, optional
grid_mapping_table is returned with dtype='uintp' if True. Otherwise
its dtype='intc'. Default is False.
Returns
-------
grid_mapping_table : ndarray
Grid point mapping table to ir-gird-points.
dtype='intc', shape=(prod(mesh),)
grid_address : ndarray
Address of all grid points. Each address is given by three unsigned
integers.
dtype='intc', shape=(prod(mesh), 3)
"""
_set_no_error()
if is_dense:
dtype = 'uintp'
else:
dtype = 'intc'
mapping_table = np.zeros(np.prod(mesh), dtype=dtype)
grid_address = np.zeros((np.prod(mesh), 3), dtype='intc')
if is_shift is None:
is_shift = [0, 0, 0]
if qpoints is None:
qpoints = np.array([[0, 0, 0]], dtype='double', order='C')
else:
qpoints = np.array(qpoints, dtype='double', order='C')
if qpoints.shape == (3,):
qpoints = np.array([qpoints], dtype='double', order='C')
if spg.stabilized_reciprocal_mesh(
grid_address,
mapping_table,
np.array(mesh, dtype='intc'),
np.array(is_shift, dtype='intc'),
is_time_reversal * 1,
np.array(rotations, dtype='intc', order='C'),
qpoints) > 0:
return mapping_table, grid_address
else:
return None | python | def get_stabilized_reciprocal_mesh(mesh,
rotations,
is_shift=None,
is_time_reversal=True,
qpoints=None,
is_dense=False):
"""Return k-point map to the irreducible k-points and k-point grid points.
The symmetry is searched from the input rotation matrices in real space.
Parameters
----------
mesh : array_like
Uniform sampling mesh numbers.
dtype='intc', shape=(3,)
rotations : array_like
Rotation matrices with respect to real space basis vectors.
dtype='intc', shape=(rotations, 3)
is_shift : array_like
[0, 0, 0] gives Gamma center mesh and value 1 gives half mesh shift.
dtype='intc', shape=(3,)
is_time_reversal : bool
Time reversal symmetry is included or not.
qpoints : array_like
q-points used as stabilizer(s) given in reciprocal space with respect
to reciprocal basis vectors.
dtype='double', shape=(qpoints ,3) or (3,)
is_dense : bool, optional
grid_mapping_table is returned with dtype='uintp' if True. Otherwise
its dtype='intc'. Default is False.
Returns
-------
grid_mapping_table : ndarray
Grid point mapping table to ir-gird-points.
dtype='intc', shape=(prod(mesh),)
grid_address : ndarray
Address of all grid points. Each address is given by three unsigned
integers.
dtype='intc', shape=(prod(mesh), 3)
"""
_set_no_error()
if is_dense:
dtype = 'uintp'
else:
dtype = 'intc'
mapping_table = np.zeros(np.prod(mesh), dtype=dtype)
grid_address = np.zeros((np.prod(mesh), 3), dtype='intc')
if is_shift is None:
is_shift = [0, 0, 0]
if qpoints is None:
qpoints = np.array([[0, 0, 0]], dtype='double', order='C')
else:
qpoints = np.array(qpoints, dtype='double', order='C')
if qpoints.shape == (3,):
qpoints = np.array([qpoints], dtype='double', order='C')
if spg.stabilized_reciprocal_mesh(
grid_address,
mapping_table,
np.array(mesh, dtype='intc'),
np.array(is_shift, dtype='intc'),
is_time_reversal * 1,
np.array(rotations, dtype='intc', order='C'),
qpoints) > 0:
return mapping_table, grid_address
else:
return None | [
"def",
"get_stabilized_reciprocal_mesh",
"(",
"mesh",
",",
"rotations",
",",
"is_shift",
"=",
"None",
",",
"is_time_reversal",
"=",
"True",
",",
"qpoints",
"=",
"None",
",",
"is_dense",
"=",
"False",
")",
":",
"_set_no_error",
"(",
")",
"if",
"is_dense",
":",
"dtype",
"=",
"'uintp'",
"else",
":",
"dtype",
"=",
"'intc'",
"mapping_table",
"=",
"np",
".",
"zeros",
"(",
"np",
".",
"prod",
"(",
"mesh",
")",
",",
"dtype",
"=",
"dtype",
")",
"grid_address",
"=",
"np",
".",
"zeros",
"(",
"(",
"np",
".",
"prod",
"(",
"mesh",
")",
",",
"3",
")",
",",
"dtype",
"=",
"'intc'",
")",
"if",
"is_shift",
"is",
"None",
":",
"is_shift",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
"if",
"qpoints",
"is",
"None",
":",
"qpoints",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"0",
",",
"0",
",",
"0",
"]",
"]",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"else",
":",
"qpoints",
"=",
"np",
".",
"array",
"(",
"qpoints",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"if",
"qpoints",
".",
"shape",
"==",
"(",
"3",
",",
")",
":",
"qpoints",
"=",
"np",
".",
"array",
"(",
"[",
"qpoints",
"]",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"if",
"spg",
".",
"stabilized_reciprocal_mesh",
"(",
"grid_address",
",",
"mapping_table",
",",
"np",
".",
"array",
"(",
"mesh",
",",
"dtype",
"=",
"'intc'",
")",
",",
"np",
".",
"array",
"(",
"is_shift",
",",
"dtype",
"=",
"'intc'",
")",
",",
"is_time_reversal",
"*",
"1",
",",
"np",
".",
"array",
"(",
"rotations",
",",
"dtype",
"=",
"'intc'",
",",
"order",
"=",
"'C'",
")",
",",
"qpoints",
")",
">",
"0",
":",
"return",
"mapping_table",
",",
"grid_address",
"else",
":",
"return",
"None"
] | Return k-point map to the irreducible k-points and k-point grid points.
The symmetry is searched from the input rotation matrices in real space.
Parameters
----------
mesh : array_like
Uniform sampling mesh numbers.
dtype='intc', shape=(3,)
rotations : array_like
Rotation matrices with respect to real space basis vectors.
dtype='intc', shape=(rotations, 3)
is_shift : array_like
[0, 0, 0] gives Gamma center mesh and value 1 gives half mesh shift.
dtype='intc', shape=(3,)
is_time_reversal : bool
Time reversal symmetry is included or not.
qpoints : array_like
q-points used as stabilizer(s) given in reciprocal space with respect
to reciprocal basis vectors.
dtype='double', shape=(qpoints ,3) or (3,)
is_dense : bool, optional
grid_mapping_table is returned with dtype='uintp' if True. Otherwise
its dtype='intc'. Default is False.
Returns
-------
grid_mapping_table : ndarray
Grid point mapping table to ir-gird-points.
dtype='intc', shape=(prod(mesh),)
grid_address : ndarray
Address of all grid points. Each address is given by three unsigned
integers.
dtype='intc', shape=(prod(mesh), 3) | [
"Return",
"k",
"-",
"point",
"map",
"to",
"the",
"irreducible",
"k",
"-",
"points",
"and",
"k",
"-",
"point",
"grid",
"points",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L562-L631 |
227,567 | atztogo/phonopy | phonopy/structure/spglib.py | relocate_BZ_grid_address | def relocate_BZ_grid_address(grid_address,
mesh,
reciprocal_lattice, # column vectors
is_shift=None,
is_dense=False):
"""Grid addresses are relocated to be inside first Brillouin zone.
Number of ir-grid-points inside Brillouin zone is returned.
It is assumed that the following arrays have the shapes of
bz_grid_address : (num_grid_points_in_FBZ, 3)
bz_map (prod(mesh * 2), )
Note that the shape of grid_address is (prod(mesh), 3) and the
addresses in grid_address are arranged to be in parallelepiped
made of reciprocal basis vectors. The addresses in bz_grid_address
are inside the first Brillouin zone or on its surface. Each
address in grid_address is mapped to one of those in
bz_grid_address by a reciprocal lattice vector (including zero
vector) with keeping element order. For those inside first
Brillouin zone, the mapping is one-to-one. For those on the first
Brillouin zone surface, more than one addresses in bz_grid_address
that are equivalent by the reciprocal lattice translations are
mapped to one address in grid_address. In this case, those grid
points except for one of them are appended to the tail of this array,
for which bz_grid_address has the following data storing:
|------------------array size of bz_grid_address-------------------------|
|--those equivalent to grid_address--|--those on surface except for one--|
|-----array size of grid_address-----|
Number of grid points stored in bz_grid_address is returned.
bz_map is used to recover grid point index expanded to include BZ
surface from grid address. The grid point indices are mapped to
(mesh[0] * 2) x (mesh[1] * 2) x (mesh[2] * 2) space (bz_map).
"""
_set_no_error()
if is_shift is None:
_is_shift = np.zeros(3, dtype='intc')
else:
_is_shift = np.array(is_shift, dtype='intc')
bz_grid_address = np.zeros((np.prod(np.add(mesh, 1)), 3), dtype='intc')
bz_map = np.zeros(np.prod(np.multiply(mesh, 2)), dtype='uintp')
num_bz_ir = spg.BZ_grid_address(
bz_grid_address,
bz_map,
grid_address,
np.array(mesh, dtype='intc'),
np.array(reciprocal_lattice, dtype='double', order='C'),
_is_shift)
if is_dense:
return bz_grid_address[:num_bz_ir], bz_map
else:
return bz_grid_address[:num_bz_ir], np.array(bz_map, dtype='intc') | python | def relocate_BZ_grid_address(grid_address,
mesh,
reciprocal_lattice, # column vectors
is_shift=None,
is_dense=False):
"""Grid addresses are relocated to be inside first Brillouin zone.
Number of ir-grid-points inside Brillouin zone is returned.
It is assumed that the following arrays have the shapes of
bz_grid_address : (num_grid_points_in_FBZ, 3)
bz_map (prod(mesh * 2), )
Note that the shape of grid_address is (prod(mesh), 3) and the
addresses in grid_address are arranged to be in parallelepiped
made of reciprocal basis vectors. The addresses in bz_grid_address
are inside the first Brillouin zone or on its surface. Each
address in grid_address is mapped to one of those in
bz_grid_address by a reciprocal lattice vector (including zero
vector) with keeping element order. For those inside first
Brillouin zone, the mapping is one-to-one. For those on the first
Brillouin zone surface, more than one addresses in bz_grid_address
that are equivalent by the reciprocal lattice translations are
mapped to one address in grid_address. In this case, those grid
points except for one of them are appended to the tail of this array,
for which bz_grid_address has the following data storing:
|------------------array size of bz_grid_address-------------------------|
|--those equivalent to grid_address--|--those on surface except for one--|
|-----array size of grid_address-----|
Number of grid points stored in bz_grid_address is returned.
bz_map is used to recover grid point index expanded to include BZ
surface from grid address. The grid point indices are mapped to
(mesh[0] * 2) x (mesh[1] * 2) x (mesh[2] * 2) space (bz_map).
"""
_set_no_error()
if is_shift is None:
_is_shift = np.zeros(3, dtype='intc')
else:
_is_shift = np.array(is_shift, dtype='intc')
bz_grid_address = np.zeros((np.prod(np.add(mesh, 1)), 3), dtype='intc')
bz_map = np.zeros(np.prod(np.multiply(mesh, 2)), dtype='uintp')
num_bz_ir = spg.BZ_grid_address(
bz_grid_address,
bz_map,
grid_address,
np.array(mesh, dtype='intc'),
np.array(reciprocal_lattice, dtype='double', order='C'),
_is_shift)
if is_dense:
return bz_grid_address[:num_bz_ir], bz_map
else:
return bz_grid_address[:num_bz_ir], np.array(bz_map, dtype='intc') | [
"def",
"relocate_BZ_grid_address",
"(",
"grid_address",
",",
"mesh",
",",
"reciprocal_lattice",
",",
"# column vectors",
"is_shift",
"=",
"None",
",",
"is_dense",
"=",
"False",
")",
":",
"_set_no_error",
"(",
")",
"if",
"is_shift",
"is",
"None",
":",
"_is_shift",
"=",
"np",
".",
"zeros",
"(",
"3",
",",
"dtype",
"=",
"'intc'",
")",
"else",
":",
"_is_shift",
"=",
"np",
".",
"array",
"(",
"is_shift",
",",
"dtype",
"=",
"'intc'",
")",
"bz_grid_address",
"=",
"np",
".",
"zeros",
"(",
"(",
"np",
".",
"prod",
"(",
"np",
".",
"add",
"(",
"mesh",
",",
"1",
")",
")",
",",
"3",
")",
",",
"dtype",
"=",
"'intc'",
")",
"bz_map",
"=",
"np",
".",
"zeros",
"(",
"np",
".",
"prod",
"(",
"np",
".",
"multiply",
"(",
"mesh",
",",
"2",
")",
")",
",",
"dtype",
"=",
"'uintp'",
")",
"num_bz_ir",
"=",
"spg",
".",
"BZ_grid_address",
"(",
"bz_grid_address",
",",
"bz_map",
",",
"grid_address",
",",
"np",
".",
"array",
"(",
"mesh",
",",
"dtype",
"=",
"'intc'",
")",
",",
"np",
".",
"array",
"(",
"reciprocal_lattice",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
",",
"_is_shift",
")",
"if",
"is_dense",
":",
"return",
"bz_grid_address",
"[",
":",
"num_bz_ir",
"]",
",",
"bz_map",
"else",
":",
"return",
"bz_grid_address",
"[",
":",
"num_bz_ir",
"]",
",",
"np",
".",
"array",
"(",
"bz_map",
",",
"dtype",
"=",
"'intc'",
")"
] | Grid addresses are relocated to be inside first Brillouin zone.
Number of ir-grid-points inside Brillouin zone is returned.
It is assumed that the following arrays have the shapes of
bz_grid_address : (num_grid_points_in_FBZ, 3)
bz_map (prod(mesh * 2), )
Note that the shape of grid_address is (prod(mesh), 3) and the
addresses in grid_address are arranged to be in parallelepiped
made of reciprocal basis vectors. The addresses in bz_grid_address
are inside the first Brillouin zone or on its surface. Each
address in grid_address is mapped to one of those in
bz_grid_address by a reciprocal lattice vector (including zero
vector) with keeping element order. For those inside first
Brillouin zone, the mapping is one-to-one. For those on the first
Brillouin zone surface, more than one addresses in bz_grid_address
that are equivalent by the reciprocal lattice translations are
mapped to one address in grid_address. In this case, those grid
points except for one of them are appended to the tail of this array,
for which bz_grid_address has the following data storing:
|------------------array size of bz_grid_address-------------------------|
|--those equivalent to grid_address--|--those on surface except for one--|
|-----array size of grid_address-----|
Number of grid points stored in bz_grid_address is returned.
bz_map is used to recover grid point index expanded to include BZ
surface from grid address. The grid point indices are mapped to
(mesh[0] * 2) x (mesh[1] * 2) x (mesh[2] * 2) space (bz_map). | [
"Grid",
"addresses",
"are",
"relocated",
"to",
"be",
"inside",
"first",
"Brillouin",
"zone",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L751-L806 |
227,568 | atztogo/phonopy | phonopy/structure/spglib.py | delaunay_reduce | def delaunay_reduce(lattice, eps=1e-5):
"""Run Delaunay reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
symprec:
float: Tolerance to check if volume is close to zero or not and
if two basis vectors are orthogonal by the value of dot
product being close to zero or not.
Returns:
if the Delaunay reduction succeeded:
Reduced lattice parameters are given as a numpy 'double' array:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
otherwise None is returned.
"""
_set_no_error()
delaunay_lattice = np.array(np.transpose(lattice),
dtype='double', order='C')
result = spg.delaunay_reduce(delaunay_lattice, float(eps))
_set_error_message()
if result == 0:
return None
else:
return np.array(np.transpose(delaunay_lattice),
dtype='double', order='C') | python | def delaunay_reduce(lattice, eps=1e-5):
"""Run Delaunay reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
symprec:
float: Tolerance to check if volume is close to zero or not and
if two basis vectors are orthogonal by the value of dot
product being close to zero or not.
Returns:
if the Delaunay reduction succeeded:
Reduced lattice parameters are given as a numpy 'double' array:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
otherwise None is returned.
"""
_set_no_error()
delaunay_lattice = np.array(np.transpose(lattice),
dtype='double', order='C')
result = spg.delaunay_reduce(delaunay_lattice, float(eps))
_set_error_message()
if result == 0:
return None
else:
return np.array(np.transpose(delaunay_lattice),
dtype='double', order='C') | [
"def",
"delaunay_reduce",
"(",
"lattice",
",",
"eps",
"=",
"1e-5",
")",
":",
"_set_no_error",
"(",
")",
"delaunay_lattice",
"=",
"np",
".",
"array",
"(",
"np",
".",
"transpose",
"(",
"lattice",
")",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"result",
"=",
"spg",
".",
"delaunay_reduce",
"(",
"delaunay_lattice",
",",
"float",
"(",
"eps",
")",
")",
"_set_error_message",
"(",
")",
"if",
"result",
"==",
"0",
":",
"return",
"None",
"else",
":",
"return",
"np",
".",
"array",
"(",
"np",
".",
"transpose",
"(",
"delaunay_lattice",
")",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")"
] | Run Delaunay reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
symprec:
float: Tolerance to check if volume is close to zero or not and
if two basis vectors are orthogonal by the value of dot
product being close to zero or not.
Returns:
if the Delaunay reduction succeeded:
Reduced lattice parameters are given as a numpy 'double' array:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
otherwise None is returned. | [
"Run",
"Delaunay",
"reduction"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L809-L841 |
227,569 | atztogo/phonopy | phonopy/structure/spglib.py | niggli_reduce | def niggli_reduce(lattice, eps=1e-5):
"""Run Niggli reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
eps:
float: Tolerance to check if difference of norms of two basis
vectors is close to zero or not and if two basis vectors are
orthogonal by the value of dot product being close to zero or
not. The detail is shown at
https://atztogo.github.io/niggli/.
Returns:
if the Niggli reduction succeeded:
Reduced lattice parameters are given as a numpy 'double' array:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
otherwise None is returned.
"""
_set_no_error()
niggli_lattice = np.array(np.transpose(lattice), dtype='double', order='C')
result = spg.niggli_reduce(niggli_lattice, float(eps))
_set_error_message()
if result == 0:
return None
else:
return np.array(np.transpose(niggli_lattice),
dtype='double', order='C') | python | def niggli_reduce(lattice, eps=1e-5):
"""Run Niggli reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
eps:
float: Tolerance to check if difference of norms of two basis
vectors is close to zero or not and if two basis vectors are
orthogonal by the value of dot product being close to zero or
not. The detail is shown at
https://atztogo.github.io/niggli/.
Returns:
if the Niggli reduction succeeded:
Reduced lattice parameters are given as a numpy 'double' array:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
otherwise None is returned.
"""
_set_no_error()
niggli_lattice = np.array(np.transpose(lattice), dtype='double', order='C')
result = spg.niggli_reduce(niggli_lattice, float(eps))
_set_error_message()
if result == 0:
return None
else:
return np.array(np.transpose(niggli_lattice),
dtype='double', order='C') | [
"def",
"niggli_reduce",
"(",
"lattice",
",",
"eps",
"=",
"1e-5",
")",
":",
"_set_no_error",
"(",
")",
"niggli_lattice",
"=",
"np",
".",
"array",
"(",
"np",
".",
"transpose",
"(",
"lattice",
")",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"result",
"=",
"spg",
".",
"niggli_reduce",
"(",
"niggli_lattice",
",",
"float",
"(",
"eps",
")",
")",
"_set_error_message",
"(",
")",
"if",
"result",
"==",
"0",
":",
"return",
"None",
"else",
":",
"return",
"np",
".",
"array",
"(",
"np",
".",
"transpose",
"(",
"niggli_lattice",
")",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")"
] | Run Niggli reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
eps:
float: Tolerance to check if difference of norms of two basis
vectors is close to zero or not and if two basis vectors are
orthogonal by the value of dot product being close to zero or
not. The detail is shown at
https://atztogo.github.io/niggli/.
Returns:
if the Niggli reduction succeeded:
Reduced lattice parameters are given as a numpy 'double' array:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
otherwise None is returned. | [
"Run",
"Niggli",
"reduction"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L844-L877 |
227,570 | atztogo/phonopy | phonopy/file_IO.py | get_FORCE_SETS_lines | def get_FORCE_SETS_lines(dataset, forces=None):
"""Generate FORCE_SETS string
See the format of dataset in the docstring of
Phonopy.set_displacement_dataset. Optionally for the type-1 (traditional)
format, forces can be given. In this case, sets of forces are
unnecessary to be stored in the dataset.
"""
if 'first_atoms' in dataset:
return _get_FORCE_SETS_lines_type1(dataset, forces=forces)
elif 'forces' in dataset:
return _get_FORCE_SETS_lines_type2(dataset) | python | def get_FORCE_SETS_lines(dataset, forces=None):
"""Generate FORCE_SETS string
See the format of dataset in the docstring of
Phonopy.set_displacement_dataset. Optionally for the type-1 (traditional)
format, forces can be given. In this case, sets of forces are
unnecessary to be stored in the dataset.
"""
if 'first_atoms' in dataset:
return _get_FORCE_SETS_lines_type1(dataset, forces=forces)
elif 'forces' in dataset:
return _get_FORCE_SETS_lines_type2(dataset) | [
"def",
"get_FORCE_SETS_lines",
"(",
"dataset",
",",
"forces",
"=",
"None",
")",
":",
"if",
"'first_atoms'",
"in",
"dataset",
":",
"return",
"_get_FORCE_SETS_lines_type1",
"(",
"dataset",
",",
"forces",
"=",
"forces",
")",
"elif",
"'forces'",
"in",
"dataset",
":",
"return",
"_get_FORCE_SETS_lines_type2",
"(",
"dataset",
")"
] | Generate FORCE_SETS string
See the format of dataset in the docstring of
Phonopy.set_displacement_dataset. Optionally for the type-1 (traditional)
format, forces can be given. In this case, sets of forces are
unnecessary to be stored in the dataset. | [
"Generate",
"FORCE_SETS",
"string"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/file_IO.py#L52-L65 |
227,571 | atztogo/phonopy | phonopy/file_IO.py | write_FORCE_CONSTANTS | def write_FORCE_CONSTANTS(force_constants,
filename='FORCE_CONSTANTS',
p2s_map=None):
"""Write force constants in text file format.
Parameters
----------
force_constants: ndarray
Force constants
shape=(n_satom,n_satom,3,3) or (n_patom,n_satom,3,3)
dtype=double
filename: str
Filename to be saved
p2s_map: ndarray
Primitive atom indices in supercell index system
dtype=intc
"""
lines = get_FORCE_CONSTANTS_lines(force_constants, p2s_map=p2s_map)
with open(filename, 'w') as w:
w.write("\n".join(lines)) | python | def write_FORCE_CONSTANTS(force_constants,
filename='FORCE_CONSTANTS',
p2s_map=None):
"""Write force constants in text file format.
Parameters
----------
force_constants: ndarray
Force constants
shape=(n_satom,n_satom,3,3) or (n_patom,n_satom,3,3)
dtype=double
filename: str
Filename to be saved
p2s_map: ndarray
Primitive atom indices in supercell index system
dtype=intc
"""
lines = get_FORCE_CONSTANTS_lines(force_constants, p2s_map=p2s_map)
with open(filename, 'w') as w:
w.write("\n".join(lines)) | [
"def",
"write_FORCE_CONSTANTS",
"(",
"force_constants",
",",
"filename",
"=",
"'FORCE_CONSTANTS'",
",",
"p2s_map",
"=",
"None",
")",
":",
"lines",
"=",
"get_FORCE_CONSTANTS_lines",
"(",
"force_constants",
",",
"p2s_map",
"=",
"p2s_map",
")",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"w",
":",
"w",
".",
"write",
"(",
"\"\\n\"",
".",
"join",
"(",
"lines",
")",
")"
] | Write force constants in text file format.
Parameters
----------
force_constants: ndarray
Force constants
shape=(n_satom,n_satom,3,3) or (n_patom,n_satom,3,3)
dtype=double
filename: str
Filename to be saved
p2s_map: ndarray
Primitive atom indices in supercell index system
dtype=intc | [
"Write",
"force",
"constants",
"in",
"text",
"file",
"format",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/file_IO.py#L243-L264 |
227,572 | atztogo/phonopy | phonopy/file_IO.py | write_force_constants_to_hdf5 | def write_force_constants_to_hdf5(force_constants,
filename='force_constants.hdf5',
p2s_map=None,
physical_unit=None,
compression=None):
"""Write force constants in hdf5 format.
Parameters
----------
force_constants: ndarray
Force constants
shape=(n_satom,n_satom,3,3) or (n_patom,n_satom,3,3)
dtype=double
filename: str
Filename to be saved
p2s_map: ndarray
Primitive atom indices in supercell index system
shape=(n_patom,)
dtype=intc
physical_unit : str, optional
Physical unit used for force contants. Default is None.
compression : str or int, optional
h5py's lossless compression filters (e.g., "gzip", "lzf").
See the detail at docstring of h5py.Group.create_dataset. Default is
None.
"""
try:
import h5py
except ImportError:
raise ModuleNotFoundError("You need to install python-h5py.")
with h5py.File(filename, 'w') as w:
w.create_dataset('force_constants', data=force_constants,
compression=compression)
if p2s_map is not None:
w.create_dataset('p2s_map', data=p2s_map)
if physical_unit is not None:
dset = w.create_dataset('physical_unit', (1,),
dtype='S%d' % len(physical_unit))
dset[0] = np.string_(physical_unit) | python | def write_force_constants_to_hdf5(force_constants,
filename='force_constants.hdf5',
p2s_map=None,
physical_unit=None,
compression=None):
"""Write force constants in hdf5 format.
Parameters
----------
force_constants: ndarray
Force constants
shape=(n_satom,n_satom,3,3) or (n_patom,n_satom,3,3)
dtype=double
filename: str
Filename to be saved
p2s_map: ndarray
Primitive atom indices in supercell index system
shape=(n_patom,)
dtype=intc
physical_unit : str, optional
Physical unit used for force contants. Default is None.
compression : str or int, optional
h5py's lossless compression filters (e.g., "gzip", "lzf").
See the detail at docstring of h5py.Group.create_dataset. Default is
None.
"""
try:
import h5py
except ImportError:
raise ModuleNotFoundError("You need to install python-h5py.")
with h5py.File(filename, 'w') as w:
w.create_dataset('force_constants', data=force_constants,
compression=compression)
if p2s_map is not None:
w.create_dataset('p2s_map', data=p2s_map)
if physical_unit is not None:
dset = w.create_dataset('physical_unit', (1,),
dtype='S%d' % len(physical_unit))
dset[0] = np.string_(physical_unit) | [
"def",
"write_force_constants_to_hdf5",
"(",
"force_constants",
",",
"filename",
"=",
"'force_constants.hdf5'",
",",
"p2s_map",
"=",
"None",
",",
"physical_unit",
"=",
"None",
",",
"compression",
"=",
"None",
")",
":",
"try",
":",
"import",
"h5py",
"except",
"ImportError",
":",
"raise",
"ModuleNotFoundError",
"(",
"\"You need to install python-h5py.\"",
")",
"with",
"h5py",
".",
"File",
"(",
"filename",
",",
"'w'",
")",
"as",
"w",
":",
"w",
".",
"create_dataset",
"(",
"'force_constants'",
",",
"data",
"=",
"force_constants",
",",
"compression",
"=",
"compression",
")",
"if",
"p2s_map",
"is",
"not",
"None",
":",
"w",
".",
"create_dataset",
"(",
"'p2s_map'",
",",
"data",
"=",
"p2s_map",
")",
"if",
"physical_unit",
"is",
"not",
"None",
":",
"dset",
"=",
"w",
".",
"create_dataset",
"(",
"'physical_unit'",
",",
"(",
"1",
",",
")",
",",
"dtype",
"=",
"'S%d'",
"%",
"len",
"(",
"physical_unit",
")",
")",
"dset",
"[",
"0",
"]",
"=",
"np",
".",
"string_",
"(",
"physical_unit",
")"
] | Write force constants in hdf5 format.
Parameters
----------
force_constants: ndarray
Force constants
shape=(n_satom,n_satom,3,3) or (n_patom,n_satom,3,3)
dtype=double
filename: str
Filename to be saved
p2s_map: ndarray
Primitive atom indices in supercell index system
shape=(n_patom,)
dtype=intc
physical_unit : str, optional
Physical unit used for force contants. Default is None.
compression : str or int, optional
h5py's lossless compression filters (e.g., "gzip", "lzf").
See the detail at docstring of h5py.Group.create_dataset. Default is
None. | [
"Write",
"force",
"constants",
"in",
"hdf5",
"format",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/file_IO.py#L285-L326 |
227,573 | atztogo/phonopy | phonopy/phonon/band_structure.py | get_band_qpoints | def get_band_qpoints(band_paths, npoints=51, rec_lattice=None):
"""Generate qpoints for band structure path
Note
----
Behavior changes with and without rec_lattice given.
Parameters
----------
band_paths: list of array_likes
Sets of end points of paths
dtype='double'
shape=(sets of paths, paths, 3)
example:
[[[0, 0, 0], [0.5, 0.5, 0], [0.5, 0.5, 0.5]],
[[0.5, 0.25, 0.75], [0, 0, 0]]]
npoints: int, optional
Number of q-points in each path including end points. Default is 51.
rec_lattice: array_like, optional
When given, q-points are sampled in a similar interval. The longest
path length divided by npoints including end points is used as the
reference interval. Reciprocal basis vectors given in column vectors.
dtype='double'
shape=(3, 3)
"""
npts = _get_npts(band_paths, npoints, rec_lattice)
qpoints_of_paths = []
c = 0
for band_path in band_paths:
nd = len(band_path)
for i in range(nd - 1):
delta = np.subtract(band_path[i + 1], band_path[i]) / (npts[c] - 1)
qpoints = [delta * j for j in range(npts[c])]
qpoints_of_paths.append(np.array(qpoints) + band_path[i])
c += 1
return qpoints_of_paths | python | def get_band_qpoints(band_paths, npoints=51, rec_lattice=None):
"""Generate qpoints for band structure path
Note
----
Behavior changes with and without rec_lattice given.
Parameters
----------
band_paths: list of array_likes
Sets of end points of paths
dtype='double'
shape=(sets of paths, paths, 3)
example:
[[[0, 0, 0], [0.5, 0.5, 0], [0.5, 0.5, 0.5]],
[[0.5, 0.25, 0.75], [0, 0, 0]]]
npoints: int, optional
Number of q-points in each path including end points. Default is 51.
rec_lattice: array_like, optional
When given, q-points are sampled in a similar interval. The longest
path length divided by npoints including end points is used as the
reference interval. Reciprocal basis vectors given in column vectors.
dtype='double'
shape=(3, 3)
"""
npts = _get_npts(band_paths, npoints, rec_lattice)
qpoints_of_paths = []
c = 0
for band_path in band_paths:
nd = len(band_path)
for i in range(nd - 1):
delta = np.subtract(band_path[i + 1], band_path[i]) / (npts[c] - 1)
qpoints = [delta * j for j in range(npts[c])]
qpoints_of_paths.append(np.array(qpoints) + band_path[i])
c += 1
return qpoints_of_paths | [
"def",
"get_band_qpoints",
"(",
"band_paths",
",",
"npoints",
"=",
"51",
",",
"rec_lattice",
"=",
"None",
")",
":",
"npts",
"=",
"_get_npts",
"(",
"band_paths",
",",
"npoints",
",",
"rec_lattice",
")",
"qpoints_of_paths",
"=",
"[",
"]",
"c",
"=",
"0",
"for",
"band_path",
"in",
"band_paths",
":",
"nd",
"=",
"len",
"(",
"band_path",
")",
"for",
"i",
"in",
"range",
"(",
"nd",
"-",
"1",
")",
":",
"delta",
"=",
"np",
".",
"subtract",
"(",
"band_path",
"[",
"i",
"+",
"1",
"]",
",",
"band_path",
"[",
"i",
"]",
")",
"/",
"(",
"npts",
"[",
"c",
"]",
"-",
"1",
")",
"qpoints",
"=",
"[",
"delta",
"*",
"j",
"for",
"j",
"in",
"range",
"(",
"npts",
"[",
"c",
"]",
")",
"]",
"qpoints_of_paths",
".",
"append",
"(",
"np",
".",
"array",
"(",
"qpoints",
")",
"+",
"band_path",
"[",
"i",
"]",
")",
"c",
"+=",
"1",
"return",
"qpoints_of_paths"
] | Generate qpoints for band structure path
Note
----
Behavior changes with and without rec_lattice given.
Parameters
----------
band_paths: list of array_likes
Sets of end points of paths
dtype='double'
shape=(sets of paths, paths, 3)
example:
[[[0, 0, 0], [0.5, 0.5, 0], [0.5, 0.5, 0.5]],
[[0.5, 0.25, 0.75], [0, 0, 0]]]
npoints: int, optional
Number of q-points in each path including end points. Default is 51.
rec_lattice: array_like, optional
When given, q-points are sampled in a similar interval. The longest
path length divided by npoints including end points is used as the
reference interval. Reciprocal basis vectors given in column vectors.
dtype='double'
shape=(3, 3) | [
"Generate",
"qpoints",
"for",
"band",
"structure",
"path"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/phonon/band_structure.py#L70-L112 |
227,574 | atztogo/phonopy | phonopy/phonon/band_structure.py | get_band_qpoints_by_seekpath | def get_band_qpoints_by_seekpath(primitive, npoints, is_const_interval=False):
"""q-points along BZ high symmetry paths are generated using seekpath.
Parameters
----------
primitive : PhonopyAtoms
Primitive cell.
npoints : int
Number of q-points sampled along a path including end points.
is_const_interval : bool, optional
When True, q-points are sampled in a similar interval. The longest
path length divided by npoints including end points is used as the
reference interval. Default is False.
Returns
-------
bands : List of ndarray
Sets of qpoints that can be passed to phonopy.set_band_structure().
shape of each ndarray : (npoints, 3)
labels : List of pairs of str
Symbols of end points of paths.
connections : List of bool
This gives one path is connected to the next path, i.e., if False,
there is a jump of q-points. Number of elements is the same at
that of paths.
"""
try:
import seekpath
except ImportError:
raise ImportError("You need to install seekpath.")
band_path = seekpath.get_path(primitive.totuple())
point_coords = band_path['point_coords']
qpoints_of_paths = []
if is_const_interval:
reclat = np.linalg.inv(primitive.get_cell())
else:
reclat = None
band_paths = [[point_coords[path[0]], point_coords[path[1]]]
for path in band_path['path']]
npts = _get_npts(band_paths, npoints, reclat)
for c, path in enumerate(band_path['path']):
q_s = np.array(point_coords[path[0]])
q_e = np.array(point_coords[path[1]])
band = [q_s + (q_e - q_s) / (npts[c] - 1) * i for i in range(npts[c])]
qpoints_of_paths.append(band)
labels, path_connections = _get_labels(band_path['path'])
return qpoints_of_paths, labels, path_connections | python | def get_band_qpoints_by_seekpath(primitive, npoints, is_const_interval=False):
"""q-points along BZ high symmetry paths are generated using seekpath.
Parameters
----------
primitive : PhonopyAtoms
Primitive cell.
npoints : int
Number of q-points sampled along a path including end points.
is_const_interval : bool, optional
When True, q-points are sampled in a similar interval. The longest
path length divided by npoints including end points is used as the
reference interval. Default is False.
Returns
-------
bands : List of ndarray
Sets of qpoints that can be passed to phonopy.set_band_structure().
shape of each ndarray : (npoints, 3)
labels : List of pairs of str
Symbols of end points of paths.
connections : List of bool
This gives one path is connected to the next path, i.e., if False,
there is a jump of q-points. Number of elements is the same at
that of paths.
"""
try:
import seekpath
except ImportError:
raise ImportError("You need to install seekpath.")
band_path = seekpath.get_path(primitive.totuple())
point_coords = band_path['point_coords']
qpoints_of_paths = []
if is_const_interval:
reclat = np.linalg.inv(primitive.get_cell())
else:
reclat = None
band_paths = [[point_coords[path[0]], point_coords[path[1]]]
for path in band_path['path']]
npts = _get_npts(band_paths, npoints, reclat)
for c, path in enumerate(band_path['path']):
q_s = np.array(point_coords[path[0]])
q_e = np.array(point_coords[path[1]])
band = [q_s + (q_e - q_s) / (npts[c] - 1) * i for i in range(npts[c])]
qpoints_of_paths.append(band)
labels, path_connections = _get_labels(band_path['path'])
return qpoints_of_paths, labels, path_connections | [
"def",
"get_band_qpoints_by_seekpath",
"(",
"primitive",
",",
"npoints",
",",
"is_const_interval",
"=",
"False",
")",
":",
"try",
":",
"import",
"seekpath",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"\"You need to install seekpath.\"",
")",
"band_path",
"=",
"seekpath",
".",
"get_path",
"(",
"primitive",
".",
"totuple",
"(",
")",
")",
"point_coords",
"=",
"band_path",
"[",
"'point_coords'",
"]",
"qpoints_of_paths",
"=",
"[",
"]",
"if",
"is_const_interval",
":",
"reclat",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"primitive",
".",
"get_cell",
"(",
")",
")",
"else",
":",
"reclat",
"=",
"None",
"band_paths",
"=",
"[",
"[",
"point_coords",
"[",
"path",
"[",
"0",
"]",
"]",
",",
"point_coords",
"[",
"path",
"[",
"1",
"]",
"]",
"]",
"for",
"path",
"in",
"band_path",
"[",
"'path'",
"]",
"]",
"npts",
"=",
"_get_npts",
"(",
"band_paths",
",",
"npoints",
",",
"reclat",
")",
"for",
"c",
",",
"path",
"in",
"enumerate",
"(",
"band_path",
"[",
"'path'",
"]",
")",
":",
"q_s",
"=",
"np",
".",
"array",
"(",
"point_coords",
"[",
"path",
"[",
"0",
"]",
"]",
")",
"q_e",
"=",
"np",
".",
"array",
"(",
"point_coords",
"[",
"path",
"[",
"1",
"]",
"]",
")",
"band",
"=",
"[",
"q_s",
"+",
"(",
"q_e",
"-",
"q_s",
")",
"/",
"(",
"npts",
"[",
"c",
"]",
"-",
"1",
")",
"*",
"i",
"for",
"i",
"in",
"range",
"(",
"npts",
"[",
"c",
"]",
")",
"]",
"qpoints_of_paths",
".",
"append",
"(",
"band",
")",
"labels",
",",
"path_connections",
"=",
"_get_labels",
"(",
"band_path",
"[",
"'path'",
"]",
")",
"return",
"qpoints_of_paths",
",",
"labels",
",",
"path_connections"
] | q-points along BZ high symmetry paths are generated using seekpath.
Parameters
----------
primitive : PhonopyAtoms
Primitive cell.
npoints : int
Number of q-points sampled along a path including end points.
is_const_interval : bool, optional
When True, q-points are sampled in a similar interval. The longest
path length divided by npoints including end points is used as the
reference interval. Default is False.
Returns
-------
bands : List of ndarray
Sets of qpoints that can be passed to phonopy.set_band_structure().
shape of each ndarray : (npoints, 3)
labels : List of pairs of str
Symbols of end points of paths.
connections : List of bool
This gives one path is connected to the next path, i.e., if False,
there is a jump of q-points. Number of elements is the same at
that of paths. | [
"q",
"-",
"points",
"along",
"BZ",
"high",
"symmetry",
"paths",
"are",
"generated",
"using",
"seekpath",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/phonon/band_structure.py#L115-L165 |
227,575 | atztogo/phonopy | phonopy/harmonic/dynmat_to_fc.py | get_commensurate_points | def get_commensurate_points(supercell_matrix): # wrt primitive cell
"""Commensurate q-points are returned.
Parameters
----------
supercell_matrix : array_like
Supercell matrix with respect to primitive cell basis vectors.
shape=(3, 3)
dtype=intc
"""
smat = np.array(supercell_matrix, dtype=int)
rec_primitive = PhonopyAtoms(numbers=[1],
scaled_positions=[[0, 0, 0]],
cell=np.diag([1, 1, 1]),
pbc=True)
rec_supercell = get_supercell(rec_primitive, smat.T)
q_pos = rec_supercell.get_scaled_positions()
return np.array(np.where(q_pos > 1 - 1e-15, q_pos - 1, q_pos),
dtype='double', order='C') | python | def get_commensurate_points(supercell_matrix): # wrt primitive cell
"""Commensurate q-points are returned.
Parameters
----------
supercell_matrix : array_like
Supercell matrix with respect to primitive cell basis vectors.
shape=(3, 3)
dtype=intc
"""
smat = np.array(supercell_matrix, dtype=int)
rec_primitive = PhonopyAtoms(numbers=[1],
scaled_positions=[[0, 0, 0]],
cell=np.diag([1, 1, 1]),
pbc=True)
rec_supercell = get_supercell(rec_primitive, smat.T)
q_pos = rec_supercell.get_scaled_positions()
return np.array(np.where(q_pos > 1 - 1e-15, q_pos - 1, q_pos),
dtype='double', order='C') | [
"def",
"get_commensurate_points",
"(",
"supercell_matrix",
")",
":",
"# wrt primitive cell",
"smat",
"=",
"np",
".",
"array",
"(",
"supercell_matrix",
",",
"dtype",
"=",
"int",
")",
"rec_primitive",
"=",
"PhonopyAtoms",
"(",
"numbers",
"=",
"[",
"1",
"]",
",",
"scaled_positions",
"=",
"[",
"[",
"0",
",",
"0",
",",
"0",
"]",
"]",
",",
"cell",
"=",
"np",
".",
"diag",
"(",
"[",
"1",
",",
"1",
",",
"1",
"]",
")",
",",
"pbc",
"=",
"True",
")",
"rec_supercell",
"=",
"get_supercell",
"(",
"rec_primitive",
",",
"smat",
".",
"T",
")",
"q_pos",
"=",
"rec_supercell",
".",
"get_scaled_positions",
"(",
")",
"return",
"np",
".",
"array",
"(",
"np",
".",
"where",
"(",
"q_pos",
">",
"1",
"-",
"1e-15",
",",
"q_pos",
"-",
"1",
",",
"q_pos",
")",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")"
] | Commensurate q-points are returned.
Parameters
----------
supercell_matrix : array_like
Supercell matrix with respect to primitive cell basis vectors.
shape=(3, 3)
dtype=intc | [
"Commensurate",
"q",
"-",
"points",
"are",
"returned",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/dynmat_to_fc.py#L42-L62 |
227,576 | atztogo/phonopy | phonopy/harmonic/dynmat_to_fc.py | get_commensurate_points_in_integers | def get_commensurate_points_in_integers(supercell_matrix):
"""Commensurate q-points in integer representation are returned.
A set of integer representation of lattice points is transformed to
the equivalent set of lattice points in fractional coordinates with
respect to supercell basis vectors by
integer_lattice_points / det(supercell_matrix)
Parameters
----------
supercell_matrix : array_like
Supercell matrix with respect to primitive cell basis vectors.
shape=(3, 3)
dtype=intc
Returns
-------
lattice_points : ndarray
Integer representation of lattice points in supercell.
shape=(N, 3)
"""
smat = np.array(supercell_matrix, dtype=int)
snf = SNF3x3(smat.T)
snf.run()
D = snf.A.diagonal()
b, c, a = np.meshgrid(range(D[1]), range(D[2]), range(D[0]))
lattice_points = np.dot(np.c_[a.ravel() * D[1] * D[2],
b.ravel() * D[0] * D[2],
c.ravel() * D[0] * D[1]], snf.Q.T)
lattice_points = np.array(lattice_points % np.prod(D),
dtype='intc', order='C')
return lattice_points | python | def get_commensurate_points_in_integers(supercell_matrix):
"""Commensurate q-points in integer representation are returned.
A set of integer representation of lattice points is transformed to
the equivalent set of lattice points in fractional coordinates with
respect to supercell basis vectors by
integer_lattice_points / det(supercell_matrix)
Parameters
----------
supercell_matrix : array_like
Supercell matrix with respect to primitive cell basis vectors.
shape=(3, 3)
dtype=intc
Returns
-------
lattice_points : ndarray
Integer representation of lattice points in supercell.
shape=(N, 3)
"""
smat = np.array(supercell_matrix, dtype=int)
snf = SNF3x3(smat.T)
snf.run()
D = snf.A.diagonal()
b, c, a = np.meshgrid(range(D[1]), range(D[2]), range(D[0]))
lattice_points = np.dot(np.c_[a.ravel() * D[1] * D[2],
b.ravel() * D[0] * D[2],
c.ravel() * D[0] * D[1]], snf.Q.T)
lattice_points = np.array(lattice_points % np.prod(D),
dtype='intc', order='C')
return lattice_points | [
"def",
"get_commensurate_points_in_integers",
"(",
"supercell_matrix",
")",
":",
"smat",
"=",
"np",
".",
"array",
"(",
"supercell_matrix",
",",
"dtype",
"=",
"int",
")",
"snf",
"=",
"SNF3x3",
"(",
"smat",
".",
"T",
")",
"snf",
".",
"run",
"(",
")",
"D",
"=",
"snf",
".",
"A",
".",
"diagonal",
"(",
")",
"b",
",",
"c",
",",
"a",
"=",
"np",
".",
"meshgrid",
"(",
"range",
"(",
"D",
"[",
"1",
"]",
")",
",",
"range",
"(",
"D",
"[",
"2",
"]",
")",
",",
"range",
"(",
"D",
"[",
"0",
"]",
")",
")",
"lattice_points",
"=",
"np",
".",
"dot",
"(",
"np",
".",
"c_",
"[",
"a",
".",
"ravel",
"(",
")",
"*",
"D",
"[",
"1",
"]",
"*",
"D",
"[",
"2",
"]",
",",
"b",
".",
"ravel",
"(",
")",
"*",
"D",
"[",
"0",
"]",
"*",
"D",
"[",
"2",
"]",
",",
"c",
".",
"ravel",
"(",
")",
"*",
"D",
"[",
"0",
"]",
"*",
"D",
"[",
"1",
"]",
"]",
",",
"snf",
".",
"Q",
".",
"T",
")",
"lattice_points",
"=",
"np",
".",
"array",
"(",
"lattice_points",
"%",
"np",
".",
"prod",
"(",
"D",
")",
",",
"dtype",
"=",
"'intc'",
",",
"order",
"=",
"'C'",
")",
"return",
"lattice_points"
] | Commensurate q-points in integer representation are returned.
A set of integer representation of lattice points is transformed to
the equivalent set of lattice points in fractional coordinates with
respect to supercell basis vectors by
integer_lattice_points / det(supercell_matrix)
Parameters
----------
supercell_matrix : array_like
Supercell matrix with respect to primitive cell basis vectors.
shape=(3, 3)
dtype=intc
Returns
-------
lattice_points : ndarray
Integer representation of lattice points in supercell.
shape=(N, 3) | [
"Commensurate",
"q",
"-",
"points",
"in",
"integer",
"representation",
"are",
"returned",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/dynmat_to_fc.py#L65-L97 |
227,577 | atztogo/phonopy | phonopy/interface/vasp.py | write_vasp | def write_vasp(filename, cell, direct=True):
"""Write crystal structure to a VASP POSCAR style file.
Parameters
----------
filename : str
Filename.
cell : PhonopyAtoms
Crystal structure.
direct : bool, optional
In 'Direct' or not in VASP POSCAR format. Default is True.
"""
lines = get_vasp_structure_lines(cell, direct=direct)
with open(filename, 'w') as w:
w.write("\n".join(lines)) | python | def write_vasp(filename, cell, direct=True):
"""Write crystal structure to a VASP POSCAR style file.
Parameters
----------
filename : str
Filename.
cell : PhonopyAtoms
Crystal structure.
direct : bool, optional
In 'Direct' or not in VASP POSCAR format. Default is True.
"""
lines = get_vasp_structure_lines(cell, direct=direct)
with open(filename, 'w') as w:
w.write("\n".join(lines)) | [
"def",
"write_vasp",
"(",
"filename",
",",
"cell",
",",
"direct",
"=",
"True",
")",
":",
"lines",
"=",
"get_vasp_structure_lines",
"(",
"cell",
",",
"direct",
"=",
"direct",
")",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"w",
":",
"w",
".",
"write",
"(",
"\"\\n\"",
".",
"join",
"(",
"lines",
")",
")"
] | Write crystal structure to a VASP POSCAR style file.
Parameters
----------
filename : str
Filename.
cell : PhonopyAtoms
Crystal structure.
direct : bool, optional
In 'Direct' or not in VASP POSCAR format. Default is True. | [
"Write",
"crystal",
"structure",
"to",
"a",
"VASP",
"POSCAR",
"style",
"file",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/vasp.py#L249-L265 |
227,578 | atztogo/phonopy | phonopy/interface/qe.py | PwscfIn._set_lattice | def _set_lattice(self):
"""Calculate and set lattice parameters.
Invoked by CELL_PARAMETERS tag.
"""
unit = self._values[0]
if unit == 'alat':
if not self._tags['celldm(1)']:
print("celldm(1) has to be specified when using alat.")
sys.exit(1)
else:
factor = self._tags['celldm(1)'] # in Bohr
elif unit == 'angstrom':
factor = 1.0 / Bohr
else:
factor = 1.0
if len(self._values[1:]) < 9:
print("CELL_PARAMETERS is wrongly set.")
sys.exit(1)
lattice = np.reshape([float(x) for x in self._values[1:10]], (3, 3))
self._tags['cell_parameters'] = lattice * factor | python | def _set_lattice(self):
"""Calculate and set lattice parameters.
Invoked by CELL_PARAMETERS tag.
"""
unit = self._values[0]
if unit == 'alat':
if not self._tags['celldm(1)']:
print("celldm(1) has to be specified when using alat.")
sys.exit(1)
else:
factor = self._tags['celldm(1)'] # in Bohr
elif unit == 'angstrom':
factor = 1.0 / Bohr
else:
factor = 1.0
if len(self._values[1:]) < 9:
print("CELL_PARAMETERS is wrongly set.")
sys.exit(1)
lattice = np.reshape([float(x) for x in self._values[1:10]], (3, 3))
self._tags['cell_parameters'] = lattice * factor | [
"def",
"_set_lattice",
"(",
"self",
")",
":",
"unit",
"=",
"self",
".",
"_values",
"[",
"0",
"]",
"if",
"unit",
"==",
"'alat'",
":",
"if",
"not",
"self",
".",
"_tags",
"[",
"'celldm(1)'",
"]",
":",
"print",
"(",
"\"celldm(1) has to be specified when using alat.\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"else",
":",
"factor",
"=",
"self",
".",
"_tags",
"[",
"'celldm(1)'",
"]",
"# in Bohr",
"elif",
"unit",
"==",
"'angstrom'",
":",
"factor",
"=",
"1.0",
"/",
"Bohr",
"else",
":",
"factor",
"=",
"1.0",
"if",
"len",
"(",
"self",
".",
"_values",
"[",
"1",
":",
"]",
")",
"<",
"9",
":",
"print",
"(",
"\"CELL_PARAMETERS is wrongly set.\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"lattice",
"=",
"np",
".",
"reshape",
"(",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"_values",
"[",
"1",
":",
"10",
"]",
"]",
",",
"(",
"3",
",",
"3",
")",
")",
"self",
".",
"_tags",
"[",
"'cell_parameters'",
"]",
"=",
"lattice",
"*",
"factor"
] | Calculate and set lattice parameters.
Invoked by CELL_PARAMETERS tag. | [
"Calculate",
"and",
"set",
"lattice",
"parameters",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/qe.py#L278-L302 |
227,579 | atztogo/phonopy | phonopy/interface/qe.py | PH_Q2R.run | def run(self, cell, is_full_fc=False, parse_fc=True):
"""Make supercell force constants readable for phonopy
Note
----
Born effective charges and dielectric constant tensor are read
from QE output file if they exist. But this means
dipole-dipole contributions are removed from force constants
and this force constants matrix is not usable in phonopy.
Arguments
---------
cell : PhonopyAtoms
Primitive cell used for QE/PH calculation.
is_full_fc : Bool, optional, default=False
Whether to create full or compact force constants.
parse_fc : Bool, optional, default=True
Force constants file of QE is not parsed when this is False.
False may be used when expected to parse only epsilon and born.
"""
with open(self._filename) as f:
fc_dct = self._parse_q2r(f)
self.dimension = fc_dct['dimension']
self.epsilon = fc_dct['dielectric']
self.borns = fc_dct['born']
if parse_fc:
(self.fc,
self.primitive,
self.supercell) = self._arrange_supercell_fc(
cell, fc_dct['fc'], is_full_fc=is_full_fc) | python | def run(self, cell, is_full_fc=False, parse_fc=True):
"""Make supercell force constants readable for phonopy
Note
----
Born effective charges and dielectric constant tensor are read
from QE output file if they exist. But this means
dipole-dipole contributions are removed from force constants
and this force constants matrix is not usable in phonopy.
Arguments
---------
cell : PhonopyAtoms
Primitive cell used for QE/PH calculation.
is_full_fc : Bool, optional, default=False
Whether to create full or compact force constants.
parse_fc : Bool, optional, default=True
Force constants file of QE is not parsed when this is False.
False may be used when expected to parse only epsilon and born.
"""
with open(self._filename) as f:
fc_dct = self._parse_q2r(f)
self.dimension = fc_dct['dimension']
self.epsilon = fc_dct['dielectric']
self.borns = fc_dct['born']
if parse_fc:
(self.fc,
self.primitive,
self.supercell) = self._arrange_supercell_fc(
cell, fc_dct['fc'], is_full_fc=is_full_fc) | [
"def",
"run",
"(",
"self",
",",
"cell",
",",
"is_full_fc",
"=",
"False",
",",
"parse_fc",
"=",
"True",
")",
":",
"with",
"open",
"(",
"self",
".",
"_filename",
")",
"as",
"f",
":",
"fc_dct",
"=",
"self",
".",
"_parse_q2r",
"(",
"f",
")",
"self",
".",
"dimension",
"=",
"fc_dct",
"[",
"'dimension'",
"]",
"self",
".",
"epsilon",
"=",
"fc_dct",
"[",
"'dielectric'",
"]",
"self",
".",
"borns",
"=",
"fc_dct",
"[",
"'born'",
"]",
"if",
"parse_fc",
":",
"(",
"self",
".",
"fc",
",",
"self",
".",
"primitive",
",",
"self",
".",
"supercell",
")",
"=",
"self",
".",
"_arrange_supercell_fc",
"(",
"cell",
",",
"fc_dct",
"[",
"'fc'",
"]",
",",
"is_full_fc",
"=",
"is_full_fc",
")"
] | Make supercell force constants readable for phonopy
Note
----
Born effective charges and dielectric constant tensor are read
from QE output file if they exist. But this means
dipole-dipole contributions are removed from force constants
and this force constants matrix is not usable in phonopy.
Arguments
---------
cell : PhonopyAtoms
Primitive cell used for QE/PH calculation.
is_full_fc : Bool, optional, default=False
Whether to create full or compact force constants.
parse_fc : Bool, optional, default=True
Force constants file of QE is not parsed when this is False.
False may be used when expected to parse only epsilon and born. | [
"Make",
"supercell",
"force",
"constants",
"readable",
"for",
"phonopy"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/qe.py#L416-L447 |
227,580 | atztogo/phonopy | phonopy/interface/qe.py | PH_Q2R._parse_q2r | def _parse_q2r(self, f):
"""Parse q2r output file
The format of q2r output is described at the mailing list below:
http://www.democritos.it/pipermail/pw_forum/2005-April/002408.html
http://www.democritos.it/pipermail/pw_forum/2008-September/010099.html
http://www.democritos.it/pipermail/pw_forum/2009-August/013613.html
https://www.mail-archive.com/pw_forum@pwscf.org/msg24388.html
"""
natom, dim, epsilon, borns = self._parse_parameters(f)
fc_dct = {'fc': self._parse_fc(f, natom, dim),
'dimension': dim,
'dielectric': epsilon,
'born': borns}
return fc_dct | python | def _parse_q2r(self, f):
"""Parse q2r output file
The format of q2r output is described at the mailing list below:
http://www.democritos.it/pipermail/pw_forum/2005-April/002408.html
http://www.democritos.it/pipermail/pw_forum/2008-September/010099.html
http://www.democritos.it/pipermail/pw_forum/2009-August/013613.html
https://www.mail-archive.com/pw_forum@pwscf.org/msg24388.html
"""
natom, dim, epsilon, borns = self._parse_parameters(f)
fc_dct = {'fc': self._parse_fc(f, natom, dim),
'dimension': dim,
'dielectric': epsilon,
'born': borns}
return fc_dct | [
"def",
"_parse_q2r",
"(",
"self",
",",
"f",
")",
":",
"natom",
",",
"dim",
",",
"epsilon",
",",
"borns",
"=",
"self",
".",
"_parse_parameters",
"(",
"f",
")",
"fc_dct",
"=",
"{",
"'fc'",
":",
"self",
".",
"_parse_fc",
"(",
"f",
",",
"natom",
",",
"dim",
")",
",",
"'dimension'",
":",
"dim",
",",
"'dielectric'",
":",
"epsilon",
",",
"'born'",
":",
"borns",
"}",
"return",
"fc_dct"
] | Parse q2r output file
The format of q2r output is described at the mailing list below:
http://www.democritos.it/pipermail/pw_forum/2005-April/002408.html
http://www.democritos.it/pipermail/pw_forum/2008-September/010099.html
http://www.democritos.it/pipermail/pw_forum/2009-August/013613.html
https://www.mail-archive.com/pw_forum@pwscf.org/msg24388.html | [
"Parse",
"q2r",
"output",
"file"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/qe.py#L457-L473 |
227,581 | atztogo/phonopy | phonopy/interface/qe.py | PH_Q2R._parse_fc | def _parse_fc(self, f, natom, dim):
"""Parse force constants part
Physical unit of force cosntants in the file is Ry/au^2.
"""
ndim = np.prod(dim)
fc = np.zeros((natom, natom * ndim, 3, 3), dtype='double', order='C')
for k, l, i, j in np.ndindex((3, 3, natom, natom)):
line = f.readline()
for i_dim in range(ndim):
line = f.readline()
# fc[i, j * ndim + i_dim, k, l] = float(line.split()[3])
fc[j, i * ndim + i_dim, l, k] = float(line.split()[3])
return fc | python | def _parse_fc(self, f, natom, dim):
"""Parse force constants part
Physical unit of force cosntants in the file is Ry/au^2.
"""
ndim = np.prod(dim)
fc = np.zeros((natom, natom * ndim, 3, 3), dtype='double', order='C')
for k, l, i, j in np.ndindex((3, 3, natom, natom)):
line = f.readline()
for i_dim in range(ndim):
line = f.readline()
# fc[i, j * ndim + i_dim, k, l] = float(line.split()[3])
fc[j, i * ndim + i_dim, l, k] = float(line.split()[3])
return fc | [
"def",
"_parse_fc",
"(",
"self",
",",
"f",
",",
"natom",
",",
"dim",
")",
":",
"ndim",
"=",
"np",
".",
"prod",
"(",
"dim",
")",
"fc",
"=",
"np",
".",
"zeros",
"(",
"(",
"natom",
",",
"natom",
"*",
"ndim",
",",
"3",
",",
"3",
")",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"for",
"k",
",",
"l",
",",
"i",
",",
"j",
"in",
"np",
".",
"ndindex",
"(",
"(",
"3",
",",
"3",
",",
"natom",
",",
"natom",
")",
")",
":",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"for",
"i_dim",
"in",
"range",
"(",
"ndim",
")",
":",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"# fc[i, j * ndim + i_dim, k, l] = float(line.split()[3])",
"fc",
"[",
"j",
",",
"i",
"*",
"ndim",
"+",
"i_dim",
",",
"l",
",",
"k",
"]",
"=",
"float",
"(",
"line",
".",
"split",
"(",
")",
"[",
"3",
"]",
")",
"return",
"fc"
] | Parse force constants part
Physical unit of force cosntants in the file is Ry/au^2. | [
"Parse",
"force",
"constants",
"part"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/qe.py#L507-L522 |
227,582 | atztogo/phonopy | phonopy/interface/cp2k.py | get_cp2k_structure | def get_cp2k_structure(atoms):
"""Convert the atoms structure to a CP2K input file skeleton string"""
from cp2k_tools.generator import dict2cp2k
# CP2K's default unit is angstrom, convert it, but still declare it explictly:
cp2k_cell = {sym: ('[angstrom]',) + tuple(coords) for sym, coords in zip(('a', 'b', 'c'), atoms.get_cell()*Bohr)}
cp2k_cell['periodic'] = 'XYZ' # anything else does not make much sense
cp2k_coord = {
'scaled': True,
'*': [[sym] + list(coord) for sym, coord in zip(atoms.get_chemical_symbols(), atoms.get_scaled_positions())],
}
return dict2cp2k(
{
'global': {
'run_type': 'ENERGY_FORCE',
},
'force_eval': {
'subsys': {
'cell': cp2k_cell,
'coord': cp2k_coord,
},
'print': {
'forces': {
'filename': 'forces',
},
},
},
}
) | python | def get_cp2k_structure(atoms):
"""Convert the atoms structure to a CP2K input file skeleton string"""
from cp2k_tools.generator import dict2cp2k
# CP2K's default unit is angstrom, convert it, but still declare it explictly:
cp2k_cell = {sym: ('[angstrom]',) + tuple(coords) for sym, coords in zip(('a', 'b', 'c'), atoms.get_cell()*Bohr)}
cp2k_cell['periodic'] = 'XYZ' # anything else does not make much sense
cp2k_coord = {
'scaled': True,
'*': [[sym] + list(coord) for sym, coord in zip(atoms.get_chemical_symbols(), atoms.get_scaled_positions())],
}
return dict2cp2k(
{
'global': {
'run_type': 'ENERGY_FORCE',
},
'force_eval': {
'subsys': {
'cell': cp2k_cell,
'coord': cp2k_coord,
},
'print': {
'forces': {
'filename': 'forces',
},
},
},
}
) | [
"def",
"get_cp2k_structure",
"(",
"atoms",
")",
":",
"from",
"cp2k_tools",
".",
"generator",
"import",
"dict2cp2k",
"# CP2K's default unit is angstrom, convert it, but still declare it explictly:",
"cp2k_cell",
"=",
"{",
"sym",
":",
"(",
"'[angstrom]'",
",",
")",
"+",
"tuple",
"(",
"coords",
")",
"for",
"sym",
",",
"coords",
"in",
"zip",
"(",
"(",
"'a'",
",",
"'b'",
",",
"'c'",
")",
",",
"atoms",
".",
"get_cell",
"(",
")",
"*",
"Bohr",
")",
"}",
"cp2k_cell",
"[",
"'periodic'",
"]",
"=",
"'XYZ'",
"# anything else does not make much sense",
"cp2k_coord",
"=",
"{",
"'scaled'",
":",
"True",
",",
"'*'",
":",
"[",
"[",
"sym",
"]",
"+",
"list",
"(",
"coord",
")",
"for",
"sym",
",",
"coord",
"in",
"zip",
"(",
"atoms",
".",
"get_chemical_symbols",
"(",
")",
",",
"atoms",
".",
"get_scaled_positions",
"(",
")",
")",
"]",
",",
"}",
"return",
"dict2cp2k",
"(",
"{",
"'global'",
":",
"{",
"'run_type'",
":",
"'ENERGY_FORCE'",
",",
"}",
",",
"'force_eval'",
":",
"{",
"'subsys'",
":",
"{",
"'cell'",
":",
"cp2k_cell",
",",
"'coord'",
":",
"cp2k_coord",
",",
"}",
",",
"'print'",
":",
"{",
"'forces'",
":",
"{",
"'filename'",
":",
"'forces'",
",",
"}",
",",
"}",
",",
"}",
",",
"}",
")"
] | Convert the atoms structure to a CP2K input file skeleton string | [
"Convert",
"the",
"atoms",
"structure",
"to",
"a",
"CP2K",
"input",
"file",
"skeleton",
"string"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/cp2k.py#L126-L156 |
227,583 | atztogo/phonopy | phonopy/api_qha.py | PhonopyQHA.plot_qha | def plot_qha(self, thin_number=10, volume_temp_exp=None):
"""Returns matplotlib.pyplot of QHA fitting curves at temperatures"""
return self._qha.plot(thin_number=thin_number,
volume_temp_exp=volume_temp_exp) | python | def plot_qha(self, thin_number=10, volume_temp_exp=None):
"""Returns matplotlib.pyplot of QHA fitting curves at temperatures"""
return self._qha.plot(thin_number=thin_number,
volume_temp_exp=volume_temp_exp) | [
"def",
"plot_qha",
"(",
"self",
",",
"thin_number",
"=",
"10",
",",
"volume_temp_exp",
"=",
"None",
")",
":",
"return",
"self",
".",
"_qha",
".",
"plot",
"(",
"thin_number",
"=",
"thin_number",
",",
"volume_temp_exp",
"=",
"volume_temp_exp",
")"
] | Returns matplotlib.pyplot of QHA fitting curves at temperatures | [
"Returns",
"matplotlib",
".",
"pyplot",
"of",
"QHA",
"fitting",
"curves",
"at",
"temperatures"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_qha.py#L137-L140 |
227,584 | atztogo/phonopy | phonopy/harmonic/force_constants.py | get_fc2 | def get_fc2(supercell,
symmetry,
dataset,
atom_list=None,
decimals=None):
"""Force constants are computed.
Force constants, Phi, are calculated from sets for forces, F, and
atomic displacement, d:
Phi = -F / d
This is solved by matrix pseudo-inversion.
Crystal symmetry is included when creating F and d matrices.
Returns
-------
ndarray
Force constants[ i, j, a, b ]
i: Atom index of finitely displaced atom.
j: Atom index at which force on the atom is measured.
a, b: Cartesian direction indices = (0, 1, 2) for i and j, respectively
dtype=double
shape=(len(atom_list),n_satom,3,3),
"""
if atom_list is None:
fc_dim0 = supercell.get_number_of_atoms()
else:
fc_dim0 = len(atom_list)
force_constants = np.zeros((fc_dim0,
supercell.get_number_of_atoms(),
3, 3), dtype='double', order='C')
# Fill force_constants[ displaced_atoms, all_atoms_in_supercell ]
atom_list_done = _get_force_constants_disps(
force_constants,
supercell,
dataset,
symmetry,
atom_list=atom_list)
rotations = symmetry.get_symmetry_operations()['rotations']
lattice = np.array(supercell.get_cell().T, dtype='double', order='C')
permutations = symmetry.get_atomic_permutations()
distribute_force_constants(force_constants,
atom_list_done,
lattice,
rotations,
permutations,
atom_list=atom_list)
if decimals:
force_constants = force_constants.round(decimals=decimals)
return force_constants | python | def get_fc2(supercell,
symmetry,
dataset,
atom_list=None,
decimals=None):
"""Force constants are computed.
Force constants, Phi, are calculated from sets for forces, F, and
atomic displacement, d:
Phi = -F / d
This is solved by matrix pseudo-inversion.
Crystal symmetry is included when creating F and d matrices.
Returns
-------
ndarray
Force constants[ i, j, a, b ]
i: Atom index of finitely displaced atom.
j: Atom index at which force on the atom is measured.
a, b: Cartesian direction indices = (0, 1, 2) for i and j, respectively
dtype=double
shape=(len(atom_list),n_satom,3,3),
"""
if atom_list is None:
fc_dim0 = supercell.get_number_of_atoms()
else:
fc_dim0 = len(atom_list)
force_constants = np.zeros((fc_dim0,
supercell.get_number_of_atoms(),
3, 3), dtype='double', order='C')
# Fill force_constants[ displaced_atoms, all_atoms_in_supercell ]
atom_list_done = _get_force_constants_disps(
force_constants,
supercell,
dataset,
symmetry,
atom_list=atom_list)
rotations = symmetry.get_symmetry_operations()['rotations']
lattice = np.array(supercell.get_cell().T, dtype='double', order='C')
permutations = symmetry.get_atomic_permutations()
distribute_force_constants(force_constants,
atom_list_done,
lattice,
rotations,
permutations,
atom_list=atom_list)
if decimals:
force_constants = force_constants.round(decimals=decimals)
return force_constants | [
"def",
"get_fc2",
"(",
"supercell",
",",
"symmetry",
",",
"dataset",
",",
"atom_list",
"=",
"None",
",",
"decimals",
"=",
"None",
")",
":",
"if",
"atom_list",
"is",
"None",
":",
"fc_dim0",
"=",
"supercell",
".",
"get_number_of_atoms",
"(",
")",
"else",
":",
"fc_dim0",
"=",
"len",
"(",
"atom_list",
")",
"force_constants",
"=",
"np",
".",
"zeros",
"(",
"(",
"fc_dim0",
",",
"supercell",
".",
"get_number_of_atoms",
"(",
")",
",",
"3",
",",
"3",
")",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"# Fill force_constants[ displaced_atoms, all_atoms_in_supercell ]",
"atom_list_done",
"=",
"_get_force_constants_disps",
"(",
"force_constants",
",",
"supercell",
",",
"dataset",
",",
"symmetry",
",",
"atom_list",
"=",
"atom_list",
")",
"rotations",
"=",
"symmetry",
".",
"get_symmetry_operations",
"(",
")",
"[",
"'rotations'",
"]",
"lattice",
"=",
"np",
".",
"array",
"(",
"supercell",
".",
"get_cell",
"(",
")",
".",
"T",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"permutations",
"=",
"symmetry",
".",
"get_atomic_permutations",
"(",
")",
"distribute_force_constants",
"(",
"force_constants",
",",
"atom_list_done",
",",
"lattice",
",",
"rotations",
",",
"permutations",
",",
"atom_list",
"=",
"atom_list",
")",
"if",
"decimals",
":",
"force_constants",
"=",
"force_constants",
".",
"round",
"(",
"decimals",
"=",
"decimals",
")",
"return",
"force_constants"
] | Force constants are computed.
Force constants, Phi, are calculated from sets for forces, F, and
atomic displacement, d:
Phi = -F / d
This is solved by matrix pseudo-inversion.
Crystal symmetry is included when creating F and d matrices.
Returns
-------
ndarray
Force constants[ i, j, a, b ]
i: Atom index of finitely displaced atom.
j: Atom index at which force on the atom is measured.
a, b: Cartesian direction indices = (0, 1, 2) for i and j, respectively
dtype=double
shape=(len(atom_list),n_satom,3,3), | [
"Force",
"constants",
"are",
"computed",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/force_constants.py#L58-L113 |
227,585 | atztogo/phonopy | phonopy/harmonic/force_constants.py | set_permutation_symmetry | def set_permutation_symmetry(force_constants):
"""Enforce permutation symmetry to force cosntants by
Phi_ij_ab = Phi_ji_ba
i, j: atom index
a, b: Cartesian axis index
This is not necessary for harmonic phonon calculation because this
condition is imposed when making dynamical matrix Hermite in
dynamical_matrix.py.
"""
fc_copy = force_constants.copy()
for i in range(force_constants.shape[0]):
for j in range(force_constants.shape[1]):
force_constants[i, j] = (force_constants[i, j] +
fc_copy[j, i].T) / 2 | python | def set_permutation_symmetry(force_constants):
"""Enforce permutation symmetry to force cosntants by
Phi_ij_ab = Phi_ji_ba
i, j: atom index
a, b: Cartesian axis index
This is not necessary for harmonic phonon calculation because this
condition is imposed when making dynamical matrix Hermite in
dynamical_matrix.py.
"""
fc_copy = force_constants.copy()
for i in range(force_constants.shape[0]):
for j in range(force_constants.shape[1]):
force_constants[i, j] = (force_constants[i, j] +
fc_copy[j, i].T) / 2 | [
"def",
"set_permutation_symmetry",
"(",
"force_constants",
")",
":",
"fc_copy",
"=",
"force_constants",
".",
"copy",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"force_constants",
".",
"shape",
"[",
"0",
"]",
")",
":",
"for",
"j",
"in",
"range",
"(",
"force_constants",
".",
"shape",
"[",
"1",
"]",
")",
":",
"force_constants",
"[",
"i",
",",
"j",
"]",
"=",
"(",
"force_constants",
"[",
"i",
",",
"j",
"]",
"+",
"fc_copy",
"[",
"j",
",",
"i",
"]",
".",
"T",
")",
"/",
"2"
] | Enforce permutation symmetry to force cosntants by
Phi_ij_ab = Phi_ji_ba
i, j: atom index
a, b: Cartesian axis index
This is not necessary for harmonic phonon calculation because this
condition is imposed when making dynamical matrix Hermite in
dynamical_matrix.py. | [
"Enforce",
"permutation",
"symmetry",
"to",
"force",
"cosntants",
"by"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/force_constants.py#L462-L480 |
227,586 | atztogo/phonopy | phonopy/harmonic/force_constants.py | similarity_transformation | def similarity_transformation(rot, mat):
""" R x M x R^-1 """
return np.dot(rot, np.dot(mat, np.linalg.inv(rot))) | python | def similarity_transformation(rot, mat):
""" R x M x R^-1 """
return np.dot(rot, np.dot(mat, np.linalg.inv(rot))) | [
"def",
"similarity_transformation",
"(",
"rot",
",",
"mat",
")",
":",
"return",
"np",
".",
"dot",
"(",
"rot",
",",
"np",
".",
"dot",
"(",
"mat",
",",
"np",
".",
"linalg",
".",
"inv",
"(",
"rot",
")",
")",
")"
] | R x M x R^-1 | [
"R",
"x",
"M",
"x",
"R^",
"-",
"1"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/force_constants.py#L529-L531 |
227,587 | atztogo/phonopy | phonopy/harmonic/force_constants.py | _get_sym_mappings_from_permutations | def _get_sym_mappings_from_permutations(permutations, atom_list_done):
"""This can be thought of as computing 'map_atom_disp' and 'map_sym'
for all atoms, except done using permutations instead of by
computing overlaps.
Input:
* permutations, shape [num_rot][num_pos]
* atom_list_done
Output:
* map_atoms, shape [num_pos].
Maps each atom in the full structure to its equivalent atom in
atom_list_done. (each entry will be an integer found in
atom_list_done)
* map_syms, shape [num_pos].
For each atom, provides the index of a rotation that maps it
into atom_list_done. (there might be more than one such
rotation, but only one will be returned) (each entry will be
an integer 0 <= i < num_rot)
"""
assert permutations.ndim == 2
num_pos = permutations.shape[1]
# filled with -1
map_atoms = np.zeros((num_pos,), dtype='intc') - 1
map_syms = np.zeros((num_pos,), dtype='intc') - 1
atom_list_done = set(atom_list_done)
for atom_todo in range(num_pos):
for (sym_index, permutation) in enumerate(permutations):
if permutation[atom_todo] in atom_list_done:
map_atoms[atom_todo] = permutation[atom_todo]
map_syms[atom_todo] = sym_index
break
else:
text = ("Input forces are not enough to calculate force constants,"
"or something wrong (e.g. crystal structure does not "
"match).")
print(textwrap.fill(text))
raise ValueError
assert set(map_atoms) & set(atom_list_done) == set(map_atoms)
assert -1 not in map_atoms
assert -1 not in map_syms
return map_atoms, map_syms | python | def _get_sym_mappings_from_permutations(permutations, atom_list_done):
"""This can be thought of as computing 'map_atom_disp' and 'map_sym'
for all atoms, except done using permutations instead of by
computing overlaps.
Input:
* permutations, shape [num_rot][num_pos]
* atom_list_done
Output:
* map_atoms, shape [num_pos].
Maps each atom in the full structure to its equivalent atom in
atom_list_done. (each entry will be an integer found in
atom_list_done)
* map_syms, shape [num_pos].
For each atom, provides the index of a rotation that maps it
into atom_list_done. (there might be more than one such
rotation, but only one will be returned) (each entry will be
an integer 0 <= i < num_rot)
"""
assert permutations.ndim == 2
num_pos = permutations.shape[1]
# filled with -1
map_atoms = np.zeros((num_pos,), dtype='intc') - 1
map_syms = np.zeros((num_pos,), dtype='intc') - 1
atom_list_done = set(atom_list_done)
for atom_todo in range(num_pos):
for (sym_index, permutation) in enumerate(permutations):
if permutation[atom_todo] in atom_list_done:
map_atoms[atom_todo] = permutation[atom_todo]
map_syms[atom_todo] = sym_index
break
else:
text = ("Input forces are not enough to calculate force constants,"
"or something wrong (e.g. crystal structure does not "
"match).")
print(textwrap.fill(text))
raise ValueError
assert set(map_atoms) & set(atom_list_done) == set(map_atoms)
assert -1 not in map_atoms
assert -1 not in map_syms
return map_atoms, map_syms | [
"def",
"_get_sym_mappings_from_permutations",
"(",
"permutations",
",",
"atom_list_done",
")",
":",
"assert",
"permutations",
".",
"ndim",
"==",
"2",
"num_pos",
"=",
"permutations",
".",
"shape",
"[",
"1",
"]",
"# filled with -1",
"map_atoms",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_pos",
",",
")",
",",
"dtype",
"=",
"'intc'",
")",
"-",
"1",
"map_syms",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_pos",
",",
")",
",",
"dtype",
"=",
"'intc'",
")",
"-",
"1",
"atom_list_done",
"=",
"set",
"(",
"atom_list_done",
")",
"for",
"atom_todo",
"in",
"range",
"(",
"num_pos",
")",
":",
"for",
"(",
"sym_index",
",",
"permutation",
")",
"in",
"enumerate",
"(",
"permutations",
")",
":",
"if",
"permutation",
"[",
"atom_todo",
"]",
"in",
"atom_list_done",
":",
"map_atoms",
"[",
"atom_todo",
"]",
"=",
"permutation",
"[",
"atom_todo",
"]",
"map_syms",
"[",
"atom_todo",
"]",
"=",
"sym_index",
"break",
"else",
":",
"text",
"=",
"(",
"\"Input forces are not enough to calculate force constants,\"",
"\"or something wrong (e.g. crystal structure does not \"",
"\"match).\"",
")",
"print",
"(",
"textwrap",
".",
"fill",
"(",
"text",
")",
")",
"raise",
"ValueError",
"assert",
"set",
"(",
"map_atoms",
")",
"&",
"set",
"(",
"atom_list_done",
")",
"==",
"set",
"(",
"map_atoms",
")",
"assert",
"-",
"1",
"not",
"in",
"map_atoms",
"assert",
"-",
"1",
"not",
"in",
"map_syms",
"return",
"map_atoms",
",",
"map_syms"
] | This can be thought of as computing 'map_atom_disp' and 'map_sym'
for all atoms, except done using permutations instead of by
computing overlaps.
Input:
* permutations, shape [num_rot][num_pos]
* atom_list_done
Output:
* map_atoms, shape [num_pos].
Maps each atom in the full structure to its equivalent atom in
atom_list_done. (each entry will be an integer found in
atom_list_done)
* map_syms, shape [num_pos].
For each atom, provides the index of a rotation that maps it
into atom_list_done. (there might be more than one such
rotation, but only one will be returned) (each entry will be
an integer 0 <= i < num_rot) | [
"This",
"can",
"be",
"thought",
"of",
"as",
"computing",
"map_atom_disp",
"and",
"map_sym",
"for",
"all",
"atoms",
"except",
"done",
"using",
"permutations",
"instead",
"of",
"by",
"computing",
"overlaps",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/force_constants.py#L778-L826 |
227,588 | atztogo/phonopy | phonopy/harmonic/displacement.py | get_least_displacements | def get_least_displacements(symmetry,
is_plusminus='auto',
is_diagonal=True,
is_trigonal=False,
log_level=0):
"""Return a set of displacements
Returns
-------
array_like
List of directions with respect to axes. This gives only the
symmetrically non equivalent directions. The format is like:
[[0, 1, 0, 0],
[7, 1, 0, 1], ...]
where each list is defined by:
First value: Atom index in supercell starting with 0
Second to fourth: If the direction is displaced or not (1, 0, or -1)
with respect to the axes.
"""
displacements = []
if is_diagonal:
directions = directions_diag
else:
directions = directions_axis
if log_level > 2:
print("Site point symmetry:")
for atom_num in symmetry.get_independent_atoms():
site_symmetry = symmetry.get_site_symmetry(atom_num)
if log_level > 2:
print("Atom %d" % (atom_num + 1))
for i, rot in enumerate(site_symmetry):
print("----%d----" % (i + 1))
for v in rot:
print("%2d %2d %2d" % tuple(v))
for disp in get_displacement(site_symmetry,
directions,
is_trigonal,
log_level):
displacements.append([atom_num,
disp[0], disp[1], disp[2]])
if is_plusminus == 'auto':
if is_minus_displacement(disp, site_symmetry):
displacements.append([atom_num,
-disp[0], -disp[1], -disp[2]])
elif is_plusminus is True:
displacements.append([atom_num,
-disp[0], -disp[1], -disp[2]])
return displacements | python | def get_least_displacements(symmetry,
is_plusminus='auto',
is_diagonal=True,
is_trigonal=False,
log_level=0):
"""Return a set of displacements
Returns
-------
array_like
List of directions with respect to axes. This gives only the
symmetrically non equivalent directions. The format is like:
[[0, 1, 0, 0],
[7, 1, 0, 1], ...]
where each list is defined by:
First value: Atom index in supercell starting with 0
Second to fourth: If the direction is displaced or not (1, 0, or -1)
with respect to the axes.
"""
displacements = []
if is_diagonal:
directions = directions_diag
else:
directions = directions_axis
if log_level > 2:
print("Site point symmetry:")
for atom_num in symmetry.get_independent_atoms():
site_symmetry = symmetry.get_site_symmetry(atom_num)
if log_level > 2:
print("Atom %d" % (atom_num + 1))
for i, rot in enumerate(site_symmetry):
print("----%d----" % (i + 1))
for v in rot:
print("%2d %2d %2d" % tuple(v))
for disp in get_displacement(site_symmetry,
directions,
is_trigonal,
log_level):
displacements.append([atom_num,
disp[0], disp[1], disp[2]])
if is_plusminus == 'auto':
if is_minus_displacement(disp, site_symmetry):
displacements.append([atom_num,
-disp[0], -disp[1], -disp[2]])
elif is_plusminus is True:
displacements.append([atom_num,
-disp[0], -disp[1], -disp[2]])
return displacements | [
"def",
"get_least_displacements",
"(",
"symmetry",
",",
"is_plusminus",
"=",
"'auto'",
",",
"is_diagonal",
"=",
"True",
",",
"is_trigonal",
"=",
"False",
",",
"log_level",
"=",
"0",
")",
":",
"displacements",
"=",
"[",
"]",
"if",
"is_diagonal",
":",
"directions",
"=",
"directions_diag",
"else",
":",
"directions",
"=",
"directions_axis",
"if",
"log_level",
">",
"2",
":",
"print",
"(",
"\"Site point symmetry:\"",
")",
"for",
"atom_num",
"in",
"symmetry",
".",
"get_independent_atoms",
"(",
")",
":",
"site_symmetry",
"=",
"symmetry",
".",
"get_site_symmetry",
"(",
"atom_num",
")",
"if",
"log_level",
">",
"2",
":",
"print",
"(",
"\"Atom %d\"",
"%",
"(",
"atom_num",
"+",
"1",
")",
")",
"for",
"i",
",",
"rot",
"in",
"enumerate",
"(",
"site_symmetry",
")",
":",
"print",
"(",
"\"----%d----\"",
"%",
"(",
"i",
"+",
"1",
")",
")",
"for",
"v",
"in",
"rot",
":",
"print",
"(",
"\"%2d %2d %2d\"",
"%",
"tuple",
"(",
"v",
")",
")",
"for",
"disp",
"in",
"get_displacement",
"(",
"site_symmetry",
",",
"directions",
",",
"is_trigonal",
",",
"log_level",
")",
":",
"displacements",
".",
"append",
"(",
"[",
"atom_num",
",",
"disp",
"[",
"0",
"]",
",",
"disp",
"[",
"1",
"]",
",",
"disp",
"[",
"2",
"]",
"]",
")",
"if",
"is_plusminus",
"==",
"'auto'",
":",
"if",
"is_minus_displacement",
"(",
"disp",
",",
"site_symmetry",
")",
":",
"displacements",
".",
"append",
"(",
"[",
"atom_num",
",",
"-",
"disp",
"[",
"0",
"]",
",",
"-",
"disp",
"[",
"1",
"]",
",",
"-",
"disp",
"[",
"2",
"]",
"]",
")",
"elif",
"is_plusminus",
"is",
"True",
":",
"displacements",
".",
"append",
"(",
"[",
"atom_num",
",",
"-",
"disp",
"[",
"0",
"]",
",",
"-",
"disp",
"[",
"1",
"]",
",",
"-",
"disp",
"[",
"2",
"]",
"]",
")",
"return",
"displacements"
] | Return a set of displacements
Returns
-------
array_like
List of directions with respect to axes. This gives only the
symmetrically non equivalent directions. The format is like:
[[0, 1, 0, 0],
[7, 1, 0, 1], ...]
where each list is defined by:
First value: Atom index in supercell starting with 0
Second to fourth: If the direction is displaced or not (1, 0, or -1)
with respect to the axes. | [
"Return",
"a",
"set",
"of",
"displacements"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/displacement.py#L74-L127 |
227,589 | atztogo/phonopy | phonopy/interface/FHIaims.py | read_aims | def read_aims(filename):
"""Method to read FHI-aims geometry files in phonopy context."""
lines = open(filename, 'r').readlines()
cell = []
is_frac = []
positions = []
symbols = []
magmoms = []
for line in lines:
fields = line.split()
if not len(fields):
continue
if fields[0] == "lattice_vector":
vec = lmap(float, fields[1:4])
cell.append(vec)
elif fields[0][0:4] == "atom":
if fields[0] == "atom":
frac = False
elif fields[0] == "atom_frac":
frac = True
pos = lmap(float, fields[1:4])
sym = fields[4]
is_frac.append(frac)
positions.append(pos)
symbols.append(sym)
magmoms.append(None)
# implicitly assuming that initial_moments line adhere to FHI-aims geometry.in specification,
# i.e. two subsequent initial_moments lines do not occur
# if they do, the value specified in the last line is taken here - without any warning
elif fields[0] == "initial_moment":
magmoms[-1] = float(fields[1])
for (n,frac) in enumerate(is_frac):
if frac:
pos = [ sum( [ positions[n][l] * cell[l][i] for l in range(3) ] ) for i in range(3) ]
positions[n] = pos
if None in magmoms:
atoms = Atoms(cell=cell, symbols=symbols, positions=positions)
else:
atoms = Atoms(cell=cell, symbols=symbols, positions=positions, magmoms=magmoms)
return atoms | python | def read_aims(filename):
"""Method to read FHI-aims geometry files in phonopy context."""
lines = open(filename, 'r').readlines()
cell = []
is_frac = []
positions = []
symbols = []
magmoms = []
for line in lines:
fields = line.split()
if not len(fields):
continue
if fields[0] == "lattice_vector":
vec = lmap(float, fields[1:4])
cell.append(vec)
elif fields[0][0:4] == "atom":
if fields[0] == "atom":
frac = False
elif fields[0] == "atom_frac":
frac = True
pos = lmap(float, fields[1:4])
sym = fields[4]
is_frac.append(frac)
positions.append(pos)
symbols.append(sym)
magmoms.append(None)
# implicitly assuming that initial_moments line adhere to FHI-aims geometry.in specification,
# i.e. two subsequent initial_moments lines do not occur
# if they do, the value specified in the last line is taken here - without any warning
elif fields[0] == "initial_moment":
magmoms[-1] = float(fields[1])
for (n,frac) in enumerate(is_frac):
if frac:
pos = [ sum( [ positions[n][l] * cell[l][i] for l in range(3) ] ) for i in range(3) ]
positions[n] = pos
if None in magmoms:
atoms = Atoms(cell=cell, symbols=symbols, positions=positions)
else:
atoms = Atoms(cell=cell, symbols=symbols, positions=positions, magmoms=magmoms)
return atoms | [
"def",
"read_aims",
"(",
"filename",
")",
":",
"lines",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
".",
"readlines",
"(",
")",
"cell",
"=",
"[",
"]",
"is_frac",
"=",
"[",
"]",
"positions",
"=",
"[",
"]",
"symbols",
"=",
"[",
"]",
"magmoms",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"fields",
"=",
"line",
".",
"split",
"(",
")",
"if",
"not",
"len",
"(",
"fields",
")",
":",
"continue",
"if",
"fields",
"[",
"0",
"]",
"==",
"\"lattice_vector\"",
":",
"vec",
"=",
"lmap",
"(",
"float",
",",
"fields",
"[",
"1",
":",
"4",
"]",
")",
"cell",
".",
"append",
"(",
"vec",
")",
"elif",
"fields",
"[",
"0",
"]",
"[",
"0",
":",
"4",
"]",
"==",
"\"atom\"",
":",
"if",
"fields",
"[",
"0",
"]",
"==",
"\"atom\"",
":",
"frac",
"=",
"False",
"elif",
"fields",
"[",
"0",
"]",
"==",
"\"atom_frac\"",
":",
"frac",
"=",
"True",
"pos",
"=",
"lmap",
"(",
"float",
",",
"fields",
"[",
"1",
":",
"4",
"]",
")",
"sym",
"=",
"fields",
"[",
"4",
"]",
"is_frac",
".",
"append",
"(",
"frac",
")",
"positions",
".",
"append",
"(",
"pos",
")",
"symbols",
".",
"append",
"(",
"sym",
")",
"magmoms",
".",
"append",
"(",
"None",
")",
"# implicitly assuming that initial_moments line adhere to FHI-aims geometry.in specification,",
"# i.e. two subsequent initial_moments lines do not occur",
"# if they do, the value specified in the last line is taken here - without any warning",
"elif",
"fields",
"[",
"0",
"]",
"==",
"\"initial_moment\"",
":",
"magmoms",
"[",
"-",
"1",
"]",
"=",
"float",
"(",
"fields",
"[",
"1",
"]",
")",
"for",
"(",
"n",
",",
"frac",
")",
"in",
"enumerate",
"(",
"is_frac",
")",
":",
"if",
"frac",
":",
"pos",
"=",
"[",
"sum",
"(",
"[",
"positions",
"[",
"n",
"]",
"[",
"l",
"]",
"*",
"cell",
"[",
"l",
"]",
"[",
"i",
"]",
"for",
"l",
"in",
"range",
"(",
"3",
")",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"3",
")",
"]",
"positions",
"[",
"n",
"]",
"=",
"pos",
"if",
"None",
"in",
"magmoms",
":",
"atoms",
"=",
"Atoms",
"(",
"cell",
"=",
"cell",
",",
"symbols",
"=",
"symbols",
",",
"positions",
"=",
"positions",
")",
"else",
":",
"atoms",
"=",
"Atoms",
"(",
"cell",
"=",
"cell",
",",
"symbols",
"=",
"symbols",
",",
"positions",
"=",
"positions",
",",
"magmoms",
"=",
"magmoms",
")",
"return",
"atoms"
] | Method to read FHI-aims geometry files in phonopy context. | [
"Method",
"to",
"read",
"FHI",
"-",
"aims",
"geometry",
"files",
"in",
"phonopy",
"context",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/FHIaims.py#L49-L92 |
227,590 | atztogo/phonopy | phonopy/interface/FHIaims.py | write_aims | def write_aims(filename, atoms):
"""Method to write FHI-aims geometry files in phonopy context."""
lines = ""
lines += "# geometry.in for FHI-aims \n"
lines += "# | generated by phonopy.FHIaims.write_aims() \n"
lattice_vector_line = "lattice_vector " + "%16.16f "*3 + "\n"
for vec in atoms.get_cell():
lines += lattice_vector_line % tuple(vec)
N = atoms.get_number_of_atoms()
atom_line = "atom " + "%16.16f "*3 + "%s \n"
positions = atoms.get_positions()
symbols = atoms.get_chemical_symbols()
initial_moment_line = "initial_moment %16.6f\n"
magmoms = atoms.get_magnetic_moments()
for n in range(N):
lines += atom_line % (tuple(positions[n]) + (symbols[n],))
if magmoms is not None:
lines += initial_moment_line % magmoms[n]
with open(filename, 'w') as f:
f.write(lines) | python | def write_aims(filename, atoms):
"""Method to write FHI-aims geometry files in phonopy context."""
lines = ""
lines += "# geometry.in for FHI-aims \n"
lines += "# | generated by phonopy.FHIaims.write_aims() \n"
lattice_vector_line = "lattice_vector " + "%16.16f "*3 + "\n"
for vec in atoms.get_cell():
lines += lattice_vector_line % tuple(vec)
N = atoms.get_number_of_atoms()
atom_line = "atom " + "%16.16f "*3 + "%s \n"
positions = atoms.get_positions()
symbols = atoms.get_chemical_symbols()
initial_moment_line = "initial_moment %16.6f\n"
magmoms = atoms.get_magnetic_moments()
for n in range(N):
lines += atom_line % (tuple(positions[n]) + (symbols[n],))
if magmoms is not None:
lines += initial_moment_line % magmoms[n]
with open(filename, 'w') as f:
f.write(lines) | [
"def",
"write_aims",
"(",
"filename",
",",
"atoms",
")",
":",
"lines",
"=",
"\"\"",
"lines",
"+=",
"\"# geometry.in for FHI-aims \\n\"",
"lines",
"+=",
"\"# | generated by phonopy.FHIaims.write_aims() \\n\"",
"lattice_vector_line",
"=",
"\"lattice_vector \"",
"+",
"\"%16.16f \"",
"*",
"3",
"+",
"\"\\n\"",
"for",
"vec",
"in",
"atoms",
".",
"get_cell",
"(",
")",
":",
"lines",
"+=",
"lattice_vector_line",
"%",
"tuple",
"(",
"vec",
")",
"N",
"=",
"atoms",
".",
"get_number_of_atoms",
"(",
")",
"atom_line",
"=",
"\"atom \"",
"+",
"\"%16.16f \"",
"*",
"3",
"+",
"\"%s \\n\"",
"positions",
"=",
"atoms",
".",
"get_positions",
"(",
")",
"symbols",
"=",
"atoms",
".",
"get_chemical_symbols",
"(",
")",
"initial_moment_line",
"=",
"\"initial_moment %16.6f\\n\"",
"magmoms",
"=",
"atoms",
".",
"get_magnetic_moments",
"(",
")",
"for",
"n",
"in",
"range",
"(",
"N",
")",
":",
"lines",
"+=",
"atom_line",
"%",
"(",
"tuple",
"(",
"positions",
"[",
"n",
"]",
")",
"+",
"(",
"symbols",
"[",
"n",
"]",
",",
")",
")",
"if",
"magmoms",
"is",
"not",
"None",
":",
"lines",
"+=",
"initial_moment_line",
"%",
"magmoms",
"[",
"n",
"]",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"lines",
")"
] | Method to write FHI-aims geometry files in phonopy context. | [
"Method",
"to",
"write",
"FHI",
"-",
"aims",
"geometry",
"files",
"in",
"phonopy",
"context",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/FHIaims.py#L95-L121 |
227,591 | atztogo/phonopy | phonopy/interface/FHIaims.py | read_aims_output | def read_aims_output(filename):
""" Read FHI-aims output and
return geometry, energy and forces from last self-consistency iteration"""
lines = open(filename, 'r').readlines()
l = 0
N = 0
while l < len(lines):
line = lines[l]
if "| Number of atoms" in line:
N = int(line.split()[5])
elif "| Unit cell:" in line:
cell = []
for i in range(3):
l += 1
vec = lmap(float, lines[l].split()[1:4])
cell.append(vec)
elif ("Atomic structure:" in line) or ("Updated atomic structure:" in line):
if "Atomic structure:" in line:
i_sym = 3
i_pos_min = 4 ; i_pos_max = 7
elif "Updated atomic structure:" in line:
i_sym = 4
i_pos_min = 1 ; i_pos_max = 4
l += 1
symbols = []
positions = []
for n in range(N):
l += 1
fields = lines[l].split()
sym = fields[i_sym]
pos = lmap(float, fields[i_pos_min:i_pos_max])
symbols.append(sym)
positions.append(pos)
elif "Total atomic forces" in line:
forces = []
for i in range(N):
l += 1
force = lmap(float, lines[l].split()[-3:])
forces.append(force)
l += 1
atoms = Atoms_with_forces(cell=cell, symbols=symbols, positions=positions)
atoms.forces = forces
return atoms | python | def read_aims_output(filename):
""" Read FHI-aims output and
return geometry, energy and forces from last self-consistency iteration"""
lines = open(filename, 'r').readlines()
l = 0
N = 0
while l < len(lines):
line = lines[l]
if "| Number of atoms" in line:
N = int(line.split()[5])
elif "| Unit cell:" in line:
cell = []
for i in range(3):
l += 1
vec = lmap(float, lines[l].split()[1:4])
cell.append(vec)
elif ("Atomic structure:" in line) or ("Updated atomic structure:" in line):
if "Atomic structure:" in line:
i_sym = 3
i_pos_min = 4 ; i_pos_max = 7
elif "Updated atomic structure:" in line:
i_sym = 4
i_pos_min = 1 ; i_pos_max = 4
l += 1
symbols = []
positions = []
for n in range(N):
l += 1
fields = lines[l].split()
sym = fields[i_sym]
pos = lmap(float, fields[i_pos_min:i_pos_max])
symbols.append(sym)
positions.append(pos)
elif "Total atomic forces" in line:
forces = []
for i in range(N):
l += 1
force = lmap(float, lines[l].split()[-3:])
forces.append(force)
l += 1
atoms = Atoms_with_forces(cell=cell, symbols=symbols, positions=positions)
atoms.forces = forces
return atoms | [
"def",
"read_aims_output",
"(",
"filename",
")",
":",
"lines",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
".",
"readlines",
"(",
")",
"l",
"=",
"0",
"N",
"=",
"0",
"while",
"l",
"<",
"len",
"(",
"lines",
")",
":",
"line",
"=",
"lines",
"[",
"l",
"]",
"if",
"\"| Number of atoms\"",
"in",
"line",
":",
"N",
"=",
"int",
"(",
"line",
".",
"split",
"(",
")",
"[",
"5",
"]",
")",
"elif",
"\"| Unit cell:\"",
"in",
"line",
":",
"cell",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"l",
"+=",
"1",
"vec",
"=",
"lmap",
"(",
"float",
",",
"lines",
"[",
"l",
"]",
".",
"split",
"(",
")",
"[",
"1",
":",
"4",
"]",
")",
"cell",
".",
"append",
"(",
"vec",
")",
"elif",
"(",
"\"Atomic structure:\"",
"in",
"line",
")",
"or",
"(",
"\"Updated atomic structure:\"",
"in",
"line",
")",
":",
"if",
"\"Atomic structure:\"",
"in",
"line",
":",
"i_sym",
"=",
"3",
"i_pos_min",
"=",
"4",
"i_pos_max",
"=",
"7",
"elif",
"\"Updated atomic structure:\"",
"in",
"line",
":",
"i_sym",
"=",
"4",
"i_pos_min",
"=",
"1",
"i_pos_max",
"=",
"4",
"l",
"+=",
"1",
"symbols",
"=",
"[",
"]",
"positions",
"=",
"[",
"]",
"for",
"n",
"in",
"range",
"(",
"N",
")",
":",
"l",
"+=",
"1",
"fields",
"=",
"lines",
"[",
"l",
"]",
".",
"split",
"(",
")",
"sym",
"=",
"fields",
"[",
"i_sym",
"]",
"pos",
"=",
"lmap",
"(",
"float",
",",
"fields",
"[",
"i_pos_min",
":",
"i_pos_max",
"]",
")",
"symbols",
".",
"append",
"(",
"sym",
")",
"positions",
".",
"append",
"(",
"pos",
")",
"elif",
"\"Total atomic forces\"",
"in",
"line",
":",
"forces",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"N",
")",
":",
"l",
"+=",
"1",
"force",
"=",
"lmap",
"(",
"float",
",",
"lines",
"[",
"l",
"]",
".",
"split",
"(",
")",
"[",
"-",
"3",
":",
"]",
")",
"forces",
".",
"append",
"(",
"force",
")",
"l",
"+=",
"1",
"atoms",
"=",
"Atoms_with_forces",
"(",
"cell",
"=",
"cell",
",",
"symbols",
"=",
"symbols",
",",
"positions",
"=",
"positions",
")",
"atoms",
".",
"forces",
"=",
"forces",
"return",
"atoms"
] | Read FHI-aims output and
return geometry, energy and forces from last self-consistency iteration | [
"Read",
"FHI",
"-",
"aims",
"output",
"and",
"return",
"geometry",
"energy",
"and",
"forces",
"from",
"last",
"self",
"-",
"consistency",
"iteration"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/FHIaims.py#L132-L178 |
227,592 | atztogo/phonopy | phonopy/structure/symmetry.py | find_primitive | def find_primitive(cell, symprec=1e-5):
"""
A primitive cell is searched in the input cell. When a primitive
cell is found, an object of Atoms class of the primitive cell is
returned. When not, None is returned.
"""
lattice, positions, numbers = spg.find_primitive(cell.totuple(), symprec)
if lattice is None:
return None
else:
return Atoms(numbers=numbers,
scaled_positions=positions,
cell=lattice,
pbc=True) | python | def find_primitive(cell, symprec=1e-5):
"""
A primitive cell is searched in the input cell. When a primitive
cell is found, an object of Atoms class of the primitive cell is
returned. When not, None is returned.
"""
lattice, positions, numbers = spg.find_primitive(cell.totuple(), symprec)
if lattice is None:
return None
else:
return Atoms(numbers=numbers,
scaled_positions=positions,
cell=lattice,
pbc=True) | [
"def",
"find_primitive",
"(",
"cell",
",",
"symprec",
"=",
"1e-5",
")",
":",
"lattice",
",",
"positions",
",",
"numbers",
"=",
"spg",
".",
"find_primitive",
"(",
"cell",
".",
"totuple",
"(",
")",
",",
"symprec",
")",
"if",
"lattice",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",
"Atoms",
"(",
"numbers",
"=",
"numbers",
",",
"scaled_positions",
"=",
"positions",
",",
"cell",
"=",
"lattice",
",",
"pbc",
"=",
"True",
")"
] | A primitive cell is searched in the input cell. When a primitive
cell is found, an object of Atoms class of the primitive cell is
returned. When not, None is returned. | [
"A",
"primitive",
"cell",
"is",
"searched",
"in",
"the",
"input",
"cell",
".",
"When",
"a",
"primitive",
"cell",
"is",
"found",
"an",
"object",
"of",
"Atoms",
"class",
"of",
"the",
"primitive",
"cell",
"is",
"returned",
".",
"When",
"not",
"None",
"is",
"returned",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/symmetry.py#L300-L313 |
227,593 | atztogo/phonopy | phonopy/structure/symmetry.py | elaborate_borns_and_epsilon | def elaborate_borns_and_epsilon(ucell,
borns,
epsilon,
primitive_matrix=None,
supercell_matrix=None,
is_symmetry=True,
symmetrize_tensors=False,
symprec=1e-5):
"""Symmetrize Born effective charges and dielectric constants and
extract Born effective charges of symmetrically independent atoms
for primitive cell.
Args:
ucell (Atoms): Unit cell structure
borns (np.array): Born effective charges of ucell
epsilon (np.array): Dielectric constant tensor
Returns:
(np.array) Born effective charges of symmetrically independent atoms
in primitive cell
(np.array) Dielectric constant
(np.array) Atomic index mapping table from supercell to primitive cell
of independent atoms
Raises:
AssertionError: Inconsistency of number of atoms or Born effective
charges.
Warning:
Broken symmetry of Born effective charges
"""
assert len(borns) == ucell.get_number_of_atoms(), \
"num_atom %d != len(borns) %d" % (ucell.get_number_of_atoms(),
len(borns))
if symmetrize_tensors:
borns_, epsilon_ = symmetrize_borns_and_epsilon(
borns,
epsilon,
ucell,
symprec=symprec,
is_symmetry=is_symmetry)
else:
borns_ = borns
epsilon_ = epsilon
indeps_in_supercell, indeps_in_unitcell = _extract_independent_atoms(
ucell,
primitive_matrix=primitive_matrix,
supercell_matrix=supercell_matrix,
is_symmetry=is_symmetry,
symprec=symprec)
return borns_[indeps_in_unitcell].copy(), epsilon_, indeps_in_supercell | python | def elaborate_borns_and_epsilon(ucell,
borns,
epsilon,
primitive_matrix=None,
supercell_matrix=None,
is_symmetry=True,
symmetrize_tensors=False,
symprec=1e-5):
"""Symmetrize Born effective charges and dielectric constants and
extract Born effective charges of symmetrically independent atoms
for primitive cell.
Args:
ucell (Atoms): Unit cell structure
borns (np.array): Born effective charges of ucell
epsilon (np.array): Dielectric constant tensor
Returns:
(np.array) Born effective charges of symmetrically independent atoms
in primitive cell
(np.array) Dielectric constant
(np.array) Atomic index mapping table from supercell to primitive cell
of independent atoms
Raises:
AssertionError: Inconsistency of number of atoms or Born effective
charges.
Warning:
Broken symmetry of Born effective charges
"""
assert len(borns) == ucell.get_number_of_atoms(), \
"num_atom %d != len(borns) %d" % (ucell.get_number_of_atoms(),
len(borns))
if symmetrize_tensors:
borns_, epsilon_ = symmetrize_borns_and_epsilon(
borns,
epsilon,
ucell,
symprec=symprec,
is_symmetry=is_symmetry)
else:
borns_ = borns
epsilon_ = epsilon
indeps_in_supercell, indeps_in_unitcell = _extract_independent_atoms(
ucell,
primitive_matrix=primitive_matrix,
supercell_matrix=supercell_matrix,
is_symmetry=is_symmetry,
symprec=symprec)
return borns_[indeps_in_unitcell].copy(), epsilon_, indeps_in_supercell | [
"def",
"elaborate_borns_and_epsilon",
"(",
"ucell",
",",
"borns",
",",
"epsilon",
",",
"primitive_matrix",
"=",
"None",
",",
"supercell_matrix",
"=",
"None",
",",
"is_symmetry",
"=",
"True",
",",
"symmetrize_tensors",
"=",
"False",
",",
"symprec",
"=",
"1e-5",
")",
":",
"assert",
"len",
"(",
"borns",
")",
"==",
"ucell",
".",
"get_number_of_atoms",
"(",
")",
",",
"\"num_atom %d != len(borns) %d\"",
"%",
"(",
"ucell",
".",
"get_number_of_atoms",
"(",
")",
",",
"len",
"(",
"borns",
")",
")",
"if",
"symmetrize_tensors",
":",
"borns_",
",",
"epsilon_",
"=",
"symmetrize_borns_and_epsilon",
"(",
"borns",
",",
"epsilon",
",",
"ucell",
",",
"symprec",
"=",
"symprec",
",",
"is_symmetry",
"=",
"is_symmetry",
")",
"else",
":",
"borns_",
"=",
"borns",
"epsilon_",
"=",
"epsilon",
"indeps_in_supercell",
",",
"indeps_in_unitcell",
"=",
"_extract_independent_atoms",
"(",
"ucell",
",",
"primitive_matrix",
"=",
"primitive_matrix",
",",
"supercell_matrix",
"=",
"supercell_matrix",
",",
"is_symmetry",
"=",
"is_symmetry",
",",
"symprec",
"=",
"symprec",
")",
"return",
"borns_",
"[",
"indeps_in_unitcell",
"]",
".",
"copy",
"(",
")",
",",
"epsilon_",
",",
"indeps_in_supercell"
] | Symmetrize Born effective charges and dielectric constants and
extract Born effective charges of symmetrically independent atoms
for primitive cell.
Args:
ucell (Atoms): Unit cell structure
borns (np.array): Born effective charges of ucell
epsilon (np.array): Dielectric constant tensor
Returns:
(np.array) Born effective charges of symmetrically independent atoms
in primitive cell
(np.array) Dielectric constant
(np.array) Atomic index mapping table from supercell to primitive cell
of independent atoms
Raises:
AssertionError: Inconsistency of number of atoms or Born effective
charges.
Warning:
Broken symmetry of Born effective charges | [
"Symmetrize",
"Born",
"effective",
"charges",
"and",
"dielectric",
"constants",
"and",
"extract",
"Born",
"effective",
"charges",
"of",
"symmetrically",
"independent",
"atoms",
"for",
"primitive",
"cell",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/symmetry.py#L343-L399 |
227,594 | atztogo/phonopy | phonopy/structure/symmetry.py | symmetrize_borns_and_epsilon | def symmetrize_borns_and_epsilon(borns,
epsilon,
ucell,
primitive_matrix=None,
supercell_matrix=None,
symprec=1e-5,
is_symmetry=True):
"""Symmetrize Born effective charges and dielectric tensor
Parameters
----------
borns: array_like
Born effective charges.
shape=(unitcell_atoms, 3, 3)
dtype='double'
epsilon: array_like
Dielectric constant
shape=(3, 3)
dtype='double'
ucell: PhonopyAtoms
Unit cell
primitive_matrix: array_like, optional
Primitive matrix. This is used to select Born effective charges in
primitive cell. If None (default), Born effective charges in unit cell
are returned.
shape=(3, 3)
dtype='double'
supercell_matrix: array_like, optional
Supercell matrix. This is used to select Born effective charges in
**primitive cell**. Supercell matrix is needed because primitive
cell is created first creating supercell from unit cell, then
the primitive cell is created from the supercell. If None (defautl),
1x1x1 supercell is created.
shape=(3, 3)
dtype='int'
symprec: float, optional
Symmetry tolerance. Default is 1e-5
is_symmetry: bool, optinal
By setting False, symmetrization can be switched off. Default is True.
"""
lattice = ucell.get_cell()
positions = ucell.get_scaled_positions()
u_sym = Symmetry(ucell, is_symmetry=is_symmetry, symprec=symprec)
rotations = u_sym.get_symmetry_operations()['rotations']
translations = u_sym.get_symmetry_operations()['translations']
ptg_ops = u_sym.get_pointgroup_operations()
epsilon_ = _symmetrize_2nd_rank_tensor(epsilon, ptg_ops, lattice)
for i, Z in enumerate(borns):
site_sym = u_sym.get_site_symmetry(i)
Z = _symmetrize_2nd_rank_tensor(Z, site_sym, lattice)
borns_ = np.zeros_like(borns)
for i in range(len(borns)):
count = 0
for r, t in zip(rotations, translations):
count += 1
diff = np.dot(positions, r.T) + t - positions[i]
diff -= np.rint(diff)
dist = np.sqrt(np.sum(np.dot(diff, lattice) ** 2, axis=1))
j = np.nonzero(dist < symprec)[0][0]
r_cart = similarity_transformation(lattice.T, r)
borns_[i] += similarity_transformation(r_cart, borns[j])
borns_[i] /= count
sum_born = borns_.sum(axis=0) / len(borns_)
borns_ -= sum_born
if (abs(borns - borns_) > 0.1).any():
lines = ["Born effective charge symmetry is largely broken. "
"Largest different among elements: "
"%s" % np.amax(abs(borns - borns_))]
import warnings
warnings.warn("\n".join(lines))
if primitive_matrix is None:
return borns_, epsilon_
else:
scell, pcell = _get_supercell_and_primitive(
ucell,
primitive_matrix=primitive_matrix,
supercell_matrix=supercell_matrix,
symprec=symprec)
idx = [scell.u2u_map[i] for i in scell.s2u_map[pcell.p2s_map]]
return borns_[idx], epsilon_ | python | def symmetrize_borns_and_epsilon(borns,
epsilon,
ucell,
primitive_matrix=None,
supercell_matrix=None,
symprec=1e-5,
is_symmetry=True):
"""Symmetrize Born effective charges and dielectric tensor
Parameters
----------
borns: array_like
Born effective charges.
shape=(unitcell_atoms, 3, 3)
dtype='double'
epsilon: array_like
Dielectric constant
shape=(3, 3)
dtype='double'
ucell: PhonopyAtoms
Unit cell
primitive_matrix: array_like, optional
Primitive matrix. This is used to select Born effective charges in
primitive cell. If None (default), Born effective charges in unit cell
are returned.
shape=(3, 3)
dtype='double'
supercell_matrix: array_like, optional
Supercell matrix. This is used to select Born effective charges in
**primitive cell**. Supercell matrix is needed because primitive
cell is created first creating supercell from unit cell, then
the primitive cell is created from the supercell. If None (defautl),
1x1x1 supercell is created.
shape=(3, 3)
dtype='int'
symprec: float, optional
Symmetry tolerance. Default is 1e-5
is_symmetry: bool, optinal
By setting False, symmetrization can be switched off. Default is True.
"""
lattice = ucell.get_cell()
positions = ucell.get_scaled_positions()
u_sym = Symmetry(ucell, is_symmetry=is_symmetry, symprec=symprec)
rotations = u_sym.get_symmetry_operations()['rotations']
translations = u_sym.get_symmetry_operations()['translations']
ptg_ops = u_sym.get_pointgroup_operations()
epsilon_ = _symmetrize_2nd_rank_tensor(epsilon, ptg_ops, lattice)
for i, Z in enumerate(borns):
site_sym = u_sym.get_site_symmetry(i)
Z = _symmetrize_2nd_rank_tensor(Z, site_sym, lattice)
borns_ = np.zeros_like(borns)
for i in range(len(borns)):
count = 0
for r, t in zip(rotations, translations):
count += 1
diff = np.dot(positions, r.T) + t - positions[i]
diff -= np.rint(diff)
dist = np.sqrt(np.sum(np.dot(diff, lattice) ** 2, axis=1))
j = np.nonzero(dist < symprec)[0][0]
r_cart = similarity_transformation(lattice.T, r)
borns_[i] += similarity_transformation(r_cart, borns[j])
borns_[i] /= count
sum_born = borns_.sum(axis=0) / len(borns_)
borns_ -= sum_born
if (abs(borns - borns_) > 0.1).any():
lines = ["Born effective charge symmetry is largely broken. "
"Largest different among elements: "
"%s" % np.amax(abs(borns - borns_))]
import warnings
warnings.warn("\n".join(lines))
if primitive_matrix is None:
return borns_, epsilon_
else:
scell, pcell = _get_supercell_and_primitive(
ucell,
primitive_matrix=primitive_matrix,
supercell_matrix=supercell_matrix,
symprec=symprec)
idx = [scell.u2u_map[i] for i in scell.s2u_map[pcell.p2s_map]]
return borns_[idx], epsilon_ | [
"def",
"symmetrize_borns_and_epsilon",
"(",
"borns",
",",
"epsilon",
",",
"ucell",
",",
"primitive_matrix",
"=",
"None",
",",
"supercell_matrix",
"=",
"None",
",",
"symprec",
"=",
"1e-5",
",",
"is_symmetry",
"=",
"True",
")",
":",
"lattice",
"=",
"ucell",
".",
"get_cell",
"(",
")",
"positions",
"=",
"ucell",
".",
"get_scaled_positions",
"(",
")",
"u_sym",
"=",
"Symmetry",
"(",
"ucell",
",",
"is_symmetry",
"=",
"is_symmetry",
",",
"symprec",
"=",
"symprec",
")",
"rotations",
"=",
"u_sym",
".",
"get_symmetry_operations",
"(",
")",
"[",
"'rotations'",
"]",
"translations",
"=",
"u_sym",
".",
"get_symmetry_operations",
"(",
")",
"[",
"'translations'",
"]",
"ptg_ops",
"=",
"u_sym",
".",
"get_pointgroup_operations",
"(",
")",
"epsilon_",
"=",
"_symmetrize_2nd_rank_tensor",
"(",
"epsilon",
",",
"ptg_ops",
",",
"lattice",
")",
"for",
"i",
",",
"Z",
"in",
"enumerate",
"(",
"borns",
")",
":",
"site_sym",
"=",
"u_sym",
".",
"get_site_symmetry",
"(",
"i",
")",
"Z",
"=",
"_symmetrize_2nd_rank_tensor",
"(",
"Z",
",",
"site_sym",
",",
"lattice",
")",
"borns_",
"=",
"np",
".",
"zeros_like",
"(",
"borns",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"borns",
")",
")",
":",
"count",
"=",
"0",
"for",
"r",
",",
"t",
"in",
"zip",
"(",
"rotations",
",",
"translations",
")",
":",
"count",
"+=",
"1",
"diff",
"=",
"np",
".",
"dot",
"(",
"positions",
",",
"r",
".",
"T",
")",
"+",
"t",
"-",
"positions",
"[",
"i",
"]",
"diff",
"-=",
"np",
".",
"rint",
"(",
"diff",
")",
"dist",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"sum",
"(",
"np",
".",
"dot",
"(",
"diff",
",",
"lattice",
")",
"**",
"2",
",",
"axis",
"=",
"1",
")",
")",
"j",
"=",
"np",
".",
"nonzero",
"(",
"dist",
"<",
"symprec",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"r_cart",
"=",
"similarity_transformation",
"(",
"lattice",
".",
"T",
",",
"r",
")",
"borns_",
"[",
"i",
"]",
"+=",
"similarity_transformation",
"(",
"r_cart",
",",
"borns",
"[",
"j",
"]",
")",
"borns_",
"[",
"i",
"]",
"/=",
"count",
"sum_born",
"=",
"borns_",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
"/",
"len",
"(",
"borns_",
")",
"borns_",
"-=",
"sum_born",
"if",
"(",
"abs",
"(",
"borns",
"-",
"borns_",
")",
">",
"0.1",
")",
".",
"any",
"(",
")",
":",
"lines",
"=",
"[",
"\"Born effective charge symmetry is largely broken. \"",
"\"Largest different among elements: \"",
"\"%s\"",
"%",
"np",
".",
"amax",
"(",
"abs",
"(",
"borns",
"-",
"borns_",
")",
")",
"]",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"\\n\"",
".",
"join",
"(",
"lines",
")",
")",
"if",
"primitive_matrix",
"is",
"None",
":",
"return",
"borns_",
",",
"epsilon_",
"else",
":",
"scell",
",",
"pcell",
"=",
"_get_supercell_and_primitive",
"(",
"ucell",
",",
"primitive_matrix",
"=",
"primitive_matrix",
",",
"supercell_matrix",
"=",
"supercell_matrix",
",",
"symprec",
"=",
"symprec",
")",
"idx",
"=",
"[",
"scell",
".",
"u2u_map",
"[",
"i",
"]",
"for",
"i",
"in",
"scell",
".",
"s2u_map",
"[",
"pcell",
".",
"p2s_map",
"]",
"]",
"return",
"borns_",
"[",
"idx",
"]",
",",
"epsilon_"
] | Symmetrize Born effective charges and dielectric tensor
Parameters
----------
borns: array_like
Born effective charges.
shape=(unitcell_atoms, 3, 3)
dtype='double'
epsilon: array_like
Dielectric constant
shape=(3, 3)
dtype='double'
ucell: PhonopyAtoms
Unit cell
primitive_matrix: array_like, optional
Primitive matrix. This is used to select Born effective charges in
primitive cell. If None (default), Born effective charges in unit cell
are returned.
shape=(3, 3)
dtype='double'
supercell_matrix: array_like, optional
Supercell matrix. This is used to select Born effective charges in
**primitive cell**. Supercell matrix is needed because primitive
cell is created first creating supercell from unit cell, then
the primitive cell is created from the supercell. If None (defautl),
1x1x1 supercell is created.
shape=(3, 3)
dtype='int'
symprec: float, optional
Symmetry tolerance. Default is 1e-5
is_symmetry: bool, optinal
By setting False, symmetrization can be switched off. Default is True. | [
"Symmetrize",
"Born",
"effective",
"charges",
"and",
"dielectric",
"tensor"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/symmetry.py#L402-L488 |
227,595 | atztogo/phonopy | phonopy/interface/dftbp.py | read_dftbp | def read_dftbp(filename):
""" Reads DFTB+ structure files in gen format.
Args:
filename: name of the gen-file to be read
Returns:
atoms: an object of the phonopy.Atoms class, representing the structure
found in filename
"""
infile = open(filename, 'r')
lines = infile.readlines()
# remove any comments
for ss in lines:
if ss.strip().startswith('#'):
lines.remove(ss)
natoms = int(lines[0].split()[0])
symbols = lines[1].split()
if (lines[0].split()[1].lower() == 'f'):
is_scaled = True
scale_pos = 1
scale_latvecs = dftbpToBohr
else:
is_scaled = False
scale_pos = dftbpToBohr
scale_latvecs = dftbpToBohr
# assign positions and expanded symbols
positions = []
expaned_symbols = []
for ii in range(2, natoms+2):
lsplit = lines[ii].split()
expaned_symbols.append(symbols[int(lsplit[1]) - 1])
positions.append([float(ss)*scale_pos for ss in lsplit[2:5]])
# origin is ignored, may be used in future
origin = [float(ss) for ss in lines[natoms+2].split()]
# assign coords of unitcell
cell = []
for ii in range(natoms+3, natoms+6):
lsplit = lines[ii].split()
cell.append([float(ss)*scale_latvecs for ss in lsplit[:3]])
cell = np.array(cell)
if is_scaled:
atoms = Atoms(symbols=expaned_symbols,
cell=cell,
scaled_positions=positions)
else:
atoms = Atoms(symbols=expaned_symbols,
cell=cell,
positions=positions)
return atoms | python | def read_dftbp(filename):
""" Reads DFTB+ structure files in gen format.
Args:
filename: name of the gen-file to be read
Returns:
atoms: an object of the phonopy.Atoms class, representing the structure
found in filename
"""
infile = open(filename, 'r')
lines = infile.readlines()
# remove any comments
for ss in lines:
if ss.strip().startswith('#'):
lines.remove(ss)
natoms = int(lines[0].split()[0])
symbols = lines[1].split()
if (lines[0].split()[1].lower() == 'f'):
is_scaled = True
scale_pos = 1
scale_latvecs = dftbpToBohr
else:
is_scaled = False
scale_pos = dftbpToBohr
scale_latvecs = dftbpToBohr
# assign positions and expanded symbols
positions = []
expaned_symbols = []
for ii in range(2, natoms+2):
lsplit = lines[ii].split()
expaned_symbols.append(symbols[int(lsplit[1]) - 1])
positions.append([float(ss)*scale_pos for ss in lsplit[2:5]])
# origin is ignored, may be used in future
origin = [float(ss) for ss in lines[natoms+2].split()]
# assign coords of unitcell
cell = []
for ii in range(natoms+3, natoms+6):
lsplit = lines[ii].split()
cell.append([float(ss)*scale_latvecs for ss in lsplit[:3]])
cell = np.array(cell)
if is_scaled:
atoms = Atoms(symbols=expaned_symbols,
cell=cell,
scaled_positions=positions)
else:
atoms = Atoms(symbols=expaned_symbols,
cell=cell,
positions=positions)
return atoms | [
"def",
"read_dftbp",
"(",
"filename",
")",
":",
"infile",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"lines",
"=",
"infile",
".",
"readlines",
"(",
")",
"# remove any comments",
"for",
"ss",
"in",
"lines",
":",
"if",
"ss",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'#'",
")",
":",
"lines",
".",
"remove",
"(",
"ss",
")",
"natoms",
"=",
"int",
"(",
"lines",
"[",
"0",
"]",
".",
"split",
"(",
")",
"[",
"0",
"]",
")",
"symbols",
"=",
"lines",
"[",
"1",
"]",
".",
"split",
"(",
")",
"if",
"(",
"lines",
"[",
"0",
"]",
".",
"split",
"(",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"==",
"'f'",
")",
":",
"is_scaled",
"=",
"True",
"scale_pos",
"=",
"1",
"scale_latvecs",
"=",
"dftbpToBohr",
"else",
":",
"is_scaled",
"=",
"False",
"scale_pos",
"=",
"dftbpToBohr",
"scale_latvecs",
"=",
"dftbpToBohr",
"# assign positions and expanded symbols",
"positions",
"=",
"[",
"]",
"expaned_symbols",
"=",
"[",
"]",
"for",
"ii",
"in",
"range",
"(",
"2",
",",
"natoms",
"+",
"2",
")",
":",
"lsplit",
"=",
"lines",
"[",
"ii",
"]",
".",
"split",
"(",
")",
"expaned_symbols",
".",
"append",
"(",
"symbols",
"[",
"int",
"(",
"lsplit",
"[",
"1",
"]",
")",
"-",
"1",
"]",
")",
"positions",
".",
"append",
"(",
"[",
"float",
"(",
"ss",
")",
"*",
"scale_pos",
"for",
"ss",
"in",
"lsplit",
"[",
"2",
":",
"5",
"]",
"]",
")",
"# origin is ignored, may be used in future",
"origin",
"=",
"[",
"float",
"(",
"ss",
")",
"for",
"ss",
"in",
"lines",
"[",
"natoms",
"+",
"2",
"]",
".",
"split",
"(",
")",
"]",
"# assign coords of unitcell",
"cell",
"=",
"[",
"]",
"for",
"ii",
"in",
"range",
"(",
"natoms",
"+",
"3",
",",
"natoms",
"+",
"6",
")",
":",
"lsplit",
"=",
"lines",
"[",
"ii",
"]",
".",
"split",
"(",
")",
"cell",
".",
"append",
"(",
"[",
"float",
"(",
"ss",
")",
"*",
"scale_latvecs",
"for",
"ss",
"in",
"lsplit",
"[",
":",
"3",
"]",
"]",
")",
"cell",
"=",
"np",
".",
"array",
"(",
"cell",
")",
"if",
"is_scaled",
":",
"atoms",
"=",
"Atoms",
"(",
"symbols",
"=",
"expaned_symbols",
",",
"cell",
"=",
"cell",
",",
"scaled_positions",
"=",
"positions",
")",
"else",
":",
"atoms",
"=",
"Atoms",
"(",
"symbols",
"=",
"expaned_symbols",
",",
"cell",
"=",
"cell",
",",
"positions",
"=",
"positions",
")",
"return",
"atoms"
] | Reads DFTB+ structure files in gen format.
Args:
filename: name of the gen-file to be read
Returns:
atoms: an object of the phonopy.Atoms class, representing the structure
found in filename | [
"Reads",
"DFTB",
"+",
"structure",
"files",
"in",
"gen",
"format",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/dftbp.py#L72-L135 |
227,596 | atztogo/phonopy | phonopy/interface/dftbp.py | get_reduced_symbols | def get_reduced_symbols(symbols):
"""Reduces expanded list of symbols.
Args:
symbols: list containing any chemical symbols as often as
the atom appears in the structure
Returns:
reduced_symbols: any symbols appears only once
"""
reduced_symbols = []
for ss in symbols:
if not (ss in reduced_symbols):
reduced_symbols.append(ss)
return reduced_symbols | python | def get_reduced_symbols(symbols):
"""Reduces expanded list of symbols.
Args:
symbols: list containing any chemical symbols as often as
the atom appears in the structure
Returns:
reduced_symbols: any symbols appears only once
"""
reduced_symbols = []
for ss in symbols:
if not (ss in reduced_symbols):
reduced_symbols.append(ss)
return reduced_symbols | [
"def",
"get_reduced_symbols",
"(",
"symbols",
")",
":",
"reduced_symbols",
"=",
"[",
"]",
"for",
"ss",
"in",
"symbols",
":",
"if",
"not",
"(",
"ss",
"in",
"reduced_symbols",
")",
":",
"reduced_symbols",
".",
"append",
"(",
"ss",
")",
"return",
"reduced_symbols"
] | Reduces expanded list of symbols.
Args:
symbols: list containing any chemical symbols as often as
the atom appears in the structure
Returns:
reduced_symbols: any symbols appears only once | [
"Reduces",
"expanded",
"list",
"of",
"symbols",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/dftbp.py#L140-L157 |
227,597 | atztogo/phonopy | phonopy/interface/dftbp.py | write_dftbp | def write_dftbp(filename, atoms):
"""Writes DFTB+ readable, gen-formatted structure files
Args:
filename: name of the gen-file to be written
atoms: object containing information about structure
"""
scale_pos = dftbpToBohr
lines = ""
# 1. line, use absolute positions
natoms = atoms.get_number_of_atoms()
lines += str(natoms)
lines += ' S \n'
# 2. line
expaned_symbols = atoms.get_chemical_symbols()
symbols = get_reduced_symbols(expaned_symbols)
lines += ' '.join(symbols) + '\n'
atom_numbers = []
for ss in expaned_symbols:
atom_numbers.append(symbols.index(ss) + 1)
positions = atoms.get_positions()/scale_pos
for ii in range(natoms):
pos = positions[ii]
pos_str = "{:3d} {:3d} {:20.15f} {:20.15f} {:20.15f}\n".format(
ii + 1, atom_numbers[ii], pos[0], pos[1], pos[2])
lines += pos_str
# origin arbitrary
lines +='0.0 0.0 0.0\n'
cell = atoms.get_cell()/scale_pos
for ii in range(3):
cell_str = "{:20.15f} {:20.15f} {:20.15f}\n".format(
cell[ii][0], cell[ii][1], cell[ii][2])
lines += cell_str
outfile = open(filename, 'w')
outfile.write(lines) | python | def write_dftbp(filename, atoms):
"""Writes DFTB+ readable, gen-formatted structure files
Args:
filename: name of the gen-file to be written
atoms: object containing information about structure
"""
scale_pos = dftbpToBohr
lines = ""
# 1. line, use absolute positions
natoms = atoms.get_number_of_atoms()
lines += str(natoms)
lines += ' S \n'
# 2. line
expaned_symbols = atoms.get_chemical_symbols()
symbols = get_reduced_symbols(expaned_symbols)
lines += ' '.join(symbols) + '\n'
atom_numbers = []
for ss in expaned_symbols:
atom_numbers.append(symbols.index(ss) + 1)
positions = atoms.get_positions()/scale_pos
for ii in range(natoms):
pos = positions[ii]
pos_str = "{:3d} {:3d} {:20.15f} {:20.15f} {:20.15f}\n".format(
ii + 1, atom_numbers[ii], pos[0], pos[1], pos[2])
lines += pos_str
# origin arbitrary
lines +='0.0 0.0 0.0\n'
cell = atoms.get_cell()/scale_pos
for ii in range(3):
cell_str = "{:20.15f} {:20.15f} {:20.15f}\n".format(
cell[ii][0], cell[ii][1], cell[ii][2])
lines += cell_str
outfile = open(filename, 'w')
outfile.write(lines) | [
"def",
"write_dftbp",
"(",
"filename",
",",
"atoms",
")",
":",
"scale_pos",
"=",
"dftbpToBohr",
"lines",
"=",
"\"\"",
"# 1. line, use absolute positions",
"natoms",
"=",
"atoms",
".",
"get_number_of_atoms",
"(",
")",
"lines",
"+=",
"str",
"(",
"natoms",
")",
"lines",
"+=",
"' S \\n'",
"# 2. line",
"expaned_symbols",
"=",
"atoms",
".",
"get_chemical_symbols",
"(",
")",
"symbols",
"=",
"get_reduced_symbols",
"(",
"expaned_symbols",
")",
"lines",
"+=",
"' '",
".",
"join",
"(",
"symbols",
")",
"+",
"'\\n'",
"atom_numbers",
"=",
"[",
"]",
"for",
"ss",
"in",
"expaned_symbols",
":",
"atom_numbers",
".",
"append",
"(",
"symbols",
".",
"index",
"(",
"ss",
")",
"+",
"1",
")",
"positions",
"=",
"atoms",
".",
"get_positions",
"(",
")",
"/",
"scale_pos",
"for",
"ii",
"in",
"range",
"(",
"natoms",
")",
":",
"pos",
"=",
"positions",
"[",
"ii",
"]",
"pos_str",
"=",
"\"{:3d} {:3d} {:20.15f} {:20.15f} {:20.15f}\\n\"",
".",
"format",
"(",
"ii",
"+",
"1",
",",
"atom_numbers",
"[",
"ii",
"]",
",",
"pos",
"[",
"0",
"]",
",",
"pos",
"[",
"1",
"]",
",",
"pos",
"[",
"2",
"]",
")",
"lines",
"+=",
"pos_str",
"# origin arbitrary",
"lines",
"+=",
"'0.0 0.0 0.0\\n'",
"cell",
"=",
"atoms",
".",
"get_cell",
"(",
")",
"/",
"scale_pos",
"for",
"ii",
"in",
"range",
"(",
"3",
")",
":",
"cell_str",
"=",
"\"{:20.15f} {:20.15f} {:20.15f}\\n\"",
".",
"format",
"(",
"cell",
"[",
"ii",
"]",
"[",
"0",
"]",
",",
"cell",
"[",
"ii",
"]",
"[",
"1",
"]",
",",
"cell",
"[",
"ii",
"]",
"[",
"2",
"]",
")",
"lines",
"+=",
"cell_str",
"outfile",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"outfile",
".",
"write",
"(",
"lines",
")"
] | Writes DFTB+ readable, gen-formatted structure files
Args:
filename: name of the gen-file to be written
atoms: object containing information about structure | [
"Writes",
"DFTB",
"+",
"readable",
"gen",
"-",
"formatted",
"structure",
"files"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/dftbp.py#L159-L203 |
227,598 | atztogo/phonopy | phonopy/interface/dftbp.py | write_supercells_with_displacements | def write_supercells_with_displacements(supercell, cells_with_disps, filename="geo.gen"):
"""Writes perfect supercell and supercells with displacements
Args:
supercell: perfect supercell
cells_with_disps: supercells with displaced atoms
filename: root-filename
"""
# original cell
write_dftbp(filename + "S", supercell)
# displaced cells
for ii in range(len(cells_with_disps)):
write_dftbp(filename + "S-{:03d}".format(ii+1), cells_with_disps[ii]) | python | def write_supercells_with_displacements(supercell, cells_with_disps, filename="geo.gen"):
"""Writes perfect supercell and supercells with displacements
Args:
supercell: perfect supercell
cells_with_disps: supercells with displaced atoms
filename: root-filename
"""
# original cell
write_dftbp(filename + "S", supercell)
# displaced cells
for ii in range(len(cells_with_disps)):
write_dftbp(filename + "S-{:03d}".format(ii+1), cells_with_disps[ii]) | [
"def",
"write_supercells_with_displacements",
"(",
"supercell",
",",
"cells_with_disps",
",",
"filename",
"=",
"\"geo.gen\"",
")",
":",
"# original cell",
"write_dftbp",
"(",
"filename",
"+",
"\"S\"",
",",
"supercell",
")",
"# displaced cells",
"for",
"ii",
"in",
"range",
"(",
"len",
"(",
"cells_with_disps",
")",
")",
":",
"write_dftbp",
"(",
"filename",
"+",
"\"S-{:03d}\"",
".",
"format",
"(",
"ii",
"+",
"1",
")",
",",
"cells_with_disps",
"[",
"ii",
"]",
")"
] | Writes perfect supercell and supercells with displacements
Args:
supercell: perfect supercell
cells_with_disps: supercells with displaced atoms
filename: root-filename | [
"Writes",
"perfect",
"supercell",
"and",
"supercells",
"with",
"displacements"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/dftbp.py#L205-L219 |
227,599 | atztogo/phonopy | phonopy/interface/__init__.py | get_interface_mode | def get_interface_mode(args):
"""Return calculator name
The calculator name is obtained from command option arguments where
argparse is used. The argument attribute name has to be
"{calculator}_mode". Then this method returns {calculator}.
"""
calculator_list = ['wien2k', 'abinit', 'qe', 'elk', 'siesta', 'cp2k',
'crystal', 'vasp', 'dftbp', 'turbomole']
for calculator in calculator_list:
mode = "%s_mode" % calculator
if mode in args and args.__dict__[mode]:
return calculator
return None | python | def get_interface_mode(args):
"""Return calculator name
The calculator name is obtained from command option arguments where
argparse is used. The argument attribute name has to be
"{calculator}_mode". Then this method returns {calculator}.
"""
calculator_list = ['wien2k', 'abinit', 'qe', 'elk', 'siesta', 'cp2k',
'crystal', 'vasp', 'dftbp', 'turbomole']
for calculator in calculator_list:
mode = "%s_mode" % calculator
if mode in args and args.__dict__[mode]:
return calculator
return None | [
"def",
"get_interface_mode",
"(",
"args",
")",
":",
"calculator_list",
"=",
"[",
"'wien2k'",
",",
"'abinit'",
",",
"'qe'",
",",
"'elk'",
",",
"'siesta'",
",",
"'cp2k'",
",",
"'crystal'",
",",
"'vasp'",
",",
"'dftbp'",
",",
"'turbomole'",
"]",
"for",
"calculator",
"in",
"calculator_list",
":",
"mode",
"=",
"\"%s_mode\"",
"%",
"calculator",
"if",
"mode",
"in",
"args",
"and",
"args",
".",
"__dict__",
"[",
"mode",
"]",
":",
"return",
"calculator",
"return",
"None"
] | Return calculator name
The calculator name is obtained from command option arguments where
argparse is used. The argument attribute name has to be
"{calculator}_mode". Then this method returns {calculator}. | [
"Return",
"calculator",
"name"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/__init__.py#L40-L55 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.