id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
241,300 | pyusb/pyusb | tools/vcp_terminal.py | ftdi_to_clkbits | def ftdi_to_clkbits(baudrate): # from libftdi
"""
10,27 => divisor = 10000, rate = 300
88,13 => divisor = 5000, rate = 600
C4,09 => divisor = 2500, rate = 1200
E2,04 => divisor = 1250, rate = 2,400
71,02 => divisor = 625, rate = 4,800
38,41 => divisor = 312.5, rate = 9,600
D0,80 => divisor = 208.25, rate = 14406
9C,80 => divisor = 156, rate = 19,230
4E,C0 => divisor = 78, rate = 38,461
34,00 => divisor = 52, rate = 57,692
1A,00 => divisor = 26, rate = 115,384
0D,00 => divisor = 13, rate = 230,769
"""
clk = 48000000
clk_div = 16
frac_code = [0, 3, 2, 4, 1, 5, 6, 7]
actual_baud = 0
if baudrate >= clk / clk_div:
encoded_divisor = 0
actual_baud = (clk // clk_div)
elif baudrate >= clk / (clk_div + clk_div / 2):
encoded_divisor = 1
actual_baud = clk // (clk_div + clk_div // 2)
elif baudrate >= clk / (2 * clk_div):
encoded_divisor = 2
actual_baud = clk // (2 * clk_div)
else:
# We divide by 16 to have 3 fractional bits and one bit for rounding
divisor = clk * 16 // clk_div // baudrate
best_divisor = (divisor + 1) // 2
if best_divisor > 0x20000:
best_divisor = 0x1ffff
actual_baud = clk * 16 // clk_div // best_divisor
actual_baud = (actual_baud + 1) // 2
encoded_divisor = ((best_divisor >> 3) +
(frac_code[best_divisor & 0x7] << 14))
value = encoded_divisor & 0xFFFF
index = encoded_divisor >> 16
return actual_baud, value, index | python | def ftdi_to_clkbits(baudrate): # from libftdi
clk = 48000000
clk_div = 16
frac_code = [0, 3, 2, 4, 1, 5, 6, 7]
actual_baud = 0
if baudrate >= clk / clk_div:
encoded_divisor = 0
actual_baud = (clk // clk_div)
elif baudrate >= clk / (clk_div + clk_div / 2):
encoded_divisor = 1
actual_baud = clk // (clk_div + clk_div // 2)
elif baudrate >= clk / (2 * clk_div):
encoded_divisor = 2
actual_baud = clk // (2 * clk_div)
else:
# We divide by 16 to have 3 fractional bits and one bit for rounding
divisor = clk * 16 // clk_div // baudrate
best_divisor = (divisor + 1) // 2
if best_divisor > 0x20000:
best_divisor = 0x1ffff
actual_baud = clk * 16 // clk_div // best_divisor
actual_baud = (actual_baud + 1) // 2
encoded_divisor = ((best_divisor >> 3) +
(frac_code[best_divisor & 0x7] << 14))
value = encoded_divisor & 0xFFFF
index = encoded_divisor >> 16
return actual_baud, value, index | [
"def",
"ftdi_to_clkbits",
"(",
"baudrate",
")",
":",
"# from libftdi",
"clk",
"=",
"48000000",
"clk_div",
"=",
"16",
"frac_code",
"=",
"[",
"0",
",",
"3",
",",
"2",
",",
"4",
",",
"1",
",",
"5",
",",
"6",
",",
"7",
"]",
"actual_baud",
"=",
"0",
"... | 10,27 => divisor = 10000, rate = 300
88,13 => divisor = 5000, rate = 600
C4,09 => divisor = 2500, rate = 1200
E2,04 => divisor = 1250, rate = 2,400
71,02 => divisor = 625, rate = 4,800
38,41 => divisor = 312.5, rate = 9,600
D0,80 => divisor = 208.25, rate = 14406
9C,80 => divisor = 156, rate = 19,230
4E,C0 => divisor = 78, rate = 38,461
34,00 => divisor = 52, rate = 57,692
1A,00 => divisor = 26, rate = 115,384
0D,00 => divisor = 13, rate = 230,769 | [
"10",
"27",
"=",
">",
"divisor",
"=",
"10000",
"rate",
"=",
"300",
"88",
"13",
"=",
">",
"divisor",
"=",
"5000",
"rate",
"=",
"600",
"C4",
"09",
"=",
">",
"divisor",
"=",
"2500",
"rate",
"=",
"1200",
"E2",
"04",
"=",
">",
"divisor",
"=",
"1250"... | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/tools/vcp_terminal.py#L576-L617 |
241,301 | pyusb/pyusb | tools/vcp_terminal.py | ComPort._read | def _read(self):
""" check ep for data, add it to queue and sleep for interval """
while self._rxactive:
try:
rv = self._ep_in.read(self._ep_in.wMaxPacketSize)
if self._isFTDI:
status = rv[:2] # FTDI prepends 2 flow control characters,
# modem status and line status of the UART
if status[0] != 1 or status[1] != 0x60:
log.info(
"USB Status: 0x{0:02X} 0x{1:02X}".format(
*status))
rv = rv[2:]
for rvi in rv:
self._rxqueue.put(rvi)
except usb.USBError as e:
log.warn("USB Error on _read {}".format(e))
return
time.sleep(self._rxinterval) | python | def _read(self):
while self._rxactive:
try:
rv = self._ep_in.read(self._ep_in.wMaxPacketSize)
if self._isFTDI:
status = rv[:2] # FTDI prepends 2 flow control characters,
# modem status and line status of the UART
if status[0] != 1 or status[1] != 0x60:
log.info(
"USB Status: 0x{0:02X} 0x{1:02X}".format(
*status))
rv = rv[2:]
for rvi in rv:
self._rxqueue.put(rvi)
except usb.USBError as e:
log.warn("USB Error on _read {}".format(e))
return
time.sleep(self._rxinterval) | [
"def",
"_read",
"(",
"self",
")",
":",
"while",
"self",
".",
"_rxactive",
":",
"try",
":",
"rv",
"=",
"self",
".",
"_ep_in",
".",
"read",
"(",
"self",
".",
"_ep_in",
".",
"wMaxPacketSize",
")",
"if",
"self",
".",
"_isFTDI",
":",
"status",
"=",
"rv"... | check ep for data, add it to queue and sleep for interval | [
"check",
"ep",
"for",
"data",
"add",
"it",
"to",
"queue",
"and",
"sleep",
"for",
"interval"
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/tools/vcp_terminal.py#L187-L206 |
241,302 | pyusb/pyusb | tools/vcp_terminal.py | ComPort._resetFTDI | def _resetFTDI(self):
""" reset the FTDI device
"""
if not self._isFTDI:
return
txdir = 0 # 0:OUT, 1:IN
req_type = 2 # 0:std, 1:class, 2:vendor
recipient = 0 # 0:device, 1:interface, 2:endpoint, 3:other
req_type = (txdir << 7) + (req_type << 5) + recipient
self.device.ctrl_transfer(
bmRequestType=req_type,
bRequest=0, # RESET
wValue=0, # RESET
wIndex=1,
data_or_wLength=0) | python | def _resetFTDI(self):
if not self._isFTDI:
return
txdir = 0 # 0:OUT, 1:IN
req_type = 2 # 0:std, 1:class, 2:vendor
recipient = 0 # 0:device, 1:interface, 2:endpoint, 3:other
req_type = (txdir << 7) + (req_type << 5) + recipient
self.device.ctrl_transfer(
bmRequestType=req_type,
bRequest=0, # RESET
wValue=0, # RESET
wIndex=1,
data_or_wLength=0) | [
"def",
"_resetFTDI",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_isFTDI",
":",
"return",
"txdir",
"=",
"0",
"# 0:OUT, 1:IN",
"req_type",
"=",
"2",
"# 0:std, 1:class, 2:vendor",
"recipient",
"=",
"0",
"# 0:device, 1:interface, 2:endpoint, 3:other",
"req_type",... | reset the FTDI device | [
"reset",
"the",
"FTDI",
"device"
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/tools/vcp_terminal.py#L359-L373 |
241,303 | pyusb/pyusb | usb/legacy.py | busses | def busses():
r"""Returns a tuple with the usb busses."""
return (Bus(g) for k, g in groupby(
sorted(core.find(find_all=True), key=lambda d: d.bus),
lambda d: d.bus)) | python | def busses():
r"""Returns a tuple with the usb busses."""
return (Bus(g) for k, g in groupby(
sorted(core.find(find_all=True), key=lambda d: d.bus),
lambda d: d.bus)) | [
"def",
"busses",
"(",
")",
":",
"return",
"(",
"Bus",
"(",
"g",
")",
"for",
"k",
",",
"g",
"in",
"groupby",
"(",
"sorted",
"(",
"core",
".",
"find",
"(",
"find_all",
"=",
"True",
")",
",",
"key",
"=",
"lambda",
"d",
":",
"d",
".",
"bus",
")",... | r"""Returns a tuple with the usb busses. | [
"r",
"Returns",
"a",
"tuple",
"with",
"the",
"usb",
"busses",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L337-L341 |
241,304 | pyusb/pyusb | usb/legacy.py | DeviceHandle.bulkWrite | def bulkWrite(self, endpoint, buffer, timeout = 100):
r"""Perform a bulk write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written.
"""
return self.dev.write(endpoint, buffer, timeout) | python | def bulkWrite(self, endpoint, buffer, timeout = 100):
r"""Perform a bulk write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written.
"""
return self.dev.write(endpoint, buffer, timeout) | [
"def",
"bulkWrite",
"(",
"self",
",",
"endpoint",
",",
"buffer",
",",
"timeout",
"=",
"100",
")",
":",
"return",
"self",
".",
"dev",
".",
"write",
"(",
"endpoint",
",",
"buffer",
",",
"timeout",
")"
] | r"""Perform a bulk write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written. | [
"r",
"Perform",
"a",
"bulk",
"write",
"request",
"to",
"the",
"endpoint",
"specified",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L131-L141 |
241,305 | pyusb/pyusb | usb/legacy.py | DeviceHandle.bulkRead | def bulkRead(self, endpoint, size, timeout = 100):
r"""Performs a bulk read request to the endpoint specified.
Arguments:
endpoint: endpoint number.
size: number of bytes to read.
timeout: operation timeout in milliseconds. (default: 100)
Returns a tuple with the data read.
"""
return self.dev.read(endpoint, size, timeout) | python | def bulkRead(self, endpoint, size, timeout = 100):
r"""Performs a bulk read request to the endpoint specified.
Arguments:
endpoint: endpoint number.
size: number of bytes to read.
timeout: operation timeout in milliseconds. (default: 100)
Returns a tuple with the data read.
"""
return self.dev.read(endpoint, size, timeout) | [
"def",
"bulkRead",
"(",
"self",
",",
"endpoint",
",",
"size",
",",
"timeout",
"=",
"100",
")",
":",
"return",
"self",
".",
"dev",
".",
"read",
"(",
"endpoint",
",",
"size",
",",
"timeout",
")"
] | r"""Performs a bulk read request to the endpoint specified.
Arguments:
endpoint: endpoint number.
size: number of bytes to read.
timeout: operation timeout in milliseconds. (default: 100)
Returns a tuple with the data read. | [
"r",
"Performs",
"a",
"bulk",
"read",
"request",
"to",
"the",
"endpoint",
"specified",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L143-L152 |
241,306 | pyusb/pyusb | usb/legacy.py | DeviceHandle.interruptWrite | def interruptWrite(self, endpoint, buffer, timeout = 100):
r"""Perform a interrupt write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written.
"""
return self.dev.write(endpoint, buffer, timeout) | python | def interruptWrite(self, endpoint, buffer, timeout = 100):
r"""Perform a interrupt write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written.
"""
return self.dev.write(endpoint, buffer, timeout) | [
"def",
"interruptWrite",
"(",
"self",
",",
"endpoint",
",",
"buffer",
",",
"timeout",
"=",
"100",
")",
":",
"return",
"self",
".",
"dev",
".",
"write",
"(",
"endpoint",
",",
"buffer",
",",
"timeout",
")"
] | r"""Perform a interrupt write request to the endpoint specified.
Arguments:
endpoint: endpoint number.
buffer: sequence data buffer to write.
This parameter can be any sequence type.
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written. | [
"r",
"Perform",
"a",
"interrupt",
"write",
"request",
"to",
"the",
"endpoint",
"specified",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L154-L164 |
241,307 | pyusb/pyusb | usb/legacy.py | DeviceHandle.interruptRead | def interruptRead(self, endpoint, size, timeout = 100):
r"""Performs a interrupt read request to the endpoint specified.
Arguments:
endpoint: endpoint number.
size: number of bytes to read.
timeout: operation timeout in milliseconds. (default: 100)
Returns a tuple with the data read.
"""
return self.dev.read(endpoint, size, timeout) | python | def interruptRead(self, endpoint, size, timeout = 100):
r"""Performs a interrupt read request to the endpoint specified.
Arguments:
endpoint: endpoint number.
size: number of bytes to read.
timeout: operation timeout in milliseconds. (default: 100)
Returns a tuple with the data read.
"""
return self.dev.read(endpoint, size, timeout) | [
"def",
"interruptRead",
"(",
"self",
",",
"endpoint",
",",
"size",
",",
"timeout",
"=",
"100",
")",
":",
"return",
"self",
".",
"dev",
".",
"read",
"(",
"endpoint",
",",
"size",
",",
"timeout",
")"
] | r"""Performs a interrupt read request to the endpoint specified.
Arguments:
endpoint: endpoint number.
size: number of bytes to read.
timeout: operation timeout in milliseconds. (default: 100)
Returns a tuple with the data read. | [
"r",
"Performs",
"a",
"interrupt",
"read",
"request",
"to",
"the",
"endpoint",
"specified",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L166-L175 |
241,308 | pyusb/pyusb | usb/legacy.py | DeviceHandle.controlMsg | def controlMsg(self, requestType, request, buffer, value = 0, index = 0, timeout = 100):
r"""Perform a control request to the default control pipe on a device.
Arguments:
requestType: specifies the direction of data flow, the type
of request, and the recipient.
request: specifies the request.
buffer: if the transfer is a write transfer, buffer is a sequence
with the transfer data, otherwise, buffer is the number of
bytes to read.
value: specific information to pass to the device. (default: 0)
index: specific information to pass to the device. (default: 0)
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written.
"""
return self.dev.ctrl_transfer(
requestType,
request,
wValue = value,
wIndex = index,
data_or_wLength = buffer,
timeout = timeout) | python | def controlMsg(self, requestType, request, buffer, value = 0, index = 0, timeout = 100):
r"""Perform a control request to the default control pipe on a device.
Arguments:
requestType: specifies the direction of data flow, the type
of request, and the recipient.
request: specifies the request.
buffer: if the transfer is a write transfer, buffer is a sequence
with the transfer data, otherwise, buffer is the number of
bytes to read.
value: specific information to pass to the device. (default: 0)
index: specific information to pass to the device. (default: 0)
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written.
"""
return self.dev.ctrl_transfer(
requestType,
request,
wValue = value,
wIndex = index,
data_or_wLength = buffer,
timeout = timeout) | [
"def",
"controlMsg",
"(",
"self",
",",
"requestType",
",",
"request",
",",
"buffer",
",",
"value",
"=",
"0",
",",
"index",
"=",
"0",
",",
"timeout",
"=",
"100",
")",
":",
"return",
"self",
".",
"dev",
".",
"ctrl_transfer",
"(",
"requestType",
",",
"r... | r"""Perform a control request to the default control pipe on a device.
Arguments:
requestType: specifies the direction of data flow, the type
of request, and the recipient.
request: specifies the request.
buffer: if the transfer is a write transfer, buffer is a sequence
with the transfer data, otherwise, buffer is the number of
bytes to read.
value: specific information to pass to the device. (default: 0)
index: specific information to pass to the device. (default: 0)
timeout: operation timeout in milliseconds. (default: 100)
Returns the number of bytes written. | [
"r",
"Perform",
"a",
"control",
"request",
"to",
"the",
"default",
"control",
"pipe",
"on",
"a",
"device",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L177-L198 |
241,309 | pyusb/pyusb | usb/legacy.py | DeviceHandle.claimInterface | def claimInterface(self, interface):
r"""Claims the interface with the Operating System.
Arguments:
interface: interface number or an Interface object.
"""
if isinstance(interface, Interface):
interface = interface.interfaceNumber
util.claim_interface(self.dev, interface)
self.__claimed_interface = interface | python | def claimInterface(self, interface):
r"""Claims the interface with the Operating System.
Arguments:
interface: interface number or an Interface object.
"""
if isinstance(interface, Interface):
interface = interface.interfaceNumber
util.claim_interface(self.dev, interface)
self.__claimed_interface = interface | [
"def",
"claimInterface",
"(",
"self",
",",
"interface",
")",
":",
"if",
"isinstance",
"(",
"interface",
",",
"Interface",
")",
":",
"interface",
"=",
"interface",
".",
"interfaceNumber",
"util",
".",
"claim_interface",
"(",
"self",
".",
"dev",
",",
"interfac... | r"""Claims the interface with the Operating System.
Arguments:
interface: interface number or an Interface object. | [
"r",
"Claims",
"the",
"interface",
"with",
"the",
"Operating",
"System",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L208-L218 |
241,310 | pyusb/pyusb | usb/legacy.py | DeviceHandle.releaseInterface | def releaseInterface(self):
r"""Release an interface previously claimed with claimInterface."""
util.release_interface(self.dev, self.__claimed_interface)
self.__claimed_interface = -1 | python | def releaseInterface(self):
r"""Release an interface previously claimed with claimInterface."""
util.release_interface(self.dev, self.__claimed_interface)
self.__claimed_interface = -1 | [
"def",
"releaseInterface",
"(",
"self",
")",
":",
"util",
".",
"release_interface",
"(",
"self",
".",
"dev",
",",
"self",
".",
"__claimed_interface",
")",
"self",
".",
"__claimed_interface",
"=",
"-",
"1"
] | r"""Release an interface previously claimed with claimInterface. | [
"r",
"Release",
"an",
"interface",
"previously",
"claimed",
"with",
"claimInterface",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L220-L223 |
241,311 | pyusb/pyusb | usb/legacy.py | DeviceHandle.setConfiguration | def setConfiguration(self, configuration):
r"""Set the active configuration of a device.
Arguments:
configuration: a configuration value or a Configuration object.
"""
if isinstance(configuration, Configuration):
configuration = configuration.value
self.dev.set_configuration(configuration) | python | def setConfiguration(self, configuration):
r"""Set the active configuration of a device.
Arguments:
configuration: a configuration value or a Configuration object.
"""
if isinstance(configuration, Configuration):
configuration = configuration.value
self.dev.set_configuration(configuration) | [
"def",
"setConfiguration",
"(",
"self",
",",
"configuration",
")",
":",
"if",
"isinstance",
"(",
"configuration",
",",
"Configuration",
")",
":",
"configuration",
"=",
"configuration",
".",
"value",
"self",
".",
"dev",
".",
"set_configuration",
"(",
"configurati... | r"""Set the active configuration of a device.
Arguments:
configuration: a configuration value or a Configuration object. | [
"r",
"Set",
"the",
"active",
"configuration",
"of",
"a",
"device",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L238-L247 |
241,312 | pyusb/pyusb | usb/legacy.py | DeviceHandle.setAltInterface | def setAltInterface(self, alternate):
r"""Sets the active alternate setting of the current interface.
Arguments:
alternate: an alternate setting number or an Interface object.
"""
if isinstance(alternate, Interface):
alternate = alternate.alternateSetting
self.dev.set_interface_altsetting(self.__claimed_interface, alternate) | python | def setAltInterface(self, alternate):
r"""Sets the active alternate setting of the current interface.
Arguments:
alternate: an alternate setting number or an Interface object.
"""
if isinstance(alternate, Interface):
alternate = alternate.alternateSetting
self.dev.set_interface_altsetting(self.__claimed_interface, alternate) | [
"def",
"setAltInterface",
"(",
"self",
",",
"alternate",
")",
":",
"if",
"isinstance",
"(",
"alternate",
",",
"Interface",
")",
":",
"alternate",
"=",
"alternate",
".",
"alternateSetting",
"self",
".",
"dev",
".",
"set_interface_altsetting",
"(",
"self",
".",
... | r"""Sets the active alternate setting of the current interface.
Arguments:
alternate: an alternate setting number or an Interface object. | [
"r",
"Sets",
"the",
"active",
"alternate",
"setting",
"of",
"the",
"current",
"interface",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L249-L258 |
241,313 | pyusb/pyusb | usb/legacy.py | DeviceHandle.getString | def getString(self, index, length, langid = None):
r"""Retrieve the string descriptor specified by index
and langid from a device.
Arguments:
index: index of descriptor in the device.
length: number of bytes of the string (ignored)
langid: Language ID. If it is omitted, the first
language will be used.
"""
return util.get_string(self.dev, index, langid).encode('ascii') | python | def getString(self, index, length, langid = None):
r"""Retrieve the string descriptor specified by index
and langid from a device.
Arguments:
index: index of descriptor in the device.
length: number of bytes of the string (ignored)
langid: Language ID. If it is omitted, the first
language will be used.
"""
return util.get_string(self.dev, index, langid).encode('ascii') | [
"def",
"getString",
"(",
"self",
",",
"index",
",",
"length",
",",
"langid",
"=",
"None",
")",
":",
"return",
"util",
".",
"get_string",
"(",
"self",
".",
"dev",
",",
"index",
",",
"langid",
")",
".",
"encode",
"(",
"'ascii'",
")"
] | r"""Retrieve the string descriptor specified by index
and langid from a device.
Arguments:
index: index of descriptor in the device.
length: number of bytes of the string (ignored)
langid: Language ID. If it is omitted, the first
language will be used. | [
"r",
"Retrieve",
"the",
"string",
"descriptor",
"specified",
"by",
"index",
"and",
"langid",
"from",
"a",
"device",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L260-L270 |
241,314 | pyusb/pyusb | usb/legacy.py | DeviceHandle.getDescriptor | def getDescriptor(self, desc_type, desc_index, length, endpoint = -1):
r"""Retrieves a descriptor from the device identified by the type
and index of the descriptor.
Arguments:
desc_type: descriptor type.
desc_index: index of the descriptor.
len: descriptor length.
endpoint: ignored.
"""
return control.get_descriptor(self.dev, length, desc_type, desc_index) | python | def getDescriptor(self, desc_type, desc_index, length, endpoint = -1):
r"""Retrieves a descriptor from the device identified by the type
and index of the descriptor.
Arguments:
desc_type: descriptor type.
desc_index: index of the descriptor.
len: descriptor length.
endpoint: ignored.
"""
return control.get_descriptor(self.dev, length, desc_type, desc_index) | [
"def",
"getDescriptor",
"(",
"self",
",",
"desc_type",
",",
"desc_index",
",",
"length",
",",
"endpoint",
"=",
"-",
"1",
")",
":",
"return",
"control",
".",
"get_descriptor",
"(",
"self",
".",
"dev",
",",
"length",
",",
"desc_type",
",",
"desc_index",
")... | r"""Retrieves a descriptor from the device identified by the type
and index of the descriptor.
Arguments:
desc_type: descriptor type.
desc_index: index of the descriptor.
len: descriptor length.
endpoint: ignored. | [
"r",
"Retrieves",
"a",
"descriptor",
"from",
"the",
"device",
"identified",
"by",
"the",
"type",
"and",
"index",
"of",
"the",
"descriptor",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/legacy.py#L272-L282 |
241,315 | pyusb/pyusb | usb/backend/__init__.py | IBackend.get_endpoint_descriptor | def get_endpoint_descriptor(self, dev, ep, intf, alt, config):
r"""Return an endpoint descriptor of the given device.
The object returned is required to have all the Endpoint Descriptor
fields acessible as member variables. They must be convertible (but
not required to be equal) to the int type.
The ep parameter is the endpoint logical index (not the bEndpointAddress
field) of the endpoint descriptor desired. dev, intf, alt and config are the same
values already described in the get_interface_descriptor() method.
"""
_not_implemented(self.get_endpoint_descriptor) | python | def get_endpoint_descriptor(self, dev, ep, intf, alt, config):
r"""Return an endpoint descriptor of the given device.
The object returned is required to have all the Endpoint Descriptor
fields acessible as member variables. They must be convertible (but
not required to be equal) to the int type.
The ep parameter is the endpoint logical index (not the bEndpointAddress
field) of the endpoint descriptor desired. dev, intf, alt and config are the same
values already described in the get_interface_descriptor() method.
"""
_not_implemented(self.get_endpoint_descriptor) | [
"def",
"get_endpoint_descriptor",
"(",
"self",
",",
"dev",
",",
"ep",
",",
"intf",
",",
"alt",
",",
"config",
")",
":",
"_not_implemented",
"(",
"self",
".",
"get_endpoint_descriptor",
")"
] | r"""Return an endpoint descriptor of the given device.
The object returned is required to have all the Endpoint Descriptor
fields acessible as member variables. They must be convertible (but
not required to be equal) to the int type.
The ep parameter is the endpoint logical index (not the bEndpointAddress
field) of the endpoint descriptor desired. dev, intf, alt and config are the same
values already described in the get_interface_descriptor() method. | [
"r",
"Return",
"an",
"endpoint",
"descriptor",
"of",
"the",
"given",
"device",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/backend/__init__.py#L140-L151 |
241,316 | 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 |
241,317 | 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 |
241,318 | 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 |
241,319 | 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 |
241,320 | 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 |
241,321 | 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 |
241,322 | 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 |
241,323 | pyusb/pyusb | usb/util.py | find_descriptor | def find_descriptor(desc, find_all=False, custom_match=None, **args):
r"""Find an inner descriptor.
find_descriptor works in the same way as the core.find() function does,
but it acts on general descriptor objects. For example, suppose you
have a Device object called dev and want a Configuration of this
object with its bConfigurationValue equals to 1, the code would
be like so:
>>> cfg = util.find_descriptor(dev, bConfigurationValue=1)
You can use any field of the Descriptor as a match criteria, and you
can supply a customized match just like core.find() does. The
find_descriptor function also accepts the find_all parameter to get
an iterator instead of just one descriptor.
"""
def desc_iter(**kwargs):
for d in desc:
tests = (val == getattr(d, key) for key, val in kwargs.items())
if _interop._all(tests) and (custom_match is None or custom_match(d)):
yield d
if find_all:
return desc_iter(**args)
else:
try:
return _interop._next(desc_iter(**args))
except StopIteration:
return None | python | def find_descriptor(desc, find_all=False, custom_match=None, **args):
r"""Find an inner descriptor.
find_descriptor works in the same way as the core.find() function does,
but it acts on general descriptor objects. For example, suppose you
have a Device object called dev and want a Configuration of this
object with its bConfigurationValue equals to 1, the code would
be like so:
>>> cfg = util.find_descriptor(dev, bConfigurationValue=1)
You can use any field of the Descriptor as a match criteria, and you
can supply a customized match just like core.find() does. The
find_descriptor function also accepts the find_all parameter to get
an iterator instead of just one descriptor.
"""
def desc_iter(**kwargs):
for d in desc:
tests = (val == getattr(d, key) for key, val in kwargs.items())
if _interop._all(tests) and (custom_match is None or custom_match(d)):
yield d
if find_all:
return desc_iter(**args)
else:
try:
return _interop._next(desc_iter(**args))
except StopIteration:
return None | [
"def",
"find_descriptor",
"(",
"desc",
",",
"find_all",
"=",
"False",
",",
"custom_match",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"def",
"desc_iter",
"(",
"*",
"*",
"kwargs",
")",
":",
"for",
"d",
"in",
"desc",
":",
"tests",
"=",
"(",
"val",... | r"""Find an inner descriptor.
find_descriptor works in the same way as the core.find() function does,
but it acts on general descriptor objects. For example, suppose you
have a Device object called dev and want a Configuration of this
object with its bConfigurationValue equals to 1, the code would
be like so:
>>> cfg = util.find_descriptor(dev, bConfigurationValue=1)
You can use any field of the Descriptor as a match criteria, and you
can supply a customized match just like core.find() does. The
find_descriptor function also accepts the find_all parameter to get
an iterator instead of just one descriptor. | [
"r",
"Find",
"an",
"inner",
"descriptor",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/util.py#L151-L179 |
241,324 | pyusb/pyusb | usb/util.py | get_langids | def get_langids(dev):
r"""Retrieve the list of supported Language IDs from the device.
Most client code should not call this function directly, but instead use
the langids property on the Device object, which will call this function as
needed and cache the result.
USB LANGIDs are 16-bit integers familiar to Windows developers, where
for example instead of en-US you say 0x0409. See the file USB_LANGIDS.pdf
somewhere on the usb.org site for a list, which does not claim to be
complete. It requires "system software must allow the enumeration and
selection of LANGIDs that are not currently on this list." It also requires
"system software should never request a LANGID not defined in the LANGID
code array (string index = 0) presented by a device." Client code can
check this tuple before issuing string requests for a specific language ID.
dev is the Device object whose supported language IDs will be retrieved.
The return value is a tuple of integer LANGIDs, possibly empty if the
device does not support strings at all (which USB 3.1 r1.0 section
9.6.9 allows). In that case client code should not request strings at all.
A USBError may be raised from this function for some devices that have no
string support, instead of returning an empty tuple. The accessor for the
langids property on Device catches that case and supplies an empty tuple,
so client code can ignore this detail by using the langids property instead
of directly calling this function.
"""
from usb.control import get_descriptor
buf = get_descriptor(
dev,
254,
DESC_TYPE_STRING,
0
)
# The array is retrieved by asking for string descriptor zero, which is
# never the index of a real string. The returned descriptor has bLength
# and bDescriptorType bytes followed by pairs of bytes representing
# little-endian LANGIDs. That is, buf[0] contains the length of the
# returned array, buf[2] is the least-significant byte of the first LANGID
# (if any), buf[3] is the most-significant byte, and in general the LSBs of
# all the LANGIDs are given by buf[2:buf[0]:2] and MSBs by buf[3:buf[0]:2].
# If the length of buf came back odd, something is wrong.
if len(buf) < 4 or buf[0] < 4 or buf[0]&1 != 0:
return ()
return tuple(map(lambda x,y: x+(y<<8), buf[2:buf[0]:2], buf[3:buf[0]:2])) | python | def get_langids(dev):
r"""Retrieve the list of supported Language IDs from the device.
Most client code should not call this function directly, but instead use
the langids property on the Device object, which will call this function as
needed and cache the result.
USB LANGIDs are 16-bit integers familiar to Windows developers, where
for example instead of en-US you say 0x0409. See the file USB_LANGIDS.pdf
somewhere on the usb.org site for a list, which does not claim to be
complete. It requires "system software must allow the enumeration and
selection of LANGIDs that are not currently on this list." It also requires
"system software should never request a LANGID not defined in the LANGID
code array (string index = 0) presented by a device." Client code can
check this tuple before issuing string requests for a specific language ID.
dev is the Device object whose supported language IDs will be retrieved.
The return value is a tuple of integer LANGIDs, possibly empty if the
device does not support strings at all (which USB 3.1 r1.0 section
9.6.9 allows). In that case client code should not request strings at all.
A USBError may be raised from this function for some devices that have no
string support, instead of returning an empty tuple. The accessor for the
langids property on Device catches that case and supplies an empty tuple,
so client code can ignore this detail by using the langids property instead
of directly calling this function.
"""
from usb.control import get_descriptor
buf = get_descriptor(
dev,
254,
DESC_TYPE_STRING,
0
)
# The array is retrieved by asking for string descriptor zero, which is
# never the index of a real string. The returned descriptor has bLength
# and bDescriptorType bytes followed by pairs of bytes representing
# little-endian LANGIDs. That is, buf[0] contains the length of the
# returned array, buf[2] is the least-significant byte of the first LANGID
# (if any), buf[3] is the most-significant byte, and in general the LSBs of
# all the LANGIDs are given by buf[2:buf[0]:2] and MSBs by buf[3:buf[0]:2].
# If the length of buf came back odd, something is wrong.
if len(buf) < 4 or buf[0] < 4 or buf[0]&1 != 0:
return ()
return tuple(map(lambda x,y: x+(y<<8), buf[2:buf[0]:2], buf[3:buf[0]:2])) | [
"def",
"get_langids",
"(",
"dev",
")",
":",
"from",
"usb",
".",
"control",
"import",
"get_descriptor",
"buf",
"=",
"get_descriptor",
"(",
"dev",
",",
"254",
",",
"DESC_TYPE_STRING",
",",
"0",
")",
"# The array is retrieved by asking for string descriptor zero, which i... | r"""Retrieve the list of supported Language IDs from the device.
Most client code should not call this function directly, but instead use
the langids property on the Device object, which will call this function as
needed and cache the result.
USB LANGIDs are 16-bit integers familiar to Windows developers, where
for example instead of en-US you say 0x0409. See the file USB_LANGIDS.pdf
somewhere on the usb.org site for a list, which does not claim to be
complete. It requires "system software must allow the enumeration and
selection of LANGIDs that are not currently on this list." It also requires
"system software should never request a LANGID not defined in the LANGID
code array (string index = 0) presented by a device." Client code can
check this tuple before issuing string requests for a specific language ID.
dev is the Device object whose supported language IDs will be retrieved.
The return value is a tuple of integer LANGIDs, possibly empty if the
device does not support strings at all (which USB 3.1 r1.0 section
9.6.9 allows). In that case client code should not request strings at all.
A USBError may be raised from this function for some devices that have no
string support, instead of returning an empty tuple. The accessor for the
langids property on Device catches that case and supplies an empty tuple,
so client code can ignore this detail by using the langids property instead
of directly calling this function. | [
"r",
"Retrieve",
"the",
"list",
"of",
"supported",
"Language",
"IDs",
"from",
"the",
"device",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/util.py#L222-L270 |
241,325 | pyusb/pyusb | usb/util.py | get_string | def get_string(dev, index, langid = None):
r"""Retrieve a string descriptor from the device.
dev is the Device object which the string will be read from.
index is the string descriptor index and langid is the Language
ID of the descriptor. If langid is omitted, the string descriptor
of the first Language ID will be returned.
Zero is never the index of a real string. The USB spec allows a device to
use zero in a string index field to indicate that no string is provided.
So the caller does not have to treat that case specially, this function
returns None if passed an index of zero, and generates no traffic
to the device.
The return value is the unicode string present in the descriptor, or None
if the requested index was zero.
It is a ValueError to request a real string (index not zero), if: the
device's langid tuple is empty, or with an explicit langid the device does
not support.
"""
if 0 == index:
return None
from usb.control import get_descriptor
langids = dev.langids
if 0 == len(langids):
raise ValueError("The device has no langid")
if langid is None:
langid = langids[0]
elif langid not in langids:
raise ValueError("The device does not support the specified langid")
buf = get_descriptor(
dev,
255, # Maximum descriptor size
DESC_TYPE_STRING,
index,
langid
)
if hexversion >= 0x03020000:
return buf[2:buf[0]].tobytes().decode('utf-16-le')
else:
return buf[2:buf[0]].tostring().decode('utf-16-le') | python | def get_string(dev, index, langid = None):
r"""Retrieve a string descriptor from the device.
dev is the Device object which the string will be read from.
index is the string descriptor index and langid is the Language
ID of the descriptor. If langid is omitted, the string descriptor
of the first Language ID will be returned.
Zero is never the index of a real string. The USB spec allows a device to
use zero in a string index field to indicate that no string is provided.
So the caller does not have to treat that case specially, this function
returns None if passed an index of zero, and generates no traffic
to the device.
The return value is the unicode string present in the descriptor, or None
if the requested index was zero.
It is a ValueError to request a real string (index not zero), if: the
device's langid tuple is empty, or with an explicit langid the device does
not support.
"""
if 0 == index:
return None
from usb.control import get_descriptor
langids = dev.langids
if 0 == len(langids):
raise ValueError("The device has no langid")
if langid is None:
langid = langids[0]
elif langid not in langids:
raise ValueError("The device does not support the specified langid")
buf = get_descriptor(
dev,
255, # Maximum descriptor size
DESC_TYPE_STRING,
index,
langid
)
if hexversion >= 0x03020000:
return buf[2:buf[0]].tobytes().decode('utf-16-le')
else:
return buf[2:buf[0]].tostring().decode('utf-16-le') | [
"def",
"get_string",
"(",
"dev",
",",
"index",
",",
"langid",
"=",
"None",
")",
":",
"if",
"0",
"==",
"index",
":",
"return",
"None",
"from",
"usb",
".",
"control",
"import",
"get_descriptor",
"langids",
"=",
"dev",
".",
"langids",
"if",
"0",
"==",
"... | r"""Retrieve a string descriptor from the device.
dev is the Device object which the string will be read from.
index is the string descriptor index and langid is the Language
ID of the descriptor. If langid is omitted, the string descriptor
of the first Language ID will be returned.
Zero is never the index of a real string. The USB spec allows a device to
use zero in a string index field to indicate that no string is provided.
So the caller does not have to treat that case specially, this function
returns None if passed an index of zero, and generates no traffic
to the device.
The return value is the unicode string present in the descriptor, or None
if the requested index was zero.
It is a ValueError to request a real string (index not zero), if: the
device's langid tuple is empty, or with an explicit langid the device does
not support. | [
"r",
"Retrieve",
"a",
"string",
"descriptor",
"from",
"the",
"device",
"."
] | ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9 | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/util.py#L272-L317 |
241,326 | 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):
pcell = PhonopyAtoms(numbers=[1],
scaled_positions=[[0, 0, 0]],
cell=np.diag([1, 1, 1]))
smat = self._supercell_matrix
self._trans_s = get_supercell(pcell, smat).get_scaled_positions()
self._trans_p = np.dot(self._trans_s, self._supercell_matrix.T)
self._N = len(self._trans_s) | [
"def",
"_set_translations",
"(",
"self",
")",
":",
"pcell",
"=",
"PhonopyAtoms",
"(",
"numbers",
"=",
"[",
"1",
"]",
",",
"scaled_positions",
"=",
"[",
"[",
"0",
",",
"0",
",",
"0",
"]",
"]",
",",
"cell",
"=",
"np",
".",
"diag",
"(",
"[",
"1",
... | Set primitive translations in supercell
_trans_s
Translations with respect to supercell basis vectors
_trans_p
Translations with respect to primitive cell basis vectors
_N
Number of the translations = det(supercel_matrix) | [
"Set",
"primitive",
"translations",
"in",
"supercell"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/unfolding/core.py#L164-L182 |
241,327 | 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):
if verbose:
print(("#%11s" + "%14s" * 4) % ("T", "E_0", "B_0", "B'_0", "V_0"))
# Plus one temperature point is necessary for computing e.g. beta.
num_elems = self._get_num_elems(self._all_temperatures) + 1
if num_elems > len(self._all_temperatures):
num_elems -= 1
temperatures = []
parameters = []
free_energies = []
for i in range(num_elems): # loop over temperaturs
if self._electronic_energies.ndim == 1:
el_energy = self._electronic_energies
else:
el_energy = self._electronic_energies[i]
fe = [ph_e + el_e
for ph_e, el_e in zip(self._fe_phonon[i], el_energy)]
try:
ep = fit_to_eos(self._volumes, fe, self._eos)
except TypeError:
print("Fitting failure at T=%.1f" % self._all_temperatures[i])
if ep is None:
# Simply omit volume point where the fitting failed.
continue
else:
[ee, eb, ebp, ev] = ep
t = self._all_temperatures[i]
temperatures.append(t)
parameters.append(ep)
free_energies.append(fe)
if verbose:
print(("%14.6f" * 5) %
(t, ep[0], ep[1] * EVAngstromToGPa, ep[2], ep[3]))
self._free_energies = np.array(free_energies)
self._temperatures = np.array(temperatures)
self._equiv_parameters = np.array(parameters)
self._equiv_volumes = np.array(self._equiv_parameters[:, 3])
self._equiv_energies = np.array(self._equiv_parameters[:, 0])
self._equiv_bulk_modulus = np.array(
self._equiv_parameters[:, 1] * EVAngstromToGPa)
self._num_elems = len(self._temperatures)
# For computing following values at temperatures, finite difference
# method is used. Therefore number of temperature points are needed
# larger than self._num_elems that nearly equals to the temparature
# point we expect.
self._set_thermal_expansion()
self._set_heat_capacity_P_numerical()
self._set_heat_capacity_P_polyfit()
self._set_gruneisen_parameter() # To be run after thermal expansion.
self._len = len(self._thermal_expansions)
assert(self._len + 1 == self._num_elems) | [
"def",
"run",
"(",
"self",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"(",
"\"#%11s\"",
"+",
"\"%14s\"",
"*",
"4",
")",
"%",
"(",
"\"T\"",
",",
"\"E_0\"",
",",
"\"B_0\"",
",",
"\"B'_0\"",
",",
"\"V_0\"",
")",
")",
... | Fit parameters to EOS at temperatures
Even if fitting failed, simply omit the volume point. In this case,
the failed temperature point doesn't exist in the returned arrays. | [
"Fit",
"parameters",
"to",
"EOS",
"at",
"temperatures"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/qha/core.py#L144-L211 |
241,328 | 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):
positions = cell.get_scaled_positions()
numbers = cell.get_atomic_numbers()
masses = cell.get_masses()
magmoms = cell.get_magnetic_moments()
lattice = cell.get_cell()
trimmed_lattice = np.dot(relative_axes.T, lattice)
trimmed_positions = []
trimmed_numbers = []
if masses is None:
trimmed_masses = None
else:
trimmed_masses = []
if magmoms is None:
trimmed_magmoms = None
else:
trimmed_magmoms = []
extracted_atoms = []
positions_in_new_lattice = np.dot(positions,
np.linalg.inv(relative_axes).T)
positions_in_new_lattice -= np.floor(positions_in_new_lattice)
trimmed_positions = np.zeros_like(positions_in_new_lattice)
num_atom = 0
mapping_table = np.arange(len(positions), dtype='intc')
for i, pos in enumerate(positions_in_new_lattice):
is_overlap = False
if num_atom > 0:
diff = trimmed_positions[:num_atom] - pos
diff -= np.rint(diff)
# Older numpy doesn't support axis argument.
# distances = np.linalg.norm(np.dot(diff, trimmed_lattice), axis=1)
# overlap_indices = np.where(distances < symprec)[0]
distances = np.sqrt(
np.sum(np.dot(diff, trimmed_lattice) ** 2, axis=1))
overlap_indices = np.where(distances < symprec)[0]
if len(overlap_indices) > 0:
assert len(overlap_indices) == 1
is_overlap = True
mapping_table[i] = extracted_atoms[overlap_indices[0]]
if not is_overlap:
trimmed_positions[num_atom] = pos
num_atom += 1
trimmed_numbers.append(numbers[i])
if masses is not None:
trimmed_masses.append(masses[i])
if magmoms is not None:
trimmed_magmoms.append(magmoms[i])
extracted_atoms.append(i)
# scale is not always to become integer.
scale = 1.0 / np.linalg.det(relative_axes)
if len(numbers) == np.rint(scale * len(trimmed_numbers)):
trimmed_cell = PhonopyAtoms(
numbers=trimmed_numbers,
masses=trimmed_masses,
magmoms=trimmed_magmoms,
scaled_positions=trimmed_positions[:num_atom],
cell=trimmed_lattice,
pbc=True)
return trimmed_cell, extracted_atoms, mapping_table
else:
return False | [
"def",
"_trim_cell",
"(",
"relative_axes",
",",
"cell",
",",
"symprec",
")",
":",
"positions",
"=",
"cell",
".",
"get_scaled_positions",
"(",
")",
"numbers",
"=",
"cell",
".",
"get_atomic_numbers",
"(",
")",
"masses",
"=",
"cell",
".",
"get_masses",
"(",
"... | Trim overlapping atoms
Parameters
----------
relative_axes: ndarray
Transformation matrix to transform supercell to a smaller cell such as:
trimmed_lattice = np.dot(relative_axes.T, cell.get_cell())
shape=(3,3)
cell: PhonopyAtoms
A supercell
symprec: float
Tolerance to find overlapping atoms in the trimmed cell
Returns
-------
tuple
trimmed_cell, extracted_atoms, mapping_table | [
"Trim",
"overlapping",
"atoms"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L459-L543 |
241,329 | 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):
if method == 'niggli':
return spg.niggli_reduce(lattice, eps=tolerance)
else:
return spg.delaunay_reduce(lattice, eps=tolerance) | [
"def",
"get_reduced_bases",
"(",
"lattice",
",",
"method",
"=",
"'delaunay'",
",",
"tolerance",
"=",
"1e-5",
")",
":",
"if",
"method",
"==",
"'niggli'",
":",
"return",
"spg",
".",
"niggli_reduce",
"(",
"lattice",
",",
"eps",
"=",
"tolerance",
")",
"else",
... | Search kinds of shortest basis vectors
Parameters
----------
lattice : ndarray or list of list
Basis vectors by row vectors, [a, b, c]^T
shape=(3, 3)
method : str
delaunay: Delaunay reduction
niggli: Niggli reduction
tolerance : float
Tolerance to find shortest basis vecotrs
Returns
--------
Reduced basis as row vectors, [a_red, b_red, c_red]^T
dtype='double'
shape=(3, 3)
order='C' | [
"Search",
"kinds",
"of",
"shortest",
"basis",
"vectors"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L549-L577 |
241,330 | 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):
reduced_bases = get_reduced_bases(supercell_bases,
method='delaunay',
tolerance=symprec)
trans_mat_float = np.dot(supercell_bases, np.linalg.inv(reduced_bases))
trans_mat = np.rint(trans_mat_float).astype(int)
assert (np.abs(trans_mat_float - trans_mat) < 1e-8).all()
trans_mat_inv_float = np.linalg.inv(trans_mat)
trans_mat_inv = np.rint(trans_mat_inv_float).astype(int)
assert (np.abs(trans_mat_inv_float - trans_mat_inv) < 1e-8).all()
# Reduce all positions into the cell formed by the reduced bases.
supercell_fracs = np.dot(supercell_pos, trans_mat)
supercell_fracs -= np.rint(supercell_fracs)
supercell_fracs = np.array(supercell_fracs, dtype='double', order='C')
primitive_fracs = np.dot(primitive_pos, trans_mat)
primitive_fracs -= np.rint(primitive_fracs)
primitive_fracs = np.array(primitive_fracs, dtype='double', order='C')
# For each vector, we will need to consider all nearby images in the
# reduced bases.
lattice_points = np.array([[i, j, k]
for i in (-1, 0, 1)
for j in (-1, 0, 1)
for k in (-1, 0, 1)],
dtype='intc', order='C')
# Here's where things get interesting.
# We want to avoid manually iterating over all possible pairings of
# supercell atoms and primitive atoms, because doing so creates a
# tight loop in larger structures that is difficult to optimize.
#
# Furthermore, it seems wise to call numpy.dot on as large of an array
# as possible, since numpy can shell out to BLAS to handle the
# real heavy lifting.
shortest_vectors = np.zeros(
(len(supercell_fracs), len(primitive_fracs), 27, 3),
dtype='double', order='C')
multiplicity = np.zeros((len(supercell_fracs), len(primitive_fracs)),
dtype='intc', order='C')
import phonopy._phonopy as phonoc
phonoc.gsv_set_smallest_vectors(
shortest_vectors,
multiplicity,
supercell_fracs,
primitive_fracs,
lattice_points,
np.array(reduced_bases.T, dtype='double', order='C'),
np.array(trans_mat_inv.T, dtype='intc', order='C'),
symprec)
# # For every atom in the supercell and every atom in the primitive cell,
# # we want 27 images of the vector between them.
# #
# # 'None' is used to insert trivial axes to make these arrays broadcast.
# #
# # shape: (size_super, size_prim, 27, 3)
# candidate_fracs = (
# supercell_fracs[:, None, None, :] # shape: (size_super, 1, 1, 3)
# - primitive_fracs[None, :, None, :] # shape: (1, size_prim, 1, 3)
# + lattice_points[None, None, :, :] # shape: (1, 1, 27, 3)
# )
# # To compute the lengths, we want cartesian positions.
# #
# # Conveniently, calling 'numpy.dot' between a 4D array and a 2D array
# # does vector-matrix multiplication on each row vector in the last axis
# # of the 4D array.
# #
# # shape: (size_super, size_prim, 27)
# lengths = np.array(np.sqrt(
# np.sum(np.dot(candidate_fracs, reduced_bases)**2, axis=-1)),
# dtype='double', order='C')
# # Create the output, initially consisting of all candidate vectors scaled
# # by the primitive cell.
# #
# # shape: (size_super, size_prim, 27, 3)
# candidate_vectors = np.array(np.dot(candidate_fracs, trans_mat_inv),
# dtype='double', order='C')
# # The last final bits are done in C.
# #
# # We will gather the shortest ones from each list of 27 vectors.
# shortest_vectors = np.zeros_like(candidate_vectors,
# dtype='double', order='C')
# multiplicity = np.zeros(shortest_vectors.shape[:2], dtype='intc',
# order='C')
# import phonopy._phonopy as phonoc
# phonoc.gsv_copy_smallest_vectors(shortest_vectors,
# multiplicity,
# candidate_vectors,
# lengths,
# symprec)
return shortest_vectors, multiplicity | [
"def",
"get_smallest_vectors",
"(",
"supercell_bases",
",",
"supercell_pos",
",",
"primitive_pos",
",",
"symprec",
"=",
"1e-5",
")",
":",
"reduced_bases",
"=",
"get_reduced_bases",
"(",
"supercell_bases",
",",
"method",
"=",
"'delaunay'",
",",
"tolerance",
"=",
"s... | Find shortest atomic pair vectors
Note
----
Shortest vectors from an atom in primitive cell to an atom in
supercell in the fractional coordinates of primitive cell. If an
atom in supercell is on the border centered at an atom in
primitive and there are multiple vectors that have the same
distance (up to tolerance) and different directions, several
shortest vectors are stored.
In fact, this method is not limited to search shortest vectors between
sueprcell atoms and primitive cell atoms, but can be used to measure
shortest vectors between atoms in periodic supercell lattice frame.
Parameters
----------
supercell_bases : ndarray
Supercell basis vectors as row vectors, (a, b, c)^T. Must be order='C'.
dtype='double'
shape=(3, 3)
supercell_pos : array_like
Atomic positions in fractional coordinates of supercell.
dtype='double'
shape=(size_super, 3)
primitive_pos : array_like
Atomic positions in fractional coordinates of supercell. Note that not
in fractional coodinates of primitive cell.
dtype='double'
shape=(size_prim, 3)
symprec : float, optional, default=1e-5
Tolerance to find equal distances of vectors
Returns
-------
shortest_vectors : ndarray
Shortest vectors in supercell coordinates. The 27 in shape is the
possible maximum number of elements.
dtype='double'
shape=(size_super, size_prim, 27, 3)
multiplicities : ndarray
Number of equidistance shortest vectors
dtype='intc'
shape=(size_super, size_prim) | [
"Find",
"shortest",
"atomic",
"pair",
"vectors"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L595-L741 |
241,331 | 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):
out = [] # Finally the shape is fixed as (num_sym, num_pos_of_supercell).
for (sym, t) in zip(rotations, translations):
rotated_positions = np.dot(positions, sym.T) + t
out.append(compute_permutation_for_rotation(positions,
rotated_positions,
lattice,
symprec))
return np.array(out, dtype='intc', order='C') | [
"def",
"compute_all_sg_permutations",
"(",
"positions",
",",
"# scaled positions",
"rotations",
",",
"# scaled",
"translations",
",",
"# scaled",
"lattice",
",",
"# column vectors",
"symprec",
")",
":",
"out",
"=",
"[",
"]",
"# Finally the shape is fixed as (num_sym, num_... | Compute a permutation for every space group operation.
See 'compute_permutation_for_rotation' for more info.
Output has shape (num_rot, num_pos) | [
"Compute",
"a",
"permutation",
"for",
"every",
"space",
"group",
"operation",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L744-L764 |
241,332 | 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):
# Sort both sides by some measure which is likely to produce a small
# maximum value of (sorted_rotated_index - sorted_original_index).
# The C code is optimized for this case, reducing an O(n^2)
# search down to ~O(n). (for O(n log n) work overall, including the sort)
#
# We choose distance from the nearest bravais lattice point as our measure.
def sort_by_lattice_distance(fracs):
carts = np.dot(fracs - np.rint(fracs), lattice.T)
perm = np.argsort(np.sum(carts**2, axis=1))
sorted_fracs = np.array(fracs[perm], dtype='double', order='C')
return perm, sorted_fracs
(perm_a, sorted_a) = sort_by_lattice_distance(positions_a)
(perm_b, sorted_b) = sort_by_lattice_distance(positions_b)
# Call the C code on our conditioned inputs.
perm_between = _compute_permutation_c(sorted_a,
sorted_b,
lattice,
symprec)
# Compose all of the permutations for the full permutation.
#
# Note the following properties of permutation arrays:
#
# 1. Inverse: if x[perm] == y then x == y[argsort(perm)]
# 2. Associativity: x[p][q] == x[p[q]]
return perm_a[perm_between][np.argsort(perm_b)] | [
"def",
"compute_permutation_for_rotation",
"(",
"positions_a",
",",
"# scaled positions",
"positions_b",
",",
"lattice",
",",
"# column vectors",
"symprec",
")",
":",
"# Sort both sides by some measure which is likely to produce a small",
"# maximum value of (sorted_rotated_index - sor... | Get the overall permutation such that
positions_a[perm[i]] == positions_b[i] (modulo the lattice)
or in numpy speak,
positions_a[perm] == positions_b (modulo the lattice)
This version is optimized for the case where positions_a and positions_b
are related by a rotation. | [
"Get",
"the",
"overall",
"permutation",
"such",
"that"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L767-L811 |
241,333 | 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):
permutation = np.zeros(shape=(len(positions_a),), dtype='intc')
def permutation_error():
raise ValueError("Input forces are not enough to calculate force constants, "
"or something wrong (e.g. crystal structure does not match).")
try:
import phonopy._phonopy as phonoc
is_found = phonoc.compute_permutation(permutation,
lattice,
positions_a,
positions_b,
symprec)
if not is_found:
permutation_error()
except ImportError:
for i, pos_b in enumerate(positions_b):
diffs = positions_a - pos_b
diffs -= np.rint(diffs)
diffs = np.dot(diffs, lattice.T)
possible_j = np.nonzero(
np.sqrt(np.sum(diffs**2, axis=1)) < symprec)[0]
if len(possible_j) != 1:
permutation_error()
permutation[i] = possible_j[0]
if -1 in permutation:
permutation_error()
return permutation | [
"def",
"_compute_permutation_c",
"(",
"positions_a",
",",
"# scaled positions",
"positions_b",
",",
"lattice",
",",
"# column vectors",
"symprec",
")",
":",
"permutation",
"=",
"np",
".",
"zeros",
"(",
"shape",
"=",
"(",
"len",
"(",
"positions_a",
")",
",",
")... | Version of '_compute_permutation_for_rotation' which just directly
calls the C function, without any conditioning of the data.
Skipping the conditioning step makes this EXTREMELY slow on large
structures. | [
"Version",
"of",
"_compute_permutation_for_rotation",
"which",
"just",
"directly",
"calls",
"the",
"C",
"function",
"without",
"any",
"conditioning",
"of",
"the",
"data",
".",
"Skipping",
"the",
"conditioning",
"step",
"makes",
"this",
"EXTREMELY",
"slow",
"on",
"... | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L814-L858 |
241,334 | 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):
spg_num = spglib_dataset['number']
num_atoms = len(spglib_dataset['std_types'])
lengths = _get_lattice_parameters(spglib_dataset['std_lattice'])
if spg_num <= 74: # Triclinic, monoclinic, and orthorhombic
multi = _get_multiplicity_abc(num_atoms, lengths, max_num_atoms)
elif spg_num <= 194: # Tetragonal and hexagonal
multi = _get_multiplicity_ac(num_atoms, lengths, max_num_atoms)
else: # Cubic
multi = _get_multiplicity_a(num_atoms, lengths, max_num_atoms)
return multi | [
"def",
"estimate_supercell_matrix",
"(",
"spglib_dataset",
",",
"max_num_atoms",
"=",
"120",
")",
":",
"spg_num",
"=",
"spglib_dataset",
"[",
"'number'",
"]",
"num_atoms",
"=",
"len",
"(",
"spglib_dataset",
"[",
"'std_types'",
"]",
")",
"lengths",
"=",
"_get_lat... | Estimate supercell matrix from conventional cell
Diagonal supercell matrix is estimated from basis vector lengths
and maximum number of atoms to be accepted. Supercell is assumed
to be made from the standardized cell and to be closest to sphere
under keeping lattice symmetry. For triclinic, monoclinic, and
orthorhombic cells, multiplicities for a, b, c are not constrained
by symmetry. For tetragonal and hexagonal cells, multiplicities
for a and b are chosen to be the same, and for cubic cell, those
of a, b, c are the same.
Parameters
----------
spglib_dataset : tuple
Spglib symmetry dataset
max_num_atoms : int, optional
Maximum number of atoms in created supercell to be tolerated.
Returns
-------
list of three integer numbers
Multiplicities for a, b, c basis vectors, respectively. | [
"Estimate",
"supercell",
"matrix",
"from",
"conventional",
"cell"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L1208-L1246 |
241,335 | 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 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 |
241,336 | 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):
self._second_one_loop()
A = self._A
if A[2, 1] == 0:
return True
elif A[2, 1] % A[1, 1] == 0:
self._second_finalize()
self._Ps += self._L
self._L = []
return True
else:
return False | [
"def",
"_second",
"(",
"self",
")",
":",
"self",
".",
"_second_one_loop",
"(",
")",
"A",
"=",
"self",
".",
"_A",
"if",
"A",
"[",
"2",
",",
"1",
"]",
"==",
"0",
":",
"return",
"True",
"elif",
"A",
"[",
"2",
",",
"1",
"]",
"%",
"A",
"[",
"1",... | Find Smith normal form for Right-low 2x2 matrix | [
"Find",
"Smith",
"normal",
"form",
"for",
"Right",
"-",
"low",
"2x2",
"matrix"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L1030-L1043 |
241,337 | 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):
if self._A[1, 1] == 0 and self._A[2, 1] != 0:
self._swap_rows(1, 2)
if self._A[2, 1] != 0:
self._zero_second_column() | [
"def",
"_second_column",
"(",
"self",
")",
":",
"if",
"self",
".",
"_A",
"[",
"1",
",",
"1",
"]",
"==",
"0",
"and",
"self",
".",
"_A",
"[",
"2",
",",
"1",
"]",
"!=",
"0",
":",
"self",
".",
"_swap_rows",
"(",
"1",
",",
"2",
")",
"if",
"self"... | Right-low 2x2 matrix
Assume elements in first row and column are all zero except for A[0,0]. | [
"Right",
"-",
"low",
"2x2",
"matrix"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L1055-L1066 |
241,338 | 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):
L = np.eye(3, dtype='intc')
L[i, i] = 0
L[j, j] = 0
L[i, j] = 1
L[j, i] = 1
self._L.append(L.copy())
self._A = np.dot(L, self._A) | [
"def",
"_swap_rows",
"(",
"self",
",",
"i",
",",
"j",
")",
":",
"L",
"=",
"np",
".",
"eye",
"(",
"3",
",",
"dtype",
"=",
"'intc'",
")",
"L",
"[",
"i",
",",
"i",
"]",
"=",
"0",
"L",
"[",
"j",
",",
"j",
"]",
"=",
"0",
"L",
"[",
"i",
","... | Swap i and j rows
As the side effect, determinant flips. | [
"Swap",
"i",
"and",
"j",
"rows"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L1088-L1101 |
241,339 | 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):
L = np.eye(3, dtype='intc')
L[i, i] = -1
self._L.append(L.copy())
self._A = np.dot(L, self._A) | [
"def",
"_flip_sign_row",
"(",
"self",
",",
"i",
")",
":",
"L",
"=",
"np",
".",
"eye",
"(",
"3",
",",
"dtype",
"=",
"'intc'",
")",
"L",
"[",
"i",
",",
"i",
"]",
"=",
"-",
"1",
"self",
".",
"_L",
".",
"append",
"(",
"L",
".",
"copy",
"(",
"... | Multiply -1 for all elements in row | [
"Multiply",
"-",
"1",
"for",
"all",
"elements",
"in",
"row"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/cells.py#L1103-L1109 |
241,340 | 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):
if 'displacements' in dataset:
natom = self._supercell.get_number_of_atoms()
if type(dataset['displacements']) is np.ndarray:
if dataset['displacements'].ndim in (1, 2):
d = dataset['displacements'].reshape((-1, natom, 3))
dataset['displacements'] = d
if type(dataset['forces']) is np.ndarray:
if dataset['forces'].ndim in (1, 2):
f = dataset['forces'].reshape((-1, natom, 3))
dataset['forces'] = f
self._displacement_dataset = dataset
self._supercells_with_displacements = None | [
"def",
"dataset",
"(",
"self",
",",
"dataset",
")",
":",
"if",
"'displacements'",
"in",
"dataset",
":",
"natom",
"=",
"self",
".",
"_supercell",
".",
"get_number_of_atoms",
"(",
")",
"if",
"type",
"(",
"dataset",
"[",
"'displacements'",
"]",
")",
"is",
"... | Set dataset having displacements and optionally forces
Note
----
Elements of the list accessed by 'first_atoms' corresponds to each
displaced supercell. Each displaced supercell contains only one
displacement. dict['first_atoms']['forces'] gives atomic forces in
each displaced supercell.
Parameters
----------
displacement_dataset : dict
There are two dict structures.
Type 1. One atomic displacement in each supercell:
{'natom': number of atoms in supercell,
'first_atoms': [
{'number': atom index of displaced atom,
'displacement': displacement in Cartesian coordinates,
'forces': forces on atoms in supercell},
{...}, ...]}
Type 2. All atomic displacements in each supercell:
{'natom': number of atoms in supercell,
'displacements': ndarray, dtype='double', order='C',
shape=(supercells, natom, 3)
'forces': ndarray, dtype='double',, order='C',
shape=(supercells, natom, 3)}
In type 2, displacements and forces can be given by numpy array
with different shape but that can be reshaped to
(supercells, natom, 3). | [
"Set",
"dataset",
"having",
"displacements",
"and",
"optionally",
"forces"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L448-L492 |
241,341 | 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):
if 'first_atoms' in self._displacement_dataset:
for disp, forces in zip(self._displacement_dataset['first_atoms'],
sets_of_forces):
disp['forces'] = forces
elif 'forces' in self._displacement_dataset:
forces = np.array(sets_of_forces, dtype='double', order='C')
self._displacement_dataset['forces'] = forces | [
"def",
"forces",
"(",
"self",
",",
"sets_of_forces",
")",
":",
"if",
"'first_atoms'",
"in",
"self",
".",
"_displacement_dataset",
":",
"for",
"disp",
",",
"forces",
"in",
"zip",
"(",
"self",
".",
"_displacement_dataset",
"[",
"'first_atoms'",
"]",
",",
"sets... | Set forces in displacement dataset.
Parameters
----------
sets_of_forces : array_like
A set of atomic forces in displaced supercells. The order of
displaced supercells has to match with that in displacement
dataset.
shape=(displaced supercells, atoms in supercell, 3), dtype='double'
[[[f_1x, f_1y, f_1z], [f_2x, f_2y, f_2z], ...], # first supercell
[[f_1x, f_1y, f_1z], [f_2x, f_2y, f_2z], ...], # second supercell
...
] | [
"Set",
"forces",
"in",
"displacement",
"dataset",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L498-L522 |
241,342 | 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):
if type(force_constants) is np.ndarray:
fc_shape = force_constants.shape
if fc_shape[0] != fc_shape[1]:
if self._primitive.get_number_of_atoms() != fc_shape[0]:
msg = ("Force constants shape disagrees with crystal "
"structure setting. This may be due to "
"PRIMITIVE_AXIS.")
raise RuntimeError(msg)
self._force_constants = force_constants
if self._primitive.get_masses() is not None:
self._set_dynamical_matrix() | [
"def",
"force_constants",
"(",
"self",
",",
"force_constants",
")",
":",
"if",
"type",
"(",
"force_constants",
")",
"is",
"np",
".",
"ndarray",
":",
"fc_shape",
"=",
"force_constants",
".",
"shape",
"if",
"fc_shape",
"[",
"0",
"]",
"!=",
"fc_shape",
"[",
... | Set force constants
Parameters
----------
force_constants : array_like
Force constants matrix. If this is given in own condiguous ndarray
with order='C' and dtype='double', internal copy of data is
avoided. Therefore some computational resources are saved.
shape=(atoms in supercell, atoms in supercell, 3, 3),
dtype='double' | [
"Set",
"force",
"constants"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L528-L553 |
241,343 | 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):
displacement_directions = get_least_displacements(
self._symmetry,
is_plusminus=is_plusminus,
is_diagonal=is_diagonal,
is_trigonal=is_trigonal,
log_level=self._log_level)
displacement_dataset = directions_to_displacement_dataset(
displacement_directions,
distance,
self._supercell)
self.set_displacement_dataset(displacement_dataset) | [
"def",
"generate_displacements",
"(",
"self",
",",
"distance",
"=",
"0.01",
",",
"is_plusminus",
"=",
"'auto'",
",",
"is_diagonal",
"=",
"True",
",",
"is_trigonal",
"=",
"False",
")",
":",
"displacement_directions",
"=",
"get_least_displacements",
"(",
"self",
"... | Generate displacement dataset | [
"Generate",
"displacement",
"dataset"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L570-L586 |
241,344 | 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):
self._set_dynamical_matrix()
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._dynamical_matrix.set_dynamical_matrix(q)
return self._dynamical_matrix.get_dynamical_matrix() | [
"def",
"get_dynamical_matrix_at_q",
"(",
"self",
",",
"q",
")",
":",
"self",
".",
"_set_dynamical_matrix",
"(",
")",
"if",
"self",
".",
"_dynamical_matrix",
"is",
"None",
":",
"msg",
"=",
"(",
"\"Dynamical matrix has not yet built.\"",
")",
"raise",
"RuntimeError"... | Calculate dynamical matrix at a given q-point
Parameters
----------
q: array_like
A q-vector.
shape=(3,), dtype='double'
Returns
-------
dynamical_matrix: ndarray
Dynamical matrix.
shape=(bands, bands), dtype='complex' | [
"Calculate",
"dynamical",
"matrix",
"at",
"a",
"given",
"q",
"-",
"point"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L652-L675 |
241,345 | 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):
self._set_dynamical_matrix()
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._dynamical_matrix.set_dynamical_matrix(q)
dm = self._dynamical_matrix.get_dynamical_matrix()
frequencies = []
for eig in np.linalg.eigvalsh(dm).real:
if eig < 0:
frequencies.append(-np.sqrt(-eig))
else:
frequencies.append(np.sqrt(eig))
return np.array(frequencies) * self._factor | [
"def",
"get_frequencies",
"(",
"self",
",",
"q",
")",
":",
"self",
".",
"_set_dynamical_matrix",
"(",
")",
"if",
"self",
".",
"_dynamical_matrix",
"is",
"None",
":",
"msg",
"=",
"(",
"\"Dynamical matrix has not yet built.\"",
")",
"raise",
"RuntimeError",
"(",
... | Calculate phonon frequencies at a given q-point
Parameters
----------
q: array_like
A q-vector.
shape=(3,), dtype='double'
Returns
-------
frequencies: ndarray
Phonon frequencies.
shape=(bands, ), dtype='double' | [
"Calculate",
"phonon",
"frequencies",
"at",
"a",
"given",
"q",
"-",
"point"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L677-L707 |
241,346 | 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):
self._set_dynamical_matrix()
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._dynamical_matrix.set_dynamical_matrix(q)
dm = self._dynamical_matrix.get_dynamical_matrix()
frequencies = []
eigvals, eigenvectors = np.linalg.eigh(dm)
frequencies = []
for eig in eigvals:
if eig < 0:
frequencies.append(-np.sqrt(-eig))
else:
frequencies.append(np.sqrt(eig))
return np.array(frequencies) * self._factor, eigenvectors | [
"def",
"get_frequencies_with_eigenvectors",
"(",
"self",
",",
"q",
")",
":",
"self",
".",
"_set_dynamical_matrix",
"(",
")",
"if",
"self",
".",
"_dynamical_matrix",
"is",
"None",
":",
"msg",
"=",
"(",
"\"Dynamical matrix has not yet built.\"",
")",
"raise",
"Runti... | Calculate phonon frequencies and eigenvectors at a given q-point
Parameters
----------
q: array_like
A q-vector.
shape=(3,)
Returns
-------
(frequencies, eigenvectors)
frequencies: ndarray
Phonon frequencies
shape=(bands, ), dtype='double', order='C'
eigenvectors: ndarray
Phonon eigenvectors
shape=(bands, bands), dtype='complex', order='C' | [
"Calculate",
"phonon",
"frequencies",
"and",
"eigenvectors",
"at",
"a",
"given",
"q",
"-",
"point"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L709-L746 |
241,347 | 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):
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
if with_group_velocities:
if self._group_velocity is None:
self._set_group_velocity()
group_velocity = self._group_velocity
else:
group_velocity = None
self._band_structure = BandStructure(
paths,
self._dynamical_matrix,
with_eigenvectors=with_eigenvectors,
is_band_connection=is_band_connection,
group_velocity=group_velocity,
path_connections=path_connections,
labels=labels,
is_legacy_plot=is_legacy_plot,
factor=self._factor) | [
"def",
"run_band_structure",
"(",
"self",
",",
"paths",
",",
"with_eigenvectors",
"=",
"False",
",",
"with_group_velocities",
"=",
"False",
",",
"is_band_connection",
"=",
"False",
",",
"path_connections",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"is_legacy... | Run phonon band structure calculation.
Parameters
----------
paths : List of array_like
Sets of qpoints that can be passed to phonopy.set_band_structure().
Numbers of qpoints can be different.
shape of each array_like : (qpoints, 3)
with_eigenvectors : bool, optional
Flag whether eigenvectors are calculated or not. Default is False.
with_group_velocities : bool, optional
Flag whether group velocities are calculated or not. Default is
False.
is_band_connection : bool, optional
Flag whether each band is connected or not. This is achieved by
comparing similarity of eigenvectors of neghboring poins. Sometimes
this fails. Default is False.
path_connections : List of bool, optional
This is only used in graphical plot of band structure and gives
whether each path is connected to the next path or not,
i.e., if False, there is a jump of q-points. Number of elements is
the same at that of paths. Default is None.
labels : List of str, optional
This is only used in graphical plot of band structure and gives
labels of end points of each path. The number of labels is equal
to (2 - np.array(path_connections)).sum().
is_legacy_plot: bool, optional
This makes the old style band structure plot. Default is False. | [
"Run",
"phonon",
"band",
"structure",
"calculation",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L749-L808 |
241,348 | 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):
if self._dynamical_matrix is None:
msg = "Dynamical matrix has not yet built."
raise RuntimeError(msg)
_mesh = np.array(mesh)
mesh_nums = None
if _mesh.shape:
if _mesh.shape == (3,):
mesh_nums = mesh
_is_gamma_center = is_gamma_center
else:
if self._primitive_symmetry is not None:
rots = self._primitive_symmetry.get_pointgroup_operations()
mesh_nums = length2mesh(mesh,
self._primitive.get_cell(),
rotations=rots)
else:
mesh_nums = length2mesh(mesh, self._primitive.get_cell())
_is_gamma_center = True
if mesh_nums is None:
msg = "mesh has inappropriate type."
raise TypeError(msg)
if with_group_velocities:
if self._group_velocity is None:
self._set_group_velocity()
group_velocity = self._group_velocity
else:
group_velocity = None
if use_iter_mesh:
self._mesh = IterMesh(
self._dynamical_matrix,
mesh,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=with_eigenvectors,
is_gamma_center=is_gamma_center,
rotations=self._primitive_symmetry.get_pointgroup_operations(),
factor=self._factor)
else:
self._mesh = Mesh(
self._dynamical_matrix,
mesh_nums,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=with_eigenvectors,
is_gamma_center=_is_gamma_center,
group_velocity=group_velocity,
rotations=self._primitive_symmetry.get_pointgroup_operations(),
factor=self._factor,
use_lapack_solver=self._use_lapack_solver) | [
"def",
"init_mesh",
"(",
"self",
",",
"mesh",
"=",
"100.0",
",",
"shift",
"=",
"None",
",",
"is_time_reversal",
"=",
"True",
",",
"is_mesh_symmetry",
"=",
"True",
",",
"with_eigenvectors",
"=",
"False",
",",
"with_group_velocities",
"=",
"False",
",",
"is_ga... | Initialize mesh sampling phonon calculation without starting to run.
Phonon calculation starts explicitly with calling Mesh.run() or
implicitly with accessing getters of Mesh instance, e.g.,
Mesh.frequencies.
Parameters
----------
mesh: array_like or float, optional
Mesh numbers along a, b, c axes when array_like object is given.
dtype='intc', shape=(3,)
When float value is given, uniform mesh is generated following
VASP convention by
N = max(1, nint(l * |a|^*))
where 'nint' is the function to return the nearest integer. In this
case, it is forced to set is_gamma_center=True.
Default value is 100.0.
shift: array_like, optional
Mesh shifts along a*, b*, c* axes with respect to neighboring grid
points from the original mesh (Monkhorst-Pack or Gamma center).
0.5 gives half grid shift. Normally 0 or 0.5 is given.
Otherwise q-points symmetry search is not performed.
Default is None (no additional shift).
dtype='double', shape=(3, )
is_time_reversal: bool, optional
Time reversal symmetry is considered in symmetry search. By this,
inversion symmetry is always included. Default is True.
is_mesh_symmetry: bool, optional
Wheather symmetry search is done or not. Default is True
with_eigenvectors: bool, optional
Eigenvectors are stored by setting True. Default False.
with_group_velocities : bool, optional
Group velocities are calculated by setting True. Default is
False.
is_gamma_center: bool, default False
Uniform mesh grids are generated centring at Gamma point but not
the Monkhorst-Pack scheme. When type(mesh) is float, this parameter
setting is ignored and it is forced to set is_gamma_center=True.
use_iter_mesh: bool
Use IterMesh instead of Mesh class not to store phonon properties
in its instance to save memory consumption. This is used with
ThermalDisplacements and ThermalDisplacementMatrices.
Default is False. | [
"Initialize",
"mesh",
"sampling",
"phonon",
"calculation",
"without",
"starting",
"to",
"run",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L974-L1082 |
241,349 | 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):
self.init_mesh(mesh=mesh,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=with_eigenvectors,
with_group_velocities=with_group_velocities,
is_gamma_center=is_gamma_center)
self._mesh.run() | [
"def",
"run_mesh",
"(",
"self",
",",
"mesh",
"=",
"100.0",
",",
"shift",
"=",
"None",
",",
"is_time_reversal",
"=",
"True",
",",
"is_mesh_symmetry",
"=",
"True",
",",
"with_eigenvectors",
"=",
"False",
",",
"with_group_velocities",
"=",
"False",
",",
"is_gam... | Run mesh sampling phonon calculation.
See the parameter details in Phonopy.init_mesh(). | [
"Run",
"mesh",
"sampling",
"phonon",
"calculation",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1084-L1105 |
241,350 | 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):
warnings.warn("Phonopy.set_mesh is deprecated. "
"Use Phonopy.run_mesh.", DeprecationWarning)
if self._group_velocity is None:
with_group_velocities = False
else:
with_group_velocities = True
if run_immediately:
self.run_mesh(mesh,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=is_eigenvectors,
with_group_velocities=with_group_velocities,
is_gamma_center=is_gamma_center)
else:
self.init_mesh(mesh,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=is_eigenvectors,
with_group_velocities=with_group_velocities,
is_gamma_center=is_gamma_center) | [
"def",
"set_mesh",
"(",
"self",
",",
"mesh",
",",
"shift",
"=",
"None",
",",
"is_time_reversal",
"=",
"True",
",",
"is_mesh_symmetry",
"=",
"True",
",",
"is_eigenvectors",
"=",
"False",
",",
"is_gamma_center",
"=",
"False",
",",
"run_immediately",
"=",
"True... | Phonon calculations on sampling mesh grids
Parameters
----------
mesh: array_like
Mesh numbers along a, b, c axes.
dtype='intc'
shape=(3,)
shift: array_like, optional, default None (no shift)
Mesh shifts along a*, b*, c* axes with respect to neighboring grid
points from the original mesh (Monkhorst-Pack or Gamma center).
0.5 gives half grid shift. Normally 0 or 0.5 is given.
Otherwise q-points symmetry search is not performed.
dtype='double'
shape=(3, )
is_time_reversal: bool, optional, default True
Time reversal symmetry is considered in symmetry search. By this,
inversion symmetry is always included.
is_mesh_symmetry: bool, optional, default True
Wheather symmetry search is done or not.
is_eigenvectors: bool, optional, default False
Eigenvectors are stored by setting True.
is_gamma_center: bool, default False
Uniform mesh grids are generated centring at Gamma point but not
the Monkhorst-Pack scheme.
run_immediately: bool, default True
With True, phonon calculations are performed immediately, which is
usual usage. | [
"Phonon",
"calculations",
"on",
"sampling",
"mesh",
"grids"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1107-L1168 |
241,351 | 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):
if self._mesh is None:
msg = ("run_mesh has to be done.")
raise RuntimeError(msg)
retdict = {'qpoints': self._mesh.qpoints,
'weights': self._mesh.weights,
'frequencies': self._mesh.frequencies,
'eigenvectors': self._mesh.eigenvectors,
'group_velocities': self._mesh.group_velocities}
return retdict | [
"def",
"get_mesh_dict",
"(",
"self",
")",
":",
"if",
"self",
".",
"_mesh",
"is",
"None",
":",
"msg",
"=",
"(",
"\"run_mesh has to be done.\"",
")",
"raise",
"RuntimeError",
"(",
"msg",
")",
"retdict",
"=",
"{",
"'qpoints'",
":",
"self",
".",
"_mesh",
"."... | Returns calculated mesh sampling phonons
Returns
-------
dict
keys: qpoints, weights, frequencies, eigenvectors, and
group_velocities
Each value for the corresponding key is explained as below.
qpoints: ndarray
q-points in reduced coordinates of reciprocal lattice
dtype='double'
shape=(ir-grid points, 3)
weights: ndarray
Geometric q-point weights. Its sum is the number of grid
points.
dtype='intc'
shape=(ir-grid points,)
frequencies: ndarray
Phonon frequencies at ir-grid points. Imaginary frequenies are
represented by negative real numbers.
dtype='double'
shape=(ir-grid points, bands)
eigenvectors: ndarray
Phonon eigenvectors at ir-grid points. See the data structure
at np.linalg.eigh.
dtype='complex'
shape=(ir-grid points, bands, bands)
group_velocities: ndarray
Phonon group velocities at ir-grid points.
dtype='double'
shape=(ir-grid points, bands, 3) | [
"Returns",
"calculated",
"mesh",
"sampling",
"phonons"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1170-L1216 |
241,352 | 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):
warnings.warn("Phonopy.set_iter_mesh is deprecated. "
"Use Phonopy.run_mesh with use_iter_mesh=True.",
DeprecationWarning)
self.run_mesh(mesh=mesh,
shift=shift,
is_time_reversal=is_time_reversal,
is_mesh_symmetry=is_mesh_symmetry,
with_eigenvectors=is_eigenvectors,
is_gamma_center=is_gamma_center,
use_iter_mesh=True) | [
"def",
"set_iter_mesh",
"(",
"self",
",",
"mesh",
",",
"shift",
"=",
"None",
",",
"is_time_reversal",
"=",
"True",
",",
"is_mesh_symmetry",
"=",
"True",
",",
"is_eigenvectors",
"=",
"False",
",",
"is_gamma_center",
"=",
"False",
")",
":",
"warnings",
".",
... | Create an IterMesh instancer
Attributes
----------
See set_mesh method. | [
"Create",
"an",
"IterMesh",
"instancer"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1252-L1277 |
241,353 | 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):
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
if with_group_velocities:
if self._group_velocity is None:
self._set_group_velocity()
group_velocity = self._group_velocity
else:
group_velocity = None
self._qpoints = QpointsPhonon(
np.reshape(q_points, (-1, 3)),
self._dynamical_matrix,
nac_q_direction=nac_q_direction,
with_eigenvectors=with_eigenvectors,
group_velocity=group_velocity,
with_dynamical_matrices=with_dynamical_matrices,
factor=self._factor) | [
"def",
"run_qpoints",
"(",
"self",
",",
"q_points",
",",
"with_eigenvectors",
"=",
"False",
",",
"with_group_velocities",
"=",
"False",
",",
"with_dynamical_matrices",
"=",
"False",
",",
"nac_q_direction",
"=",
"None",
")",
":",
"if",
"self",
".",
"_dynamical_ma... | Phonon calculations on q-points.
Parameters
----------
q_points: array_like or float, optional
q-points in reduced coordinates.
dtype='double', shape=(q-points, 3)
with_eigenvectors: bool, optional
Eigenvectors are stored by setting True. Default False.
with_group_velocities : bool, optional
Group velocities are calculated by setting True. Default is False.
with_dynamical_matrices : bool, optional
Calculated dynamical matrices are stored by setting True.
Default is False.
nac_q_direction : array_like
q=(0,0,0) is replaced by q=epsilon * nac_q_direction where epsilon
is infinitsimal for non-analytical term correction. This is used,
e.g., to observe LO-TO splitting, | [
"Phonon",
"calculations",
"on",
"q",
"-",
"points",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1349-L1394 |
241,354 | 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):
if self._mesh is None:
msg = "run_mesh has to be done before DOS calculation."
raise RuntimeError(msg)
total_dos = TotalDos(self._mesh,
sigma=sigma,
use_tetrahedron_method=use_tetrahedron_method)
total_dos.set_draw_area(freq_min, freq_max, freq_pitch)
total_dos.run()
self._total_dos = total_dos | [
"def",
"run_total_dos",
"(",
"self",
",",
"sigma",
"=",
"None",
",",
"freq_min",
"=",
"None",
",",
"freq_max",
"=",
"None",
",",
"freq_pitch",
"=",
"None",
",",
"use_tetrahedron_method",
"=",
"True",
")",
":",
"if",
"self",
".",
"_mesh",
"is",
"None",
... | Calculate total DOS from phonons on sampling mesh.
Parameters
----------
sigma : float, optional
Smearing width for smearing method. Default is None
freq_min, freq_max, freq_pitch : float, optional
Minimum and maximum frequencies in which range DOS is computed
with the specified interval (freq_pitch).
Defaults are None and they are automatically determined.
use_tetrahedron_method : float, optional
Use tetrahedron method when this is True. When sigma is set,
smearing method is used. | [
"Calculate",
"total",
"DOS",
"from",
"phonons",
"on",
"sampling",
"mesh",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1436-L1466 |
241,355 | 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):
warnings.warn("Phonopy.get_total_DOS is deprecated. "
"Use Phonopy.get_total_dos_dict.", DeprecationWarning)
dos = self.get_total_dos_dict()
return dos['frequency_points'], dos['total_dos'] | [
"def",
"get_total_DOS",
"(",
"self",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Phonopy.get_total_DOS is deprecated. \"",
"\"Use Phonopy.get_total_dos_dict.\"",
",",
"DeprecationWarning",
")",
"dos",
"=",
"self",
".",
"get_total_dos_dict",
"(",
")",
"return",
"dos",
"... | Return frequency points and total DOS as a tuple.
Returns
-------
A tuple with (frequency_points, total_dos).
frequency_points: ndarray
shape=(frequency_sampling_points, ), dtype='double'
total_dos:
shape=(frequency_sampling_points, ), dtype='double' | [
"Return",
"frequency",
"points",
"and",
"total",
"DOS",
"as",
"a",
"tuple",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1519-L1538 |
241,356 | 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):
self._pdos = None
if self._mesh is None:
msg = "run_mesh has to be done before PDOS calculation."
raise RuntimeError(msg)
if not self._mesh.with_eigenvectors:
msg = "run_mesh has to be called with with_eigenvectors=True."
raise RuntimeError(msg)
if np.prod(self._mesh.mesh_numbers) != len(self._mesh.ir_grid_points):
msg = "run_mesh has to be done with is_mesh_symmetry=False."
raise RuntimeError(msg)
if direction is not None:
direction_cart = np.dot(direction, self._primitive.get_cell())
else:
direction_cart = None
self._pdos = PartialDos(self._mesh,
sigma=sigma,
use_tetrahedron_method=use_tetrahedron_method,
direction=direction_cart,
xyz_projection=xyz_projection)
self._pdos.set_draw_area(freq_min, freq_max, freq_pitch)
self._pdos.run() | [
"def",
"run_projected_dos",
"(",
"self",
",",
"sigma",
"=",
"None",
",",
"freq_min",
"=",
"None",
",",
"freq_max",
"=",
"None",
",",
"freq_pitch",
"=",
"None",
",",
"use_tetrahedron_method",
"=",
"True",
",",
"direction",
"=",
"None",
",",
"xyz_projection",
... | Calculate projected DOS from phonons on sampling mesh.
Parameters
----------
sigma : float, optional
Smearing width for smearing method. Default is None
freq_min, freq_max, freq_pitch : float, optional
Minimum and maximum frequencies in which range DOS is computed
with the specified interval (freq_pitch).
Defaults are None and they are automatically determined.
use_tetrahedron_method : float, optional
Use tetrahedron method when this is True. When sigma is set,
smearing method is used.
direction : array_like, optional
Specific projection direction. This is specified three values
along basis vectors or the primitive cell. Default is None,
i.e., no projection.
xyz_projection : bool, optional
This determines whether projected along Cartesian directions or
not. Default is False, i.e., no projection. | [
"Calculate",
"projected",
"DOS",
"from",
"phonons",
"on",
"sampling",
"mesh",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1578-L1633 |
241,357 | 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):
warnings.warn("Phonopy.get_partial_DOS is deprecated. "
"Use Phonopy.get_projected_dos_dict.",
DeprecationWarning)
pdos = self.get_projected_dos_dict()
return pdos['frequency_points'], pdos['projected_dos'] | [
"def",
"get_partial_DOS",
"(",
"self",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Phonopy.get_partial_DOS is deprecated. \"",
"\"Use Phonopy.get_projected_dos_dict.\"",
",",
"DeprecationWarning",
")",
"pdos",
"=",
"self",
".",
"get_projected_dos_dict",
"(",
")",
"return",... | Return frequency points and partial DOS as a tuple.
Projection is done to atoms and may be also done along directions
depending on the parameters at run_partial_dos.
Returns
-------
A tuple with (frequency_points, partial_dos).
frequency_points: ndarray
shape=(frequency_sampling_points, ), dtype='double'
partial_dos:
shape=(frequency_sampling_points, projections), dtype='double' | [
"Return",
"frequency",
"points",
"and",
"partial",
"DOS",
"as",
"a",
"tuple",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1695-L1717 |
241,358 | 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):
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.xaxis.set_ticks_position('both')
ax.yaxis.set_ticks_position('both')
ax.xaxis.set_tick_params(which='both', direction='in')
ax.yaxis.set_tick_params(which='both', direction='in')
self._pdos.plot(ax,
indices=pdos_indices,
legend=legend,
draw_grid=False)
ax.set_ylim((0, None))
return plt | [
"def",
"plot_projected_dos",
"(",
"self",
",",
"pdos_indices",
"=",
"None",
",",
"legend",
"=",
"None",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
")",
"ax",
".",
"xaxis",
".",
"s... | Plot projected DOS
Parameters
----------
pdos_indices : list of list, optional
Sets of indices of atoms whose projected DOS are summed over.
The indices start with 0. An example is as follwos:
pdos_indices=[[0, 1], [2, 3, 4, 5]]
Default is None, which means
pdos_indices=[[i] for i in range(natom)]
legend : list of instances such as str or int, optional
The str(instance) are shown in legend.
It has to be len(pdos_indices)==len(legend). Default is None.
When None, legend is not shown. | [
"Plot",
"projected",
"DOS"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1727-L1760 |
241,359 | 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):
if self._mesh is None:
msg = ("run_mesh has to be done before"
"run_thermal_properties.")
raise RuntimeError(msg)
tp = ThermalProperties(self._mesh,
is_projection=is_projection,
band_indices=band_indices,
cutoff_frequency=cutoff_frequency,
pretend_real=pretend_real)
if temperatures is None:
tp.set_temperature_range(t_step=t_step,
t_max=t_max,
t_min=t_min)
else:
tp.set_temperatures(temperatures)
tp.run()
self._thermal_properties = tp | [
"def",
"run_thermal_properties",
"(",
"self",
",",
"t_min",
"=",
"0",
",",
"t_max",
"=",
"1000",
",",
"t_step",
"=",
"10",
",",
"temperatures",
"=",
"None",
",",
"is_projection",
"=",
"False",
",",
"band_indices",
"=",
"None",
",",
"cutoff_frequency",
"=",... | Calculate thermal properties at constant volume
Parameters
----------
t_min, t_max, t_step : float, optional
Minimum and maximum temperatures and the interval in this
temperature range. Default values are 0, 1000, and 10.
temperatures : array_like, optional
Temperature points where thermal properties are calculated.
When this is set, t_min, t_max, and t_step are ignored. | [
"Calculate",
"thermal",
"properties",
"at",
"constant",
"volume"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1772-L1810 |
241,360 | 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):
warnings.warn("Phonopy.get_thermal_properties is deprecated. "
"Use Phonopy.get_thermal_properties_dict.",
DeprecationWarning)
tp = self.get_thermal_properties_dict()
return (tp['temperatures'],
tp['free_energy'],
tp['entropy'],
tp['heat_capacity']) | [
"def",
"get_thermal_properties",
"(",
"self",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Phonopy.get_thermal_properties is deprecated. \"",
"\"Use Phonopy.get_thermal_properties_dict.\"",
",",
"DeprecationWarning",
")",
"tp",
"=",
"self",
".",
"get_thermal_properties_dict",
"... | Return thermal properties
Returns
-------
(temperatures, free energy, entropy, heat capacity) | [
"Return",
"thermal",
"properties"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1856-L1872 |
241,361 | 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):
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
if self._mesh is None:
msg = ("run_mesh has to be done.")
raise RuntimeError(msg)
mesh_nums = self._mesh.mesh_numbers
ir_grid_points = self._mesh.ir_grid_points
if not self._mesh.with_eigenvectors:
msg = ("run_mesh has to be done with with_eigenvectors=True.")
raise RuntimeError(msg)
if np.prod(mesh_nums) != len(ir_grid_points):
msg = ("run_mesh has to be done with is_mesh_symmetry=False.")
raise RuntimeError(msg)
if direction is not None:
projection_direction = np.dot(direction,
self._primitive.get_cell())
td = ThermalDisplacements(
self._mesh,
projection_direction=projection_direction,
freq_min=freq_min,
freq_max=freq_max)
else:
td = ThermalDisplacements(self._mesh,
freq_min=freq_min,
freq_max=freq_max)
if temperatures is None:
td.set_temperature_range(t_min, t_max, t_step)
else:
td.set_temperatures(temperatures)
td.run()
self._thermal_displacements = td | [
"def",
"run_thermal_displacements",
"(",
"self",
",",
"t_min",
"=",
"0",
",",
"t_max",
"=",
"1000",
",",
"t_step",
"=",
"10",
",",
"temperatures",
"=",
"None",
",",
"direction",
"=",
"None",
",",
"freq_min",
"=",
"None",
",",
"freq_max",
"=",
"None",
"... | Prepare thermal displacements calculation
Parameters
----------
t_min, t_max, t_step : float, optional
Minimum and maximum temperatures and the interval in this
temperature range. Default valuues are 0, 1000, and 10.
temperatures : array_like, optional
Temperature points where thermal properties are calculated.
When this is set, t_min, t_max, and t_step are ignored.
direction : array_like, optional
Projection direction in reduced coordinates. Default is None,
i.e., no projection.
dtype=float, shape=(3,)
freq_min, freq_max : float, optional
Phonon frequencies larger than freq_min and smaller than
freq_max are included. Default is None, i.e., all phonons. | [
"Prepare",
"thermal",
"displacements",
"calculation"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1897-L1959 |
241,362 | 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):
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",
... | 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 |
241,363 | 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):
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",
... | 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 |
241,364 | 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):
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",
"=",
"(",
"\"Dyna... | 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 |
241,365 | 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):
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",
".",
"_mes... | 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 |
241,366 | 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):
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_... | 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 |
241,367 | 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):
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",
".",... | 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 |
241,368 | 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):
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",
... | 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 |
241,369 | 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
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",
... | 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 |
241,370 | 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):
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",
".",
"a... | 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 |
241,371 | 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):
_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",
"latt... | 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 |
241,372 | 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):
_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",... | 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 |
241,373 | 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):
_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",
"=",
"sympre... | 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 |
241,374 | 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):
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",
".",
"arra... | 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 |
241,375 | 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):
_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'",
",",
... | 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 |
241,376 | 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):
_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... | 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 |
241,377 | 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):
_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",
",",
"_num... | 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 |
241,378 | 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):
_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"... | 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 |
241,379 | 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):
_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",
"("... | 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 |
241,380 | 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):
_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",
".",
"arr... | 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 |
241,381 | 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):
_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",
","... | 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 |
241,382 | 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):
_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",
":"... | 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 |
241,383 | 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):
_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"... | 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 |
241,384 | 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):
_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... | 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 |
241,385 | 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):
_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'",
... | 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 |
241,386 | 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):
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",
"... | 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 |
241,387 | 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):
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",
"(",
... | 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 |
241,388 | 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):
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",
"Im... | 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 |
241,389 | 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):
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",
"f... | 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 |
241,390 | 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):
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... | 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 |
241,391 | 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
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",
"]",
",",... | 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 |
241,392 | 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):
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",
... | 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 |
241,393 | 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):
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 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 |
241,394 | 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):
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 ... | 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 |
241,395 | 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):
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",
... | 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 |
241,396 | 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):
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",
",",
... | 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 |
241,397 | 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):
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",
")",
",",
"dtyp... | 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 |
241,398 | 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):
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]'",
",",
")",
"+",
"... | 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 |
241,399 | 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):
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.