text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Convert the needle positions to the wire format.
<END_TASK>
<USER_TASK:>
Description:
def needle_positions_to_bytes(self, needle_positions):
"""Convert the needle positions to the wire format.
This conversion is used for :ref:`cnfline`.
:param needle_positions: an iterable over :attr:`needle_positions` of
length :attr:`number_of_needles`
:rtype: bytes
""" |
bit = self.needle_positions
assert len(bit) == 2
max_length = len(needle_positions)
assert max_length == self.number_of_needles
result = []
for byte_index in range(0, max_length, 8):
byte = 0
for bit_index in range(8):
index = byte_index + bit_index
if index >= max_length:
break
needle_position = needle_positions[index]
if bit.index(needle_position) == 1:
byte |= 1 << bit_index
result.append(byte)
if byte_index >= max_length:
break
result.extend(b"\x00" * (25 - len(result)))
return bytes(result) |
<SYSTEM_TASK:>
What this object is equal to.
<END_TASK>
<USER_TASK:>
Description:
def _id(self):
"""What this object is equal to.""" |
return (self.__class__, self.number_of_needles, self.needle_positions,
self.left_end_needle) |
<SYSTEM_TASK:>
Add a Chapter to your epub.
<END_TASK>
<USER_TASK:>
Description:
def add_chapter(self, c):
"""
Add a Chapter to your epub.
Args:
c (Chapter): A Chapter object representing your chapter.
Raises:
TypeError: Raised if a Chapter object isn't supplied to this
method.
""" |
try:
assert type(c) == chapter.Chapter
except AssertionError:
raise TypeError('chapter must be of type Chapter')
chapter_file_output = os.path.join(self.OEBPS_DIR, self.current_chapter_path)
c._replace_images_in_chapter(self.OEBPS_DIR)
c.write(chapter_file_output)
self._increase_current_chapter_number()
self.chapters.append(c) |
<SYSTEM_TASK:>
Create an epub file from this object.
<END_TASK>
<USER_TASK:>
Description:
def create_epub(self, output_directory, epub_name=None):
"""
Create an epub file from this object.
Args:
output_directory (str): Directory to output the epub file to
epub_name (Option[str]): The file name of your epub. This should not contain
.epub at the end. If this argument is not provided, defaults to the title of the epub.
""" |
def createTOCs_and_ContentOPF():
for epub_file, name in ((self.toc_html, 'toc.html'), (self.toc_ncx, 'toc.ncx'), (self.opf, 'content.opf'),):
epub_file.add_chapters(self.chapters)
epub_file.write(os.path.join(self.OEBPS_DIR, name))
def create_zip_archive(epub_name):
try:
assert isinstance(epub_name, basestring) or epub_name is None
except AssertionError:
raise TypeError('epub_name must be string or None')
if epub_name is None:
epub_name = self.title
epub_name = ''.join([c for c in epub_name if c.isalpha() or c.isdigit() or c == ' ']).rstrip()
epub_name_with_path = os.path.join(output_directory, epub_name)
try:
os.remove(os.path.join(epub_name_with_path, '.zip'))
except OSError:
pass
shutil.make_archive(epub_name_with_path, 'zip', self.EPUB_DIR)
return epub_name_with_path + '.zip'
def turn_zip_into_epub(zip_archive):
epub_full_name = zip_archive.strip('.zip') + '.epub'
try:
os.remove(epub_full_name)
except OSError:
pass
os.rename(zip_archive, epub_full_name)
return epub_full_name
createTOCs_and_ContentOPF()
epub_path = turn_zip_into_epub(create_zip_archive(epub_name))
return epub_path |
<SYSTEM_TASK:>
Saves an online image from image_url to image_directory with the name image_name.
<END_TASK>
<USER_TASK:>
Description:
def save_image(image_url, image_directory, image_name):
"""
Saves an online image from image_url to image_directory with the name image_name.
Returns the extension of the image saved, which is determined dynamically.
Args:
image_url (str): The url of the image.
image_directory (str): The directory to save the image in.
image_name (str): The file name to save the image as.
Raises:
ImageErrorException: Raised if unable to save the image at image_url
""" |
image_type = get_image_type(image_url)
if image_type is None:
raise ImageErrorException(image_url)
full_image_file_name = os.path.join(image_directory, image_name + '.' + image_type)
# If the image is present on the local filesystem just copy it
if os.path.exists(image_url):
shutil.copy(image_url, full_image_file_name)
return image_type
try:
# urllib.urlretrieve(image_url, full_image_file_name)
with open(full_image_file_name, 'wb') as f:
user_agent = r'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0'
request_headers = {'User-Agent': user_agent}
requests_object = requests.get(image_url, headers=request_headers)
try:
content = requests_object.content
# Check for empty response
f.write(content)
except AttributeError:
raise ImageErrorException(image_url)
except IOError:
raise ImageErrorException(image_url)
return image_type |
<SYSTEM_TASK:>
Replaces the src of an image to link to the local copy in the images folder of the ebook. Tightly coupled with bs4
<END_TASK>
<USER_TASK:>
Description:
def _replace_image(image_url, image_tag, ebook_folder,
image_name=None):
"""
Replaces the src of an image to link to the local copy in the images folder of the ebook. Tightly coupled with bs4
package.
Args:
image_url (str): The url of the image.
image_tag (bs4.element.Tag): The bs4 tag containing the image.
ebook_folder (str): The directory where the ebook files are being saved. This must contain a subdirectory
called "images".
image_name (Option[str]): The short name to save the image as. Should not contain a directory or an extension.
""" |
try:
assert isinstance(image_tag, bs4.element.Tag)
except AssertionError:
raise TypeError("image_tag cannot be of type " + str(type(image_tag)))
if image_name is None:
image_name = str(uuid.uuid4())
try:
image_full_path = os.path.join(ebook_folder, 'images')
assert os.path.exists(image_full_path)
image_extension = save_image(image_url, image_full_path,
image_name)
image_tag['src'] = 'images' + '/' + image_name + '.' + image_extension
except ImageErrorException:
image_tag.decompose()
except AssertionError:
raise ValueError('%s doesn\'t exist or doesn\'t contain a subdirectory images' % ebook_folder)
except TypeError:
image_tag.decompose() |
<SYSTEM_TASK:>
Writes the chapter object to an xhtml file.
<END_TASK>
<USER_TASK:>
Description:
def write(self, file_name):
"""
Writes the chapter object to an xhtml file.
Args:
file_name (str): The full name of the xhtml file to save to.
""" |
try:
assert file_name[-6:] == '.xhtml'
except (AssertionError, IndexError):
raise ValueError('filename must end with .xhtml')
with open(file_name, 'wb') as f:
f.write(self.content.encode('utf-8')) |
<SYSTEM_TASK:>
Creates a Chapter object from a url. Pulls the webpage from the
<END_TASK>
<USER_TASK:>
Description:
def create_chapter_from_url(self, url, title=None):
"""
Creates a Chapter object from a url. Pulls the webpage from the
given url, sanitizes it using the clean_function method, and saves
it as the content of the created chapter. Basic webpage loaded
before any javascript executed.
Args:
url (string): The url to pull the content of the created Chapter
from
title (Option[string]): The title of the created Chapter. By
default, this is None, in which case the title will try to be
inferred from the webpage at the url.
Returns:
Chapter: A chapter object whose content is the webpage at the given
url and whose title is that provided or inferred from the url
Raises:
ValueError: Raised if unable to connect to url supplied
""" |
try:
request_object = requests.get(url, headers=self.request_headers, allow_redirects=False)
except (requests.exceptions.MissingSchema,
requests.exceptions.ConnectionError):
raise ValueError("%s is an invalid url or no network connection" % url)
except requests.exceptions.SSLError:
raise ValueError("Url %s doesn't have valid SSL certificate" % url)
unicode_string = request_object.text
return self.create_chapter_from_string(unicode_string, url, title) |
<SYSTEM_TASK:>
Creates a Chapter object from an html or xhtml file. Sanitizes the
<END_TASK>
<USER_TASK:>
Description:
def create_chapter_from_file(self, file_name, url=None, title=None):
"""
Creates a Chapter object from an html or xhtml file. Sanitizes the
file's content using the clean_function method, and saves
it as the content of the created chapter.
Args:
file_name (string): The file_name containing the html or xhtml
content of the created Chapter
url (Option[string]): A url to infer the title of the chapter from
title (Option[string]): The title of the created Chapter. By
default, this is None, in which case the title will try to be
inferred from the webpage at the url.
Returns:
Chapter: A chapter object whose content is the given file
and whose title is that provided or inferred from the url
""" |
with codecs.open(file_name, 'r', encoding='utf-8') as f:
content_string = f.read()
return self.create_chapter_from_string(content_string, url, title) |
<SYSTEM_TASK:>
Creates a Chapter object from a string. Sanitizes the
<END_TASK>
<USER_TASK:>
Description:
def create_chapter_from_string(self, html_string, url=None, title=None):
"""
Creates a Chapter object from a string. Sanitizes the
string using the clean_function method, and saves
it as the content of the created chapter.
Args:
html_string (string): The html or xhtml content of the created
Chapter
url (Option[string]): A url to infer the title of the chapter from
title (Option[string]): The title of the created Chapter. By
default, this is None, in which case the title will try to be
inferred from the webpage at the url.
Returns:
Chapter: A chapter object whose content is the given string
and whose title is that provided or inferred from the url
""" |
clean_html_string = self.clean_function(html_string)
clean_xhtml_string = clean.html_to_xhtml(clean_html_string)
if title:
pass
else:
try:
root = BeautifulSoup(html_string, 'html.parser')
title_node = root.title
if title_node is not None:
title = unicode(title_node.string)
else:
raise ValueError
except (IndexError, ValueError):
title = 'Ebook Chapter'
return Chapter(clean_xhtml_string, title, url) |
<SYSTEM_TASK:>
Creates full html tree from a fragment. Assumes that tag should be wrapped in a body and is currently not
<END_TASK>
<USER_TASK:>
Description:
def create_html_from_fragment(tag):
"""
Creates full html tree from a fragment. Assumes that tag should be wrapped in a body and is currently not
Args:
tag: a bs4.element.Tag
Returns:"
bs4.element.Tag: A bs4 tag representing a full html document
""" |
try:
assert isinstance(tag, bs4.element.Tag)
except AssertionError:
raise TypeError
try:
assert tag.find_all('body') == []
except AssertionError:
raise ValueError
soup = BeautifulSoup('<html><head></head><body></body></html>', 'html.parser')
soup.body.append(tag)
return soup |
<SYSTEM_TASK:>
Trims leadings and trailing whitespace between tags in an html document
<END_TASK>
<USER_TASK:>
Description:
def condense(input_string):
"""
Trims leadings and trailing whitespace between tags in an html document
Args:
input_string: A (possible unicode) string representing HTML.
Returns:
A (possibly unicode) string representing HTML.
Raises:
TypeError: Raised if input_string isn't a unicode string or string.
""" |
try:
assert isinstance(input_string, basestring)
except AssertionError:
raise TypeError
removed_leading_whitespace = re.sub('>\s+', '>', input_string).strip()
removed_trailing_whitespace = re.sub('\s+<', '<', removed_leading_whitespace).strip()
return removed_trailing_whitespace |
<SYSTEM_TASK:>
Replaces the current application default depot
<END_TASK>
<USER_TASK:>
Description:
def set_default(cls, name):
"""Replaces the current application default depot""" |
if name not in cls._depots:
raise RuntimeError('%s depot has not been configured' % (name,))
cls._default_depot = name |
<SYSTEM_TASK:>
Gets the application wide depot instance.
<END_TASK>
<USER_TASK:>
Description:
def get(cls, name=None):
"""Gets the application wide depot instance.
Might return ``None`` if :meth:`configure` has not been
called yet.
""" |
if name is None:
name = cls._default_depot
name = cls.resolve_alias(name) # resolve alias
return cls._depots.get(name) |
<SYSTEM_TASK:>
Retrieves a file by storage name and fileid in the form of a path
<END_TASK>
<USER_TASK:>
Description:
def get_file(cls, path):
"""Retrieves a file by storage name and fileid in the form of a path
Path is expected to be ``storage_name/fileid``.
""" |
depot_name, file_id = path.split('/', 1)
depot = cls.get(depot_name)
return depot.get(file_id) |
<SYSTEM_TASK:>
Configures an application depot.
<END_TASK>
<USER_TASK:>
Description:
def configure(cls, name, config, prefix='depot.'):
"""Configures an application depot.
This configures the application wide depot from a settings dictionary.
The settings dictionary is usually loaded from an application configuration
file where all the depot options are specified with a given ``prefix``.
The default ``prefix`` is *depot.*, the minimum required setting
is ``depot.backend`` which specified the required backend for files storage.
Additional options depend on the choosen backend.
""" |
if name in cls._depots:
raise RuntimeError('Depot %s has already been configured' % (name,))
if cls._default_depot is None:
cls._default_depot = name
cls._depots[name] = cls.from_config(config, prefix)
return cls._depots[name] |
<SYSTEM_TASK:>
Creates the application WSGI middleware in charge of serving local files.
<END_TASK>
<USER_TASK:>
Description:
def make_middleware(cls, app, **options):
"""Creates the application WSGI middleware in charge of serving local files.
A Depot middleware is required if your application wants to serve files from
storages that don't directly provide and HTTP interface like
:class:`depot.io.local.LocalFileStorage` and :class:`depot.io.gridfs.GridFSStorage`
""" |
from depot.middleware import DepotMiddleware
mw = DepotMiddleware(app, **options)
cls.set_middleware(mw)
return mw |
<SYSTEM_TASK:>
Creates a new depot from a settings dictionary.
<END_TASK>
<USER_TASK:>
Description:
def from_config(cls, config, prefix='depot.'):
"""Creates a new depot from a settings dictionary.
Behaves like the :meth:`configure` method but instead of configuring the application
depot it creates a new one each time.
""" |
config = config or {}
# Get preferred storage backend
backend = config.get(prefix + 'backend', 'depot.io.local.LocalFileStorage')
# Get all options
prefixlen = len(prefix)
options = dict((k[prefixlen:], config[k]) for k in config.keys() if k.startswith(prefix))
# Backend is already passed as a positional argument
options.pop('backend', None)
return cls._new(backend, **options) |
<SYSTEM_TASK:>
This is only for testing pourposes, resets the DepotManager status
<END_TASK>
<USER_TASK:>
Description:
def _clear(cls):
"""This is only for testing pourposes, resets the DepotManager status
This is to simplify writing test fixtures, resets the DepotManager global
status and removes the informations related to the current configured depots
and middleware.
""" |
cls._default_depot = None
cls._depots = {}
cls._middleware = None
cls._aliases = {} |
<SYSTEM_TASK:>
Return the user object whose email address is ``email``.
<END_TASK>
<USER_TASK:>
Description:
def by_email_address(cls, email):
"""Return the user object whose email address is ``email``.""" |
return DBSession.query(cls).filter_by(email_address=email).first() |
<SYSTEM_TASK:>
Return the user object whose user name is ``username``.
<END_TASK>
<USER_TASK:>
Description:
def by_user_name(cls, username):
"""Return the user object whose user name is ``username``.""" |
return DBSession.query(cls).filter_by(user_name=username).first() |
<SYSTEM_TASK:>
Check the password against existing credentials.
<END_TASK>
<USER_TASK:>
Description:
def validate_password(self, password):
"""
Check the password against existing credentials.
:param password: the password that was provided by the user to
try and authenticate. This is the clear text version that we will
need to match against the hashed one in the database.
:type password: unicode object.
:return: Whether the password is valid.
:rtype: bool
""" |
hash = sha256()
hash.update((password + self.password[:64]).encode('utf-8'))
return self.password[64:] == hash.hexdigest() |
<SYSTEM_TASK:>
Tries to extract from the given input the actual file object, filename and content_type
<END_TASK>
<USER_TASK:>
Description:
def fileinfo(fileobj, filename=None, content_type=None, existing=None):
"""Tries to extract from the given input the actual file object, filename and content_type
This is used by the create and replace methods to correctly deduce their parameters
from the available information when possible.
""" |
return _FileInfo(fileobj, filename, content_type).get_info(existing) |
<SYSTEM_TASK:>
Redirect the user to the initially requested page on successful
<END_TASK>
<USER_TASK:>
Description:
def post_login(self, came_from=lurl('/')):
"""
Redirect the user to the initially requested page on successful
authentication or redirect her back to the login page if login failed.
""" |
if not request.identity:
login_counter = request.environ.get('repoze.who.logins', 0) + 1
redirect('/login',
params=dict(came_from=came_from, __logins=login_counter))
userid = request.identity['repoze.who.userid']
flash(_('Welcome back, %s!') % userid)
redirect(came_from) |
<SYSTEM_TASK:>
Return a list of date elements by applying rewrites to the initial date element list
<END_TASK>
<USER_TASK:>
Description:
def _apply_rewrites(date_classes, rules):
"""
Return a list of date elements by applying rewrites to the initial date element list
""" |
for rule in rules:
date_classes = rule.execute(date_classes)
return date_classes |
<SYSTEM_TASK:>
Return the date_elem that has the most restrictive range from date_elems
<END_TASK>
<USER_TASK:>
Description:
def _most_restrictive(date_elems):
"""
Return the date_elem that has the most restrictive range from date_elems
""" |
most_index = len(DATE_ELEMENTS)
for date_elem in date_elems:
if date_elem in DATE_ELEMENTS and DATE_ELEMENTS.index(date_elem) < most_index:
most_index = DATE_ELEMENTS.index(date_elem)
if most_index < len(DATE_ELEMENTS):
return DATE_ELEMENTS[most_index]
else:
raise KeyError('No least restrictive date element found') |
<SYSTEM_TASK:>
If condition, return a new elem_list provided by executing action.
<END_TASK>
<USER_TASK:>
Description:
def execute(self, elem_list):
"""
If condition, return a new elem_list provided by executing action.
""" |
if self.condition.is_true(elem_list):
return self.action.act(elem_list)
else:
return elem_list |
<SYSTEM_TASK:>
Return the first position in elem_list where find_seq starts
<END_TASK>
<USER_TASK:>
Description:
def find(find_seq, elem_list):
"""
Return the first position in elem_list where find_seq starts
""" |
seq_pos = 0
for index, elem in enumerate(elem_list):
if Sequence.match(elem, find_seq[seq_pos]):
seq_pos += 1
if seq_pos == len(find_seq): # found matching sequence
return index - seq_pos + 1
else: # exited sequence
seq_pos = 0
raise LookupError('Failed to find sequence in elem_list') |
<SYSTEM_TASK:>
Main function for Mine Sweeper Game.
<END_TASK>
<USER_TASK:>
Description:
def ms_game_main(board_width, board_height, num_mines, port, ip_add):
"""Main function for Mine Sweeper Game.
Parameters
----------
board_width : int
the width of the board (> 0)
board_height : int
the height of the board (> 0)
num_mines : int
the number of mines, cannot be larger than
(board_width x board_height)
port : int
UDP port number, default is 5678
ip_add : string
the ip address for receiving the command,
default is localhost.
""" |
ms_game = MSGame(board_width, board_height, num_mines,
port=port, ip_add=ip_add)
ms_app = QApplication([])
ms_window = QWidget()
ms_window.setAutoFillBackground(True)
ms_window.setWindowTitle("Mine Sweeper")
ms_layout = QGridLayout()
ms_window.setLayout(ms_layout)
fun_wg = gui.ControlWidget()
grid_wg = gui.GameWidget(ms_game, fun_wg)
remote_thread = gui.RemoteControlThread()
def update_grid_remote(move_msg):
"""Update grid from remote control."""
if grid_wg.ms_game.game_status == 2:
grid_wg.ms_game.play_move_msg(str(move_msg))
grid_wg.update_grid()
remote_thread.transfer.connect(update_grid_remote)
def reset_button_state():
"""Reset button state."""
grid_wg.reset_game()
fun_wg.reset_button.clicked.connect(reset_button_state)
ms_layout.addWidget(fun_wg, 0, 0)
ms_layout.addWidget(grid_wg, 1, 0)
remote_thread.control_start(grid_wg.ms_game)
ms_window.show()
ms_app.exec_() |
<SYSTEM_TASK:>
Init a new game.
<END_TASK>
<USER_TASK:>
Description:
def init_new_game(self, with_tcp=True):
"""Init a new game.
Parameters
----------
board : MSBoard
define a new board.
game_status : int
define the game status:
0: lose, 1: win, 2: playing
moves : int
how many moves carried out.
""" |
self.board = self.create_board(self.board_width, self.board_height,
self.num_mines)
self.game_status = 2
self.num_moves = 0
self.move_history = []
if with_tcp is True:
# init TCP communication.
self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.tcp_socket.bind((self.TCP_IP, self.TCP_PORT))
self.tcp_socket.listen(1) |
<SYSTEM_TASK:>
Check if a move is valid.
<END_TASK>
<USER_TASK:>
Description:
def check_move(self, move_type, move_x, move_y):
"""Check if a move is valid.
If the move is not valid, then shut the game.
If the move is valid, then setup a dictionary for the game,
and update move counter.
TODO: maybe instead of shut the game, can end the game or turn it into
a valid move?
Parameters
----------
move_type : string
one of four move types:
"click", "flag", "unflag", "question"
move_x : int
X position of the move
move_y : int
Y position of the move
""" |
if move_type not in self.move_types:
raise ValueError("This is not a valid move!")
if move_x < 0 or move_x >= self.board_width:
raise ValueError("This is not a valid X position of the move!")
if move_y < 0 or move_y >= self.board_height:
raise ValueError("This is not a valid Y position of the move!")
move_des = {}
move_des["move_type"] = move_type
move_des["move_x"] = move_x
move_des["move_y"] = move_y
self.num_moves += 1
return move_des |
<SYSTEM_TASK:>
Updat board by a given move.
<END_TASK>
<USER_TASK:>
Description:
def play_move(self, move_type, move_x, move_y):
"""Updat board by a given move.
Parameters
----------
move_type : string
one of four move types:
"click", "flag", "unflag", "question"
move_x : int
X position of the move
move_y : int
Y position of the move
""" |
# record the move
if self.game_status == 2:
self.move_history.append(self.check_move(move_type, move_x,
move_y))
else:
self.end_game()
# play the move, update the board
if move_type == "click":
self.board.click_field(move_x, move_y)
elif move_type == "flag":
self.board.flag_field(move_x, move_y)
elif move_type == "unflag":
self.board.unflag_field(move_x, move_y)
elif move_type == "question":
self.board.question_field(move_x, move_y)
# check the status, see if end the game
if self.board.check_board() == 0:
self.game_status = 0 # game loses
# self.print_board()
self.end_game()
elif self.board.check_board() == 1:
self.game_status = 1 # game wins
# self.print_board()
self.end_game()
elif self.board.check_board() == 2:
self.game_status = 2 |
<SYSTEM_TASK:>
Parse a move from a string.
<END_TASK>
<USER_TASK:>
Description:
def parse_move(self, move_msg):
"""Parse a move from a string.
Parameters
----------
move_msg : string
a valid message should be in:
"[move type]: [X], [Y]"
Returns
-------
""" |
# TODO: some condition check
type_idx = move_msg.index(":")
move_type = move_msg[:type_idx]
pos_idx = move_msg.index(",")
move_x = int(move_msg[type_idx+1:pos_idx])
move_y = int(move_msg[pos_idx+1:])
return move_type, move_x, move_y |
<SYSTEM_TASK:>
Another play move function for move message.
<END_TASK>
<USER_TASK:>
Description:
def play_move_msg(self, move_msg):
"""Another play move function for move message.
Parameters
----------
move_msg : string
a valid message should be in:
"[move type]: [X], [Y]"
""" |
move_type, move_x, move_y = self.parse_move(move_msg)
self.play_move(move_type, move_x, move_y) |
<SYSTEM_TASK:>
Waiting for a TCP connection.
<END_TASK>
<USER_TASK:>
Description:
def tcp_accept(self):
"""Waiting for a TCP connection.""" |
self.conn, self.addr = self.tcp_socket.accept()
print("[MESSAGE] The connection is established at: ", self.addr)
self.tcp_send("> ") |
<SYSTEM_TASK:>
Receive data from TCP port.
<END_TASK>
<USER_TASK:>
Description:
def tcp_receive(self):
"""Receive data from TCP port.""" |
data = self.conn.recv(self.BUFFER_SIZE)
if type(data) != str:
# Python 3 specific
data = data.decode("utf-8")
return str(data) |
<SYSTEM_TASK:>
Init a valid board by given settings.
<END_TASK>
<USER_TASK:>
Description:
def init_board(self):
"""Init a valid board by given settings.
Parameters
----------
mine_map : numpy.ndarray
the map that defines the mine
0 is empty, 1 is mine
info_map : numpy.ndarray
the map that presents to gamer
0-8 is number of mines in srrounding.
9 is flagged field.
10 is questioned field.
11 is undiscovered field.
12 is a mine field.
""" |
self.mine_map = np.zeros((self.board_height, self.board_width),
dtype=np.uint8)
idx_list = np.random.permutation(self.board_width*self.board_height)
idx_list = idx_list[:self.num_mines]
for idx in idx_list:
idx_x = int(idx % self.board_width)
idx_y = int(idx / self.board_width)
self.mine_map[idx_y, idx_x] = 1
self.info_map = np.ones((self.board_height, self.board_width),
dtype=np.uint8)*11 |
<SYSTEM_TASK:>
Click one grid by given position.
<END_TASK>
<USER_TASK:>
Description:
def click_field(self, move_x, move_y):
"""Click one grid by given position.""" |
field_status = self.info_map[move_y, move_x]
# can only click blank region
if field_status == 11:
if self.mine_map[move_y, move_x] == 1:
self.info_map[move_y, move_x] = 12
else:
# discover the region.
self.discover_region(move_x, move_y) |
<SYSTEM_TASK:>
Get region around a location.
<END_TASK>
<USER_TASK:>
Description:
def get_region(self, move_x, move_y):
"""Get region around a location.""" |
top_left = (max(move_y-1, 0), max(move_x-1, 0))
bottom_right = (min(move_y+1, self.board_height-1),
min(move_x+1, self.board_width-1))
region_sum = self.mine_map[top_left[0]:bottom_right[0]+1,
top_left[1]:bottom_right[1]+1].sum()
return top_left, bottom_right, region_sum |
<SYSTEM_TASK:>
Unflag or unquestion a grid by given position.
<END_TASK>
<USER_TASK:>
Description:
def unflag_field(self, move_x, move_y):
"""Unflag or unquestion a grid by given position.""" |
field_status = self.info_map[move_y, move_x]
if field_status == 9 or field_status == 10:
self.info_map[move_y, move_x] = 11 |
<SYSTEM_TASK:>
Question a grid by given position.
<END_TASK>
<USER_TASK:>
Description:
def question_field(self, move_x, move_y):
"""Question a grid by given position.""" |
field_status = self.info_map[move_y, move_x]
# a questioned or undiscovered field
if field_status != 10 and (field_status == 9 or field_status == 11):
self.info_map[move_y, move_x] = 10 |
<SYSTEM_TASK:>
Check the board status and give feedback.
<END_TASK>
<USER_TASK:>
Description:
def check_board(self):
"""Check the board status and give feedback.""" |
num_mines = np.sum(self.info_map == 12)
num_undiscovered = np.sum(self.info_map == 11)
num_questioned = np.sum(self.info_map == 10)
if num_mines > 0:
return 0
elif np.array_equal(self.info_map == 9, self.mine_map):
return 1
elif num_undiscovered > 0 or num_questioned > 0:
return 2 |
<SYSTEM_TASK:>
Create a grid layout with stacked widgets.
<END_TASK>
<USER_TASK:>
Description:
def create_grid(self, grid_width, grid_height):
"""Create a grid layout with stacked widgets.
Parameters
----------
grid_width : int
the width of the grid
grid_height : int
the height of the grid
""" |
self.grid_layout = QGridLayout()
self.setLayout(self.grid_layout)
self.grid_layout.setSpacing(1)
self.grid_wgs = {}
for i in xrange(grid_height):
for j in xrange(grid_width):
self.grid_wgs[(i, j)] = FieldWidget()
self.grid_layout.addWidget(self.grid_wgs[(i, j)], i, j) |
<SYSTEM_TASK:>
Set info label by given settings.
<END_TASK>
<USER_TASK:>
Description:
def info_label(self, indicator):
"""Set info label by given settings.
Parameters
----------
indicator : int
A number where
0-8 is number of mines in srrounding.
12 is a mine field.
""" |
if indicator in xrange(1, 9):
self.id = indicator
self.setPixmap(QtGui.QPixmap(NUMBER_PATHS[indicator]).scaled(
self.field_width, self.field_height))
elif indicator == 0:
self.id == 0
self.setPixmap(QtGui.QPixmap(NUMBER_PATHS[0]).scaled(
self.field_width, self.field_height))
elif indicator == 12:
self.id = 12
self.setPixmap(QtGui.QPixmap(BOOM_PATH).scaled(self.field_width,
self.field_height))
self.setStyleSheet("QLabel {background-color: black;}")
elif indicator == 9:
self.id = 9
self.setPixmap(QtGui.QPixmap(FLAG_PATH).scaled(self.field_width,
self.field_height))
self.setStyleSheet("QLabel {background-color: #A3C1DA;}")
elif indicator == 10:
self.id = 10
self.setPixmap(QtGui.QPixmap(QUESTION_PATH).scaled(
self.field_width, self.field_height))
self.setStyleSheet("QLabel {background-color: yellow;}")
elif indicator == 11:
self.id = 11
self.setPixmap(QtGui.QPixmap(EMPTY_PATH).scaled(
self.field_width*3, self.field_height*3))
self.setStyleSheet('QLabel {background-color: blue;}') |
<SYSTEM_TASK:>
Configure which kinds of exceptions trigger plugin.
<END_TASK>
<USER_TASK:>
Description:
def configure(self, options, conf):
"""Configure which kinds of exceptions trigger plugin.
""" |
self.conf = conf
self.enabled = options.epdb_debugErrors or options.epdb_debugFailures
self.enabled_for_errors = options.epdb_debugErrors
self.enabled_for_failures = options.epdb_debugFailures |
<SYSTEM_TASK:>
Convert a chain of traceback or frame objects into a list of frames.
<END_TASK>
<USER_TASK:>
Description:
def stackToList(stack):
"""
Convert a chain of traceback or frame objects into a list of frames.
""" |
if isinstance(stack, types.TracebackType):
while stack.tb_next:
stack = stack.tb_next
stack = stack.tb_frame
out = []
while stack:
out.append(stack)
stack = stack.f_back
return out |
<SYSTEM_TASK:>
Read in and parse IAC commands as passed by telnetlib.
<END_TASK>
<USER_TASK:>
Description:
def process_IAC(self, sock, cmd, option):
"""
Read in and parse IAC commands as passed by telnetlib.
SB/SE commands are stored in sbdataq, and passed in w/ a command
of SE.
""" |
if cmd == DO:
if option == TM:
# timing mark - send WILL into outgoing stream
os.write(self.remote, IAC + WILL + TM)
else:
pass
elif cmd == IP:
# interrupt process
os.write(self.local, IPRESP)
elif cmd == SB:
pass
elif cmd == SE:
option = self.sbdataq[0]
if option == NAWS[0]:
# negotiate window size.
cols = six.indexbytes(self.sbdataq, 1)
rows = six.indexbytes(self.sbdataq, 2)
s = struct.pack('HHHH', rows, cols, 0, 0)
fcntl.ioctl(self.local, termios.TIOCSWINSZ, s)
elif cmd == DONT:
pass
else:
pass |
<SYSTEM_TASK:>
Creates a child process that is fully controlled by this
<END_TASK>
<USER_TASK:>
Description:
def handle(self):
"""
Creates a child process that is fully controlled by this
request handler, and serves data to and from it via the
protocol handler.
""" |
pid, fd = pty.fork()
if pid:
protocol = TelnetServerProtocolHandler(self.request, fd)
protocol.handle()
else:
self.execute() |
<SYSTEM_TASK:>
Handle one request - serve current process to one connection.
<END_TASK>
<USER_TASK:>
Description:
def handle_request(self):
"""
Handle one request - serve current process to one connection.
Use close_request() to disconnect this process.
""" |
try:
request, client_address = self.get_request()
except socket.error:
return
if self.verify_request(request, client_address):
try:
# we only serve once, and we want to free up the port
# for future serves.
self.socket.close()
self.process_request(request, client_address)
except SocketConnected as err:
self._serve_process(err.slaveFd, err.serverPid)
return
except Exception as err:
self.handle_error(request, client_address)
self.close_request() |
<SYSTEM_TASK:>
An auxiliary function to construct a dictionary of Criteria
<END_TASK>
<USER_TASK:>
Description:
def atom_criteria(*params):
"""An auxiliary function to construct a dictionary of Criteria""" |
result = {}
for index, param in enumerate(params):
if param is None:
continue
elif isinstance(param, int):
result[index] = HasAtomNumber(param)
else:
result[index] = param
return result |
<SYSTEM_TASK:>
the size must be the same as the length of the array numbers and all elements must be strings
<END_TASK>
<USER_TASK:>
Description:
def _check_symbols(self, symbols):
"""the size must be the same as the length of the array numbers and all elements must be strings""" |
if len(symbols) != self.size:
raise TypeError("The number of symbols in the graph does not "
"match the length of the atomic numbers array.")
for symbol in symbols:
if not isinstance(symbol, str):
raise TypeError("All symbols must be strings.") |
<SYSTEM_TASK:>
Construct a molecular graph from the blob representation
<END_TASK>
<USER_TASK:>
Description:
def from_blob(cls, s):
"""Construct a molecular graph from the blob representation""" |
atom_str, edge_str = s.split()
numbers = np.array([int(s) for s in atom_str.split(",")])
edges = []
orders = []
for s in edge_str.split(","):
i, j, o = (int(w) for w in s.split("_"))
edges.append((i, j))
orders.append(o)
return cls(edges, numbers, np.array(orders)) |
<SYSTEM_TASK:>
A compact text representation of the graph
<END_TASK>
<USER_TASK:>
Description:
def blob(self):
"""A compact text representation of the graph""" |
atom_str = ",".join(str(number) for number in self.numbers)
edge_str = ",".join("%i_%i_%i" % (i, j, o) for (i, j), o in zip(self.edges, self.orders))
return "%s %s" % (atom_str, edge_str) |
<SYSTEM_TASK:>
Return a string based on the atom number
<END_TASK>
<USER_TASK:>
Description:
def get_vertex_string(self, i):
"""Return a string based on the atom number""" |
number = self.numbers[i]
if number == 0:
return Graph.get_vertex_string(self, i)
else:
# pad with zeros to make sure that string sort is identical to number sort
return "%03i" % number |
<SYSTEM_TASK:>
Return a string based on the bond order
<END_TASK>
<USER_TASK:>
Description:
def get_edge_string(self, i):
"""Return a string based on the bond order""" |
order = self.orders[i]
if order == 0:
return Graph.get_edge_string(self, i)
else:
# pad with zeros to make sure that string sort is identical to number sort
return "%03i" % order |
<SYSTEM_TASK:>
Creates a subgraph of the current graph
<END_TASK>
<USER_TASK:>
Description:
def get_subgraph(self, subvertices, normalize=False):
"""Creates a subgraph of the current graph
See :meth:`molmod.graphs.Graph.get_subgraph` for more information.
""" |
graph = Graph.get_subgraph(self, subvertices, normalize)
if normalize:
new_numbers = self.numbers[graph._old_vertex_indexes] # vertices do change
else:
new_numbers = self.numbers # vertices don't change!
if self.symbols is None:
new_symbols = None
elif normalize:
new_symbols = tuple(self.symbols[i] for i in graph._old_vertex_indexes)
else:
new_symbols = self.symbols
new_orders = self.orders[graph._old_edge_indexes]
result = MolecularGraph(graph.edges, new_numbers, new_orders, new_symbols)
if normalize:
result._old_vertex_indexes = graph._old_vertex_indexes
result._old_edge_indexes = graph._old_edge_indexes
return result |
<SYSTEM_TASK:>
Returns a molecular graph where hydrogens are added explicitely
<END_TASK>
<USER_TASK:>
Description:
def add_hydrogens(self, formal_charges=None):
"""Returns a molecular graph where hydrogens are added explicitely
When the bond order is unknown, it assumes bond order one. If the
graph has an attribute formal_charges, this routine will take it
into account when counting the number of hydrogens to be added. The
returned graph will also have a formal_charges attribute.
This routine only adds hydrogen atoms for a limited set of atoms from
the periodic system: B, C, N, O, F, Al, Si, P, S, Cl, Br.
""" |
new_edges = list(self.edges)
counter = self.num_vertices
for i in range(self.num_vertices):
num_elec = self.numbers[i]
if formal_charges is not None:
num_elec -= int(formal_charges[i])
if num_elec >= 5 and num_elec <= 9:
num_hydrogen = num_elec - 10 + 8
elif num_elec >= 13 and num_elec <= 17:
num_hydrogen = num_elec - 18 + 8
elif num_elec == 35:
num_hydrogen = 1
else:
continue
if num_hydrogen > 4:
num_hydrogen = 8 - num_hydrogen
for n in self.neighbors[i]:
bo = self.orders[self.edge_index[frozenset([i, n])]]
if bo <= 0:
bo = 1
num_hydrogen -= int(bo)
for j in range(num_hydrogen):
new_edges.append((i, counter))
counter += 1
new_numbers = np.zeros(counter, int)
new_numbers[:self.num_vertices] = self.numbers
new_numbers[self.num_vertices:] = 1
new_orders = np.zeros(len(new_edges), int)
new_orders[:self.num_edges] = self.orders
new_orders[self.num_edges:] = 1
result = MolecularGraph(new_edges, new_numbers, new_orders)
return result |
<SYSTEM_TASK:>
Check the completeness of the ring match
<END_TASK>
<USER_TASK:>
Description:
def complete(self, match, subject_graph):
"""Check the completeness of the ring match""" |
if not CustomPattern.complete(self, match, subject_graph):
return False
if self.strong:
# If the ring is not strong, return False
if self.size % 2 == 0:
# even ring
for i in range(self.size//2):
vertex1_start = match.forward[i]
vertex1_stop = match.forward[(i+self.size//2)%self.size]
paths = list(subject_graph.iter_shortest_paths(vertex1_start, vertex1_stop))
if len(paths) != 2:
#print "Even ring must have two paths between opposite vertices"
return False
for path in paths:
if len(path) != self.size//2+1:
#print "Paths between opposite vertices must half the size of the ring+1"
return False
else:
# odd ring
for i in range(self.size//2+1):
vertex1_start = match.forward[i]
vertex1_stop = match.forward[(i+self.size//2)%self.size]
paths = list(subject_graph.iter_shortest_paths(vertex1_start, vertex1_stop))
if len(paths) > 1:
return False
if len(paths[0]) != self.size//2+1:
return False
vertex1_stop = match.forward[(i+self.size//2+1)%self.size]
paths = list(subject_graph.iter_shortest_paths(vertex1_start, vertex1_stop))
if len(paths) > 1:
return False
if len(paths[0]) != self.size//2+1:
return False
return True |
<SYSTEM_TASK:>
Return the value of the attribute
<END_TASK>
<USER_TASK:>
Description:
def get(self, copy=False):
"""Return the value of the attribute""" |
array = getattr(self.owner, self.name)
if copy:
return array.copy()
else:
return array |
<SYSTEM_TASK:>
Load the array data from a file-like object
<END_TASK>
<USER_TASK:>
Description:
def load(self, f, skip):
"""Load the array data from a file-like object""" |
array = self.get()
counter = 0
counter_limit = array.size
convert = array.dtype.type
while counter < counter_limit:
line = f.readline()
words = line.split()
for word in words:
if counter >= counter_limit:
raise FileFormatError("Wrong array data: too many values.")
if not skip:
array.flat[counter] = convert(word)
counter += 1 |
<SYSTEM_TASK:>
Register a new attribute to take care of with dump and load
<END_TASK>
<USER_TASK:>
Description:
def _register(self, name, AttrCls):
"""Register a new attribute to take care of with dump and load
Arguments:
| ``name`` -- the name to be used in the dump file
| ``AttrCls`` -- an attr class describing the attribute
""" |
if not issubclass(AttrCls, StateAttr):
raise TypeError("The second argument must a StateAttr instance.")
if len(name) > 40:
raise ValueError("Name can count at most 40 characters.")
self._fields[name] = AttrCls(self._owner, name) |
<SYSTEM_TASK:>
Return a dictionary object with the registered fields and their values
<END_TASK>
<USER_TASK:>
Description:
def get(self, subset=None):
"""Return a dictionary object with the registered fields and their values
Optional rgument:
| ``subset`` -- a list of names to restrict the number of fields
in the result
""" |
if subset is None:
return dict((name, attr.get(copy=True)) for name, attr in self._fields.items())
else:
return dict((name, attr.get(copy=True)) for name, attr in self._fields.items() if name in subset) |
<SYSTEM_TASK:>
Assign the registered fields based on a dictionary
<END_TASK>
<USER_TASK:>
Description:
def set(self, new_fields, subset=None):
"""Assign the registered fields based on a dictionary
Argument:
| ``new_fields`` -- the dictionary with the data to be assigned to
the attributes
Optional argument:
| ``subset`` -- a list of names to restrict the fields that are
effectively overwritten
""" |
for name in new_fields:
if name not in self._fields and (subset is None or name in subset):
raise ValueError("new_fields contains an unknown field '%s'." % name)
if subset is not None:
for name in subset:
if name not in self._fields:
raise ValueError("name '%s' in subset is not a known field in self._fields." % name)
if name not in new_fields:
raise ValueError("name '%s' in subset is not a known field in new_fields." % name)
if subset is None:
if len(new_fields) != len(self._fields):
raise ValueError("new_fields contains too many fields.")
for name, attr in self._fields.items():
if name in subset:
attr.set(new_fields[name]) |
<SYSTEM_TASK:>
Dump the registered fields to a file
<END_TASK>
<USER_TASK:>
Description:
def dump(self, filename):
"""Dump the registered fields to a file
Argument:
| ``filename`` -- the file to write to
""" |
with open(filename, "w") as f:
for name in sorted(self._fields):
self._fields[name].dump(f, name) |
<SYSTEM_TASK:>
Load data into the registered fields
<END_TASK>
<USER_TASK:>
Description:
def load(self, filename, subset=None):
"""Load data into the registered fields
Argument:
| ``filename`` -- the filename to read from
Optional argument:
| ``subset`` -- a list of field names that are read from the file.
If not given, all data is read from the file.
""" |
with open(filename, "r") as f:
name = None
num_names = 0
while True:
# read a header line
line = f.readline()
if len(line) == 0:
break
# process the header line
words = line.split()
name = words[0]
attr = self._fields.get(name)
if attr is None:
raise FileFormatError("Wrong header: unknown field %s" % name)
if not words[1].startswith("kind="):
raise FileFormatError("Malformatted array header line. (kind)")
kind = words[1][5:]
expected_kind = attr.get_kind(attr.get())
if kind != expected_kind:
raise FileFormatError("Wrong header: kind of field %s does not match. Got %s, expected %s" % (name, kind, expected_kind))
skip = ((subset is not None) and (name not in subset))
print(words)
if (words[2].startswith("shape=(") and words[2].endswith(")")):
if not isinstance(attr, ArrayAttr):
raise FileFormatError("field '%s' is not an array." % name)
shape = words[2][7:-1]
if shape[-1] == ', ':
shape = shape[:-1]
try:
shape = tuple(int(word) for word in shape.split(","))
except ValueError:
raise FileFormatError("Malformatted array header. (shape)")
expected_shape = attr.get().shape
if shape != expected_shape:
raise FileFormatError("Wrong header: shape of field %s does not match. Got %s, expected %s" % (name, shape, expected_shape))
attr.load(f, skip)
elif words[2].startswith("value="):
if not isinstance(attr, ScalarAttr):
raise FileFormatError("field '%s' is not a single value." % name)
if not skip:
if kind == 'i':
attr.set(int(words[2][6:]))
else:
attr.set(float(words[2][6:]))
else:
raise FileFormatError("Malformatted array header line. (shape/value)")
num_names += 1
if num_names != len(self._fields) and subset is None:
raise FileFormatError("Some fields are missing in the file.") |
<SYSTEM_TASK:>
Load the bond data from the given file
<END_TASK>
<USER_TASK:>
Description:
def _load_bond_data(self):
"""Load the bond data from the given file
It's assumed that the uncommented lines in the data file have the
following format:
symbol1 symbol2 number1 number2 bond_length_single_a bond_length_double_a bond_length_triple_a bond_length_single_b bond_length_double_b bond_length_triple_b ..."
where a, b, ... stand for different sources.
""" |
def read_units(unit_names):
"""convert unit_names into conversion factors"""
tmp = {
"A": units.angstrom,
"pm": units.picometer,
"nm": units.nanometer,
}
return [tmp[unit_name] for unit_name in unit_names]
def read_length(BOND_TYPE, words, col):
"""Read the bondlengths from a single line in the data file"""
nlow = int(words[2])
nhigh = int(words[3])
for i, conversion in zip(range((len(words) - 4) // 3), conversions):
word = words[col + 3 + i*3]
if word != 'NA':
self.lengths[BOND_TYPE][frozenset([nlow, nhigh])] = float(word)*conversion
return
with pkg_resources.resource_stream(__name__, 'data/bonds.csv') as f:
for line in f:
words = line.decode('utf-8').split()
if (len(words) > 0) and (words[0][0] != "#"):
if words[0] == "unit":
conversions = read_units(words[1:])
else:
read_length(BOND_SINGLE, words, 1)
read_length(BOND_DOUBLE, words, 2)
read_length(BOND_TRIPLE, words, 3) |
<SYSTEM_TASK:>
Completes the bond length database with approximations based on VDW radii
<END_TASK>
<USER_TASK:>
Description:
def _approximate_unkown_bond_lengths(self):
"""Completes the bond length database with approximations based on VDW radii""" |
dataset = self.lengths[BOND_SINGLE]
for n1 in periodic.iter_numbers():
for n2 in periodic.iter_numbers():
if n1 <= n2:
pair = frozenset([n1, n2])
atom1 = periodic[n1]
atom2 = periodic[n2]
#if (pair not in dataset) and hasattr(atom1, "covalent_radius") and hasattr(atom2, "covalent_radius"):
if (pair not in dataset) and (atom1.covalent_radius is not None) and (atom2.covalent_radius is not None):
dataset[pair] = (atom1.covalent_radius + atom2.covalent_radius) |
<SYSTEM_TASK:>
Return the estimated bond type
<END_TASK>
<USER_TASK:>
Description:
def bonded(self, n1, n2, distance):
"""Return the estimated bond type
Arguments:
| ``n1`` -- the atom number of the first atom in the bond
| ``n2`` -- the atom number of the second atom the bond
| ``distance`` -- the distance between the two atoms
This method checks whether for the given pair of atom numbers, the
given distance corresponds to a certain bond length. The best
matching bond type will be returned. If the distance is a factor
``self.bond_tolerance`` larger than a tabulated distance, the
algorithm will not relate them.
""" |
if distance > self.max_length * self.bond_tolerance:
return None
deviation = 0.0
pair = frozenset([n1, n2])
result = None
for bond_type in bond_types:
bond_length = self.lengths[bond_type].get(pair)
if (bond_length is not None) and \
(distance < bond_length * self.bond_tolerance):
if result is None:
result = bond_type
deviation = abs(bond_length - distance)
else:
new_deviation = abs(bond_length - distance)
if deviation > new_deviation:
result = bond_type
deviation = new_deviation
return result |
<SYSTEM_TASK:>
Return the length of a bond between n1 and n2 of type bond_type
<END_TASK>
<USER_TASK:>
Description:
def get_length(self, n1, n2, bond_type=BOND_SINGLE):
"""Return the length of a bond between n1 and n2 of type bond_type
Arguments:
| ``n1`` -- the atom number of the first atom in the bond
| ``n2`` -- the atom number of the second atom the bond
Optional argument:
| ``bond_type`` -- the type of bond [default=BOND_SINGLE]
This is a safe method for querying a bond_length. If no answer can be
found, this get_length returns None.
""" |
dataset = self.lengths.get(bond_type)
if dataset == None:
return None
return dataset.get(frozenset([n1, n2])) |
<SYSTEM_TASK:>
Construct a 3D unit cell with the given parameters
<END_TASK>
<USER_TASK:>
Description:
def from_parameters3(cls, lengths, angles):
"""Construct a 3D unit cell with the given parameters
The a vector is always parallel with the x-axis and they point in the
same direction. The b vector is always in the xy plane and points
towards the positive y-direction. The c vector points towards the
positive z-direction.
""" |
for length in lengths:
if length <= 0:
raise ValueError("The length parameters must be strictly positive.")
for angle in angles:
if angle <= 0 or angle >= np.pi:
raise ValueError("The angle parameters must lie in the range ]0 deg, 180 deg[.")
del length
del angle
matrix = np.zeros((3, 3), float)
# first cell vector along x-axis
matrix[0, 0] = lengths[0]
# second cell vector in x-y plane
matrix[0, 1] = np.cos(angles[2])*lengths[1]
matrix[1, 1] = np.sin(angles[2])*lengths[1]
# Finding the third cell vector is slightly more difficult. :-)
# It works like this:
# The dot products of a with c, b with c and c with c are known. the
# vector a has only an x component, b has no z component. This results
# in the following equations:
u_a = lengths[0]*lengths[2]*np.cos(angles[1])
u_b = lengths[1]*lengths[2]*np.cos(angles[0])
matrix[0, 2] = u_a/matrix[0, 0]
matrix[1, 2] = (u_b - matrix[0, 1]*matrix[0, 2])/matrix[1, 1]
u_c = lengths[2]**2 - matrix[0, 2]**2 - matrix[1, 2]**2
if u_c < 0:
raise ValueError("The given cell parameters do not correspond to a unit cell.")
matrix[2, 2] = np.sqrt(u_c)
active = np.ones(3, bool)
return cls(matrix, active) |
<SYSTEM_TASK:>
The volume of the unit cell
<END_TASK>
<USER_TASK:>
Description:
def volume(self):
"""The volume of the unit cell
The actual definition of the volume depends on the number of active
directions:
* num_active == 0 -- always -1
* num_active == 1 -- length of the cell vector
* num_active == 2 -- surface of the parallelogram
* num_active == 3 -- volume of the parallelepiped
""" |
active = self.active_inactive[0]
if len(active) == 0:
return -1
elif len(active) == 1:
return np.linalg.norm(self.matrix[:, active[0]])
elif len(active) == 2:
return np.linalg.norm(np.cross(self.matrix[:, active[0]], self.matrix[:, active[1]]))
elif len(active) == 3:
return abs(np.linalg.det(self.matrix)) |
<SYSTEM_TASK:>
The indexes of the active and the inactive cell vectors
<END_TASK>
<USER_TASK:>
Description:
def active_inactive(self):
"""The indexes of the active and the inactive cell vectors""" |
active_indices = []
inactive_indices = []
for index, active in enumerate(self.active):
if active:
active_indices.append(index)
else:
inactive_indices.append(index)
return active_indices, inactive_indices |
<SYSTEM_TASK:>
The reciprocal of the unit cell
<END_TASK>
<USER_TASK:>
Description:
def reciprocal(self):
"""The reciprocal of the unit cell
In case of a three-dimensional periodic system, this is trivially the
transpose of the inverse of the cell matrix. This means that each
column of the matrix corresponds to a reciprocal cell vector. In case
of lower-dimensional periodicity, the inactive columns are zero, and
the active columns span the same sub space as the original cell
vectors.
""" |
U, S, Vt = np.linalg.svd(self.matrix*self.active)
Sinv = np.zeros(S.shape, float)
for i in range(3):
if abs(S[i]) < self.eps:
Sinv[i] = 0.0
else:
Sinv[i] = 1.0/S[i]
return np.dot(U*Sinv, Vt)*self.active |
<SYSTEM_TASK:>
An equivalent unit cell with the active cell vectors coming first
<END_TASK>
<USER_TASK:>
Description:
def ordered(self):
"""An equivalent unit cell with the active cell vectors coming first""" |
active, inactive = self.active_inactive
order = active + inactive
return UnitCell(self.matrix[:,order], self.active[order]) |
<SYSTEM_TASK:>
Computes the rotation matrix that aligns the unit cell with the
<END_TASK>
<USER_TASK:>
Description:
def alignment_a(self):
"""Computes the rotation matrix that aligns the unit cell with the
Cartesian axes, starting with cell vector a.
* a parallel to x
* b in xy-plane with b_y positive
* c with c_z positive
""" |
from molmod.transformations import Rotation
new_x = self.matrix[:, 0].copy()
new_x /= np.linalg.norm(new_x)
new_z = np.cross(new_x, self.matrix[:, 1])
new_z /= np.linalg.norm(new_z)
new_y = np.cross(new_z, new_x)
new_y /= np.linalg.norm(new_y)
return Rotation(np.array([new_x, new_y, new_z])) |
<SYSTEM_TASK:>
Computes the distances between neighboring crystal planes
<END_TASK>
<USER_TASK:>
Description:
def spacings(self):
"""Computes the distances between neighboring crystal planes""" |
result_invsq = (self.reciprocal**2).sum(axis=0)
result = np.zeros(3, float)
for i in range(3):
if result_invsq[i] > 0:
result[i] = result_invsq[i]**(-0.5)
return result |
<SYSTEM_TASK:>
Returns a new unit cell with an additional cell vector
<END_TASK>
<USER_TASK:>
Description:
def add_cell_vector(self, vector):
"""Returns a new unit cell with an additional cell vector""" |
act = self.active_inactive[0]
if len(act) == 3:
raise ValueError("The unit cell already has three active cell vectors.")
matrix = np.zeros((3, 3), float)
active = np.zeros(3, bool)
if len(act) == 0:
# Add the new vector
matrix[:, 0] = vector
active[0] = True
return UnitCell(matrix, active)
a = self.matrix[:, act[0]]
matrix[:, 0] = a
active[0] = True
if len(act) == 1:
# Add the new vector
matrix[:, 1] = vector
active[1] = True
return UnitCell(matrix, active)
b = self.matrix[:, act[1]]
matrix[:, 1] = b
active[1] = True
if len(act) == 2:
# Add the new vector
matrix[:, 2] = vector
active[2] = True
return UnitCell(matrix, active) |
<SYSTEM_TASK:>
Return ranges of indexes of the interacting neighboring unit cells
<END_TASK>
<USER_TASK:>
Description:
def get_radius_ranges(self, radius, mic=False):
"""Return ranges of indexes of the interacting neighboring unit cells
Interacting neighboring unit cells have at least one point in their
box volume that has a distance smaller or equal than radius to at
least one point in the central cell. This concept is of importance
when computing pair wise long-range interactions in periodic systems.
The mic (stands for minimum image convention) option can be used to
change the behavior of this routine such that only neighboring cells
are considered that have at least one point withing a distance below
`radius` from the center of the reference cell.
""" |
result = np.zeros(3, int)
for i in range(3):
if self.spacings[i] > 0:
if mic:
result[i] = np.ceil(radius/self.spacings[i]-0.5)
else:
result[i] = np.ceil(radius/self.spacings[i])
return result |
<SYSTEM_TASK:>
Return the indexes of the interacting neighboring unit cells
<END_TASK>
<USER_TASK:>
Description:
def get_radius_indexes(self, radius, max_ranges=None):
"""Return the indexes of the interacting neighboring unit cells
Interacting neighboring unit cells have at least one point in their
box volume that has a distance smaller or equal than radius to at
least one point in the central cell. This concept is of importance
when computing pair wise long-range interactions in periodic systems.
Argument:
| ``radius`` -- the radius of the interaction sphere
Optional argument:
| ``max_ranges`` -- numpy array with three elements: The maximum
ranges of indexes to consider. This is
practical when working with the minimum image
convention to reduce the generated bins to the
minimum image. (see binning.py) Use -1 to
avoid such limitations. The default is three
times -1.
""" |
if max_ranges is None:
max_ranges = np.array([-1, -1, -1])
ranges = self.get_radius_ranges(radius)*2+1
mask = (max_ranges != -1) & (max_ranges < ranges)
ranges[mask] = max_ranges[mask]
max_size = np.product(self.get_radius_ranges(radius)*2 + 1)
indexes = np.zeros((max_size, 3), int)
from molmod.ext import unit_cell_get_radius_indexes
reciprocal = self.reciprocal*self.active
matrix = self.matrix*self.active
size = unit_cell_get_radius_indexes(
matrix, reciprocal, radius, max_ranges, indexes
)
return indexes[:size] |
<SYSTEM_TASK:>
Construct a molecular geometry based on a molecular graph.
<END_TASK>
<USER_TASK:>
Description:
def guess_geometry(graph, unit_cell=None, verbose=False):
"""Construct a molecular geometry based on a molecular graph.
This routine does not require initial coordinates and will give a very
rough picture of the initial geometry. Do not expect all details to be
in perfect condition. A subsequent optimization with a more accurate
level of theory is at least advisable.
Argument:
| ``graph`` -- The molecular graph of the system, see
:class:molmod.molecular_graphs.MolecularGraph
Optional argument:
| ``unit_cell`` -- periodic boundry conditions, see
:class:`molmod.unit_cells.UnitCell`
| ``verbose`` -- Show optimizer progress when True
""" |
N = len(graph.numbers)
from molmod.minimizer import Minimizer, ConjugateGradient, \
NewtonLineSearch, ConvergenceCondition, StopLossCondition
search_direction = ConjugateGradient()
line_search = NewtonLineSearch()
convergence = ConvergenceCondition(grad_rms=1e-6, step_rms=1e-6)
stop_loss = StopLossCondition(max_iter=500, fun_margin=0.1)
ff = ToyFF(graph, unit_cell)
x_init = np.random.normal(0, 1, N*3)
# level 1 geometry optimization: graph based
ff.dm_quad = 1.0
minimizer = Minimizer(x_init, ff, search_direction, line_search, convergence, stop_loss, anagrad=True, verbose=verbose)
x_init = minimizer.x
# level 2 geometry optimization: graph based + pauli repulsion
ff.dm_quad = 1.0
ff.dm_reci = 1.0
minimizer = Minimizer(x_init, ff, search_direction, line_search, convergence, stop_loss, anagrad=True, verbose=verbose)
x_init = minimizer.x
# Add a little noise to avoid saddle points
x_init += np.random.uniform(-0.01, 0.01, len(x_init))
# level 3 geometry optimization: bond lengths + pauli
ff.dm_quad = 0.0
ff.dm_reci = 0.2
ff.bond_quad = 1.0
minimizer = Minimizer(x_init, ff, search_direction, line_search, convergence, stop_loss, anagrad=True, verbose=verbose)
x_init = minimizer.x
# level 4 geometry optimization: bond lengths + bending angles + pauli
ff.bond_quad = 0.0
ff.bond_hyper = 1.0
ff.span_quad = 1.0
minimizer = Minimizer(x_init, ff, search_direction, line_search, convergence, stop_loss, anagrad=True, verbose=verbose)
x_init = minimizer.x
x_opt = x_init
mol = Molecule(graph.numbers, x_opt.reshape((N, 3)))
return mol |
<SYSTEM_TASK:>
Compute the energy of the system
<END_TASK>
<USER_TASK:>
Description:
def energy(self):
"""Compute the energy of the system""" |
result = 0.0
for index1 in range(self.numc):
for index2 in range(index1):
if self.scaling[index1, index2] > 0:
for se, ve in self.yield_pair_energies(index1, index2):
result += se*ve*self.scaling[index1, index2]
return result |
<SYSTEM_TASK:>
Compute the gradient of the energy for one atom
<END_TASK>
<USER_TASK:>
Description:
def gradient_component(self, index1):
"""Compute the gradient of the energy for one atom""" |
result = np.zeros(3, float)
for index2 in range(self.numc):
if self.scaling[index1, index2] > 0:
for (se, ve), (sg, vg) in zip(self.yield_pair_energies(index1, index2), self.yield_pair_gradients(index1, index2)):
result += (sg*self.directions[index1, index2]*ve + se*vg)*self.scaling[index1, index2]
return result |
<SYSTEM_TASK:>
Compute the gradient of the energy for all atoms
<END_TASK>
<USER_TASK:>
Description:
def gradient(self):
"""Compute the gradient of the energy for all atoms""" |
result = np.zeros((self.numc, 3), float)
for index1 in range(self.numc):
result[index1] = self.gradient_component(index1)
return result |
<SYSTEM_TASK:>
Compute the hessian of the energy for one atom pair
<END_TASK>
<USER_TASK:>
Description:
def hessian_component(self, index1, index2):
"""Compute the hessian of the energy for one atom pair""" |
result = np.zeros((3, 3), float)
if index1 == index2:
for index3 in range(self.numc):
if self.scaling[index1, index3] > 0:
d_1 = 1/self.distances[index1, index3]
for (se, ve), (sg, vg), (sh, vh) in zip(
self.yield_pair_energies(index1, index3),
self.yield_pair_gradients(index1, index3),
self.yield_pair_hessians(index1, index3)
):
result += (
+sh*self.dirouters[index1, index3]*ve
+sg*(np.identity(3, float) - self.dirouters[index1, index3])*ve*d_1
+sg*np.outer(self.directions[index1, index3], vg)
+sg*np.outer(vg, self.directions[index1, index3])
+se*vh
)*self.scaling[index1, index3]
elif self.scaling[index1, index2] > 0:
d_1 = 1/self.distances[index1, index2]
for (se, ve), (sg, vg), (sh, vh) in zip(
self.yield_pair_energies(index1, index2),
self.yield_pair_gradients(index1, index2),
self.yield_pair_hessians(index1, index2)
):
result -= (
+sh*self.dirouters[index1, index2]*ve
+sg*(np.identity(3, float) - self.dirouters[index1, index2])*ve*d_1
+sg*np.outer(self.directions[index1, index2], vg)
+sg*np.outer(vg, self.directions[index1, index2])
+se*vh
)*self.scaling[index1, index2]
return result |
<SYSTEM_TASK:>
Compute the hessian of the energy
<END_TASK>
<USER_TASK:>
Description:
def hessian(self):
"""Compute the hessian of the energy""" |
result = np.zeros((self.numc, 3, self.numc, 3), float)
for index1 in range(self.numc):
for index2 in range(self.numc):
result[index1, :, index2, :] = self.hessian_component(index1, index2)
return result |
<SYSTEM_TASK:>
Load the molecules from a CML file
<END_TASK>
<USER_TASK:>
Description:
def load_cml(cml_filename):
"""Load the molecules from a CML file
Argument:
| ``cml_filename`` -- The filename of a CML file.
Returns a list of molecule objects with optional molecular graph
attribute and extra attributes.
""" |
parser = make_parser()
parser.setFeature(feature_namespaces, 0)
dh = CMLMoleculeLoader()
parser.setContentHandler(dh)
parser.parse(cml_filename)
return dh.molecules |
<SYSTEM_TASK:>
Dump a single molecule to a CML file
<END_TASK>
<USER_TASK:>
Description:
def _dump_cml_molecule(f, molecule):
"""Dump a single molecule to a CML file
Arguments:
| ``f`` -- a file-like object
| ``molecule`` -- a Molecule instance
""" |
extra = getattr(molecule, "extra", {})
attr_str = " ".join("%s='%s'" % (key, value) for key, value in extra.items())
f.write(" <molecule id='%s' %s>\n" % (molecule.title, attr_str))
f.write(" <atomArray>\n")
atoms_extra = getattr(molecule, "atoms_extra", {})
for counter, number, coordinate in zip(range(molecule.size), molecule.numbers, molecule.coordinates/angstrom):
atom_extra = atoms_extra.get(counter, {})
attr_str = " ".join("%s='%s'" % (key, value) for key, value in atom_extra.items())
f.write(" <atom id='a%i' elementType='%s' x3='%s' y3='%s' z3='%s' %s />\n" % (
counter, periodic[number].symbol, coordinate[0], coordinate[1],
coordinate[2], attr_str,
))
f.write(" </atomArray>\n")
if molecule.graph is not None:
bonds_extra = getattr(molecule, "bonds_extra", {})
f.write(" <bondArray>\n")
for edge in molecule.graph.edges:
bond_extra = bonds_extra.get(edge, {})
attr_str = " ".join("%s='%s'" % (key, value) for key, value in bond_extra.items())
i1, i2 = edge
f.write(" <bond atomRefs2='a%i a%i' %s />\n" % (i1, i2, attr_str))
f.write(" </bondArray>\n")
f.write(" </molecule>\n") |
<SYSTEM_TASK:>
Write a list of molecules to a CML file
<END_TASK>
<USER_TASK:>
Description:
def dump_cml(f, molecules):
"""Write a list of molecules to a CML file
Arguments:
| ``f`` -- a filename of a CML file or a file-like object
| ``molecules`` -- a list of molecule objects.
""" |
if isinstance(f, str):
f = open(f, "w")
close = True
else:
close = False
f.write("<?xml version='1.0'?>\n")
f.write("<list xmlns='http://www.xml-cml.org/schema'>\n")
for molecule in molecules:
_dump_cml_molecule(f, molecule)
f.write("</list>\n")
if close:
f.close() |
<SYSTEM_TASK:>
Read the extra properties, taking into account an exclude list
<END_TASK>
<USER_TASK:>
Description:
def _get_extra(self, attrs, exclude):
"""Read the extra properties, taking into account an exclude list""" |
result = {}
for key in attrs.getNames():
if key not in exclude:
result[str(key)] = str(attrs[key])
return result |
<SYSTEM_TASK:>
Read all the requested fields
<END_TASK>
<USER_TASK:>
Description:
def _read(self, filename, field_labels=None):
"""Read all the requested fields
Arguments:
| ``filename`` -- the filename of the FCHK file
| ``field_labels`` -- when given, only these fields are read
""" |
# if fields is None, all fields are read
def read_field(f):
"""Read a single field"""
datatype = None
while datatype is None:
# find a sane header line
line = f.readline()
if line == "":
return False
label = line[:43].strip()
if field_labels is not None:
if len(field_labels) == 0:
return False
elif label not in field_labels:
return True
else:
field_labels.discard(label)
line = line[43:]
words = line.split()
if len(words) == 0:
return True
if words[0] == 'I':
datatype = int
unreadable = 0
elif words[0] == 'R':
datatype = float
unreadable = np.nan
if len(words) == 2:
try:
value = datatype(words[1])
except ValueError:
return True
elif len(words) == 3:
if words[1] != "N=":
raise FileFormatError("Unexpected line in formatted checkpoint file %s\n%s" % (filename, line[:-1]))
length = int(words[2])
value = np.zeros(length, datatype)
counter = 0
try:
while counter < length:
line = f.readline()
if line == "":
raise FileFormatError("Unexpected end of formatted checkpoint file %s" % filename)
for word in line.split():
try:
value[counter] = datatype(word)
except (ValueError, OverflowError) as e:
print('WARNING: could not interpret word while reading %s: %s' % (word, self.filename))
if self.ignore_errors:
value[counter] = unreadable
else:
raise
counter += 1
except ValueError:
return True
else:
raise FileFormatError("Unexpected line in formatted checkpoint file %s\n%s" % (filename, line[:-1]))
self.fields[label] = value
return True
self.fields = {}
with open(filename, 'r') as f:
self.title = f.readline()[:-1].strip()
words = f.readline().split()
if len(words) == 3:
self.command, self.lot, self.basis = words
elif len(words) == 2:
self.command, self.lot = words
else:
raise FileFormatError('The second line of the FCHK file should contain two or three words.')
while read_field(f):
pass |
<SYSTEM_TASK:>
Convert a few elementary fields into a molecule object
<END_TASK>
<USER_TASK:>
Description:
def _analyze(self):
"""Convert a few elementary fields into a molecule object""" |
if ("Atomic numbers" in self.fields) and ("Current cartesian coordinates" in self.fields):
self.molecule = Molecule(
self.fields["Atomic numbers"],
np.reshape(self.fields["Current cartesian coordinates"], (-1, 3)),
self.title,
) |
<SYSTEM_TASK:>
Return the coordinates of the geometries at each point in the optimization
<END_TASK>
<USER_TASK:>
Description:
def get_optimization_coordinates(self):
"""Return the coordinates of the geometries at each point in the optimization""" |
coor_array = self.fields.get("Opt point 1 Geometries")
if coor_array is None:
return []
else:
return np.reshape(coor_array, (-1, len(self.molecule.numbers), 3)) |
<SYSTEM_TASK:>
Return a molecule object of the optimal geometry
<END_TASK>
<USER_TASK:>
Description:
def get_optimized_molecule(self):
"""Return a molecule object of the optimal geometry""" |
opt_coor = self.get_optimization_coordinates()
if len(opt_coor) == 0:
return None
else:
return Molecule(
self.molecule.numbers,
opt_coor[-1],
) |
<SYSTEM_TASK:>
Return the energy gradients of all geometries during an optimization
<END_TASK>
<USER_TASK:>
Description:
def get_optimization_gradients(self):
"""Return the energy gradients of all geometries during an optimization""" |
grad_array = self.fields.get("Opt point 1 Gradient at each geome")
if grad_array is None:
return []
else:
return np.reshape(grad_array, (-1, len(self.molecule.numbers), 3)) |
<SYSTEM_TASK:>
Internal routine that reads all data from the punch file.
<END_TASK>
<USER_TASK:>
Description:
def _read(self, filename):
"""Internal routine that reads all data from the punch file.""" |
data = {}
parsers = [
FirstDataParser(), CoordinateParser(), EnergyGradParser(),
SkipApproxHessian(), HessianParser(), MassParser(),
]
with open(filename) as f:
while True:
line = f.readline()
if line == "":
break
# at each line, a parsers checks if it has to process a piece of
# file. If that happens, the parser gets control over the file
# and reads as many lines as it needs to collect data for some
# attributes.
for parser in parsers:
if parser.test(line, data):
parser.read(line, f, data)
break
self.__dict__.update(data) |
<SYSTEM_TASK:>
Create a simple ForceField object for hydrocarbons based on the graph.
<END_TASK>
<USER_TASK:>
Description:
def setup_hydrocarbon_ff(graph):
"""Create a simple ForceField object for hydrocarbons based on the graph.""" |
# A) Define parameters.
# the bond parameters:
bond_params = {
(6, 1): 310*kcalmol/angstrom**2,
(6, 6): 220*kcalmol/angstrom**2,
}
# for every (a, b), also add (b, a)
for key, val in list(bond_params.items()):
if key[0] != key[1]:
bond_params[(key[1], key[0])] = val
# the bend parameters
bend_params = {
(1, 6, 1): 35*kcalmol/rad**2,
(1, 6, 6): 30*kcalmol/rad**2,
(6, 6, 6): 60*kcalmol/rad**2,
}
# for every (a, b, c), also add (c, b, a)
for key, val in list(bend_params.items()):
if key[0] != key[2]:
bend_params[(key[2], key[1], key[0])] = val
# B) detect all internal coordinates and corresponding energy terms.
terms = []
# bonds
for i0, i1 in graph.edges:
K = bond_params[(graph.numbers[i0], graph.numbers[i1])]
terms.append(BondStretchTerm(K, i0, i1))
# bends (see b_bending_angles.py for the explanation)
for i1 in range(graph.num_vertices):
n = list(graph.neighbors[i1])
for index, i0 in enumerate(n):
for i2 in n[:index]:
K = bend_params[(graph.numbers[i0], graph.numbers[i1], graph.numbers[i2])]
terms.append(BendAngleTerm(K, i0, i1, i2))
# C) Create and return the force field
return ForceField(terms) |
<SYSTEM_TASK:>
Add the contributions of this energy term to the Hessian
<END_TASK>
<USER_TASK:>
Description:
def add_to_hessian(self, coordinates, hessian):
"""Add the contributions of this energy term to the Hessian
Arguments:
| ``coordinates`` -- A numpy array with 3N Cartesian coordinates.
| ``hessian`` -- A matrix for the full Hessian to which this energy
term has to add its contribution.
""" |
# Compute the derivatives of the bond stretch towards the two cartesian
# coordinates. The bond length is computed too, but not used.
q, g = self.icfn(coordinates[list(self.indexes)], 1)
# Add the contribution to the Hessian (an outer product)
for ja, ia in enumerate(self.indexes):
# ja is 0, 1, 2, ...
# ia is i0, i1, i2, ...
for jb, ib in enumerate(self.indexes):
contrib = 2*self.force_constant*numpy.outer(g[ja], g[jb])
hessian[3*ia:3*ia+3, 3*ib:3*ib+3] += contrib |
<SYSTEM_TASK:>
Compute the force-field Hessian for the given coordinates.
<END_TASK>
<USER_TASK:>
Description:
def hessian(self, coordinates):
"""Compute the force-field Hessian for the given coordinates.
Argument:
| ``coordinates`` -- A numpy array with the Cartesian atom
coordinates, with shape (N,3).
Returns:
| ``hessian`` -- A numpy array with the Hessian, with shape (3*N,
3*N).
""" |
# N3 is 3 times the number of atoms.
N3 = coordinates.size
# Start with a zero hessian.
hessian = numpy.zeros((N3,N3), float)
# Add the contribution of each term.
for term in self.terms:
term.add_to_hessian(coordinates, hessian)
return hessian |
<SYSTEM_TASK:>
Compute the rotational symmetry number
<END_TASK>
<USER_TASK:>
Description:
def compute_rotsym(molecule, graph, threshold=1e-3*angstrom):
"""Compute the rotational symmetry number
Arguments:
| ``molecule`` -- The molecule
| ``graph`` -- The corresponding bond graph
Optional argument:
| ``threshold`` -- only when a rotation results in an rmsd below the
given threshold, the rotation is considered to
transform the molecule onto itself.
""" |
result = 0
for match in graph.symmetries:
permutation = list(j for i,j in sorted(match.forward.items()))
new_coordinates = molecule.coordinates[permutation]
rmsd = fit_rmsd(molecule.coordinates, new_coordinates)[2]
if rmsd < threshold:
result += 1
return result |
<SYSTEM_TASK:>
Return the quaternion product of the two arguments
<END_TASK>
<USER_TASK:>
Description:
def quaternion_product(quat1, quat2):
"""Return the quaternion product of the two arguments""" |
return np.array([
quat1[0]*quat2[0] - np.dot(quat1[1:], quat2[1:]),
quat1[0]*quat2[1] + quat2[0]*quat1[1] + quat1[2]*quat2[3] - quat1[3]*quat2[2],
quat1[0]*quat2[2] + quat2[0]*quat1[2] + quat1[3]*quat2[1] - quat1[1]*quat2[3],
quat1[0]*quat2[3] + quat2[0]*quat1[3] + quat1[1]*quat2[2] - quat1[2]*quat2[1]
], float) |
Subsets and Splits