sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
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
... | Click one grid by given position. | entailment |
def discover_region(self, move_x, move_y):
"""Discover region from given location."""
field_list = deque([(move_y, move_x)])
while len(field_list) != 0:
field = field_list.popleft()
(tl_idx, br_idx, region_sum) = self.get_region(field[1], field[0])
if region... | Discover region from given location. | entailment |
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]+... | Get region around a location. | entailment |
def flag_field(self, move_x, move_y):
"""Flag a grid by given position."""
field_status = self.info_map[move_y, move_x]
# a questioned or undiscovered field
if field_status != 9 and (field_status == 10 or field_status == 11):
self.info_map[move_y, move_x] = 9 | Flag a grid by given position. | entailment |
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 | Unflag or unquestion a grid by given position. | entailment |
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 | Question a grid by given position. | entailment |
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... | Check the board status and give feedback. | entailment |
def board_msg(self):
"""Structure a board as in print_board."""
board_str = "s\t\t"
for i in xrange(self.board_width):
board_str += str(i)+"\t"
board_str = board_str.expandtabs(4)+"\n\n"
for i in xrange(self.board_height):
temp_line = str(i)+"\t\t"
... | Structure a board as in print_board. | entailment |
def report_response(response,
request_headers=True, request_body=True,
response_headers=False, response_body=False,
redirection=False):
"""
生成响应报告
:param response: ``requests.models.Response`` 对象
:param request_headers: 是否加入请求头
:param requ... | 生成响应报告
:param response: ``requests.models.Response`` 对象
:param request_headers: 是否加入请求头
:param request_body: 是否加入请求体
:param response_headers: 是否加入响应头
:param response_body: 是否加入响应体
:param redirection: 是否加入重定向响应
:return: str | entailment |
def init_ui(self):
"""Setup control widget UI."""
self.control_layout = QHBoxLayout()
self.setLayout(self.control_layout)
self.reset_button = QPushButton()
self.reset_button.setFixedSize(40, 40)
self.reset_button.setIcon(QtGui.QIcon(WIN_PATH))
self.game_timer = QL... | Setup control widget UI. | entailment |
def init_ui(self):
"""Init game interface."""
board_width = self.ms_game.board_width
board_height = self.ms_game.board_height
self.create_grid(board_width, board_height)
self.time = 0
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.timing_game)
... | Init game interface. | entailment |
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()
... | Create a grid layout with stacked widgets.
Parameters
----------
grid_width : int
the width of the grid
grid_height : int
the height of the grid | entailment |
def timing_game(self):
"""Timing game."""
self.ctrl_wg.game_timer.display(self.time)
self.time += 1 | Timing game. | entailment |
def reset_game(self):
"""Reset game board."""
self.ms_game.reset_game()
self.update_grid()
self.time = 0
self.timer.start(1000) | Reset game board. | entailment |
def update_grid(self):
"""Update grid according to info map."""
info_map = self.ms_game.get_info_map()
for i in xrange(self.ms_game.board_height):
for j in xrange(self.ms_game.board_width):
self.grid_wgs[(i, j)].info_label(info_map[i, j])
self.ctrl_wg.move_co... | Update grid according to info map. | entailment |
def init_ui(self):
"""Init the ui."""
self.id = 11
self.setFixedSize(self.field_width, self.field_height)
self.setPixmap(QtGui.QPixmap(EMPTY_PATH).scaled(
self.field_width*3, self.field_height*3))
self.setStyleSheet("QLabel {background-color: blue;}") | Init the ui. | entailment |
def mousePressEvent(self, event):
"""Define mouse press event."""
if event.button() == QtCore.Qt.LeftButton:
# get label position
p_wg = self.parent()
p_layout = p_wg.layout()
idx = p_layout.indexOf(self)
loc = p_layout.getItemPosition(idx)[:2]... | Define mouse press event. | entailment |
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 ... | 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. | entailment |
def run(self):
"""Thread behavior."""
self.ms_game.tcp_accept()
while True:
data = self.ms_game.tcp_receive()
if data == "help\n":
self.ms_game.tcp_help()
self.ms_game.tcp_send("> ")
elif data == "exit\n":
self... | Thread behavior. | entailment |
def options(self, parser, env):
"""Register commandline options.
"""
parser.add_option(
"--epdb", action="store_true", dest="epdb_debugErrors",
default=env.get('NOSE_EPDB', False),
help="Drop into extended debugger on errors")
parser.add_option(
... | Register commandline options. | entailment |
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.epd... | Configure which kinds of exceptions trigger plugin. | entailment |
def set_trace_cond(*args, **kw):
""" Sets a condition for set_trace statements that have the
specified marker. A condition can either callable, in
which case it should take one argument, which is the
number of times set_trace(marker) has been called,
or it can be a number, in which ... | Sets a condition for set_trace statements that have the
specified marker. A condition can either callable, in
which case it should take one argument, which is the
number of times set_trace(marker) has been called,
or it can be a number, in which case the break will
only be calle... | entailment |
def matchFileOnDirPath(curpath, pathdir):
"""Find match for a file by slicing away its directory elements
from the front and replacing them with pathdir. Assume that the
end of curpath is right and but that the beginning may contain
some garbage (or it may be short)
Overlaps are allowed... | Find match for a file by slicing away its directory elements
from the front and replacing them with pathdir. Assume that the
end of curpath is right and but that the beginning may contain
some garbage (or it may be short)
Overlaps are allowed:
e.g /tmp/fdjsklf/real/path/elements, /al... | entailment |
def lookupmodule(self, filename):
"""Helper function for break/clear parsing -- may be overridden.
lookupmodule() translates (possibly incomplete) file or module name
into an absolute file name.
"""
if os.path.isabs(filename) and os.path.exists(filename):
return file... | Helper function for break/clear parsing -- may be overridden.
lookupmodule() translates (possibly incomplete) file or module name
into an absolute file name. | entailment |
def set_trace_cond(klass, marker='default', cond=None):
""" Sets a condition for set_trace statements that have the
specified marker. A condition can be either callable, in
which case it should take one argument, which is the
number of times set_trace(marker) has been called... | Sets a condition for set_trace statements that have the
specified marker. A condition can be either callable, in
which case it should take one argument, which is the
number of times set_trace(marker) has been called,
or it can be a number, in which case the break will
... | entailment |
def _set_trace(self, skip=0):
"""Start debugging from here."""
frame = sys._getframe().f_back
# go up the specified number of frames
for i in range(skip):
frame = frame.f_back
self.reset()
while frame:
frame.f_trace = self.trace_dispatch
... | Start debugging from here. | entailment |
def user_call(self, frame, argument_list):
"""This method is called when there is the remote possibility
that we ever need to stop in this function."""
if self.stop_here(frame):
pdb.Pdb.user_call(self, frame, argument_list) | This method is called when there is the remote possibility
that we ever need to stop in this function. | entailment |
def user_return(self, frame, return_value):
"""This function is called when a return trap is set here."""
pdb.Pdb.user_return(self, frame, return_value) | This function is called when a return trap is set here. | entailment |
def user_exception(self, frame, exc_info):
"""This function is called if an exception occurs,
but only if we are to stop at or just below this level."""
pdb.Pdb.user_exception(self, frame, exc_info) | This function is called if an exception occurs,
but only if we are to stop at or just below this level. | entailment |
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)
st... | Convert a chain of traceback or frame objects into a list of frames. | entailment |
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 WI... | 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. | entailment |
def handle(self):
"""
Performs endless processing of socket input/output, passing
cooked information onto the local process.
"""
while True:
toRead = select.select([self.local, self.remote], [], [], 0.1)[0]
if self.local in toRead:
... | Performs endless processing of socket input/output, passing
cooked information onto the local process. | entailment |
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, f... | Creates a child process that is fully controlled by this
request handler, and serves data to and from it via the
protocol handler. | entailment |
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.v... | Handle one request - serve current process to one connection.
Use close_request() to disconnect this process. | entailment |
def _serve_process(self, slaveFd, serverPid):
"""
Serves a process by connecting its outputs/inputs to the pty
slaveFd. serverPid is the process controlling the master fd
that passes that output over the socket.
"""
self.serverPid = serverPid
if sys.s... | Serves a process by connecting its outputs/inputs to the pty
slaveFd. serverPid is the process controlling the master fd
that passes that output over the socket. | entailment |
def int_input(message, low, high, show_range = True):
'''
Ask a user for a int input between two values
args:
message (str): Prompt for user
low (int): Low value, user entered value must be > this value to be accepted
high (int): High value, user entered value must be < this value t... | Ask a user for a int input between two values
args:
message (str): Prompt for user
low (int): Low value, user entered value must be > this value to be accepted
high (int): High value, user entered value must be < this value to be accepted
show_range (boolean, Default True): Print hi... | entailment |
def float_input(message, low, high):
'''
Ask a user for a float input between two values
args:
message (str): Prompt for user
low (float): Low value, user entered value must be > this value to be accepted
high (float): High value, user entered value must be < this value to be accept... | Ask a user for a float input between two values
args:
message (str): Prompt for user
low (float): Low value, user entered value must be > this value to be accepted
high (float): High value, user entered value must be < this value to be accepted
returns:
float_in (int): Input fl... | entailment |
def bool_input(message):
'''
Ask a user for a boolean input
args:
message (str): Prompt for user
returns:
bool_in (boolean): Input boolean
'''
while True:
suffix = ' (true or false): '
inp = input(message + suffix)
if inp.lower() == 'true':
... | Ask a user for a boolean input
args:
message (str): Prompt for user
returns:
bool_in (boolean): Input boolean | entailment |
def main(args = None):
'''
Main entry point for transfer command line tool.
This essentially will marshall the user to the functions they need.
'''
parser = argparse.ArgumentParser(description = 'Tool to perform transfer learning')
parser.add_argument('-c','--configure',
... | Main entry point for transfer command line tool.
This essentially will marshall the user to the functions they need. | entailment |
def configure():
'''
Configure the transfer environment and store
'''
completer = Completer()
readline.set_completer_delims('\t')
readline.parse_and_bind('tab: complete')
readline.set_completer(completer.path_completer)
home = os.path.expanduser('~')
if os.path.isfile(os.path.join(h... | Configure the transfer environment and store | entailment |
def configure_server():
'''
Configure the transfer environment and store
'''
home = os.path.expanduser('~')
if os.path.isfile(os.path.join(home, '.transfer', 'config.yaml')):
with open(os.path.join(home, '.transfer', 'config.yaml'), 'r') as fp:
config = yaml.load(fp.read())
... | Configure the transfer environment and store | entailment |
def select_project(user_provided_project):
'''
Select a project from configuration to run transfer on
args:
user_provided_project (str): Project name that should match a project in the config
returns:
project (dict): Configuration settings for a user selected project
'''
home... | Select a project from configuration to run transfer on
args:
user_provided_project (str): Project name that should match a project in the config
returns:
project (dict): Configuration settings for a user selected project | entailment |
def store_config(config, suffix = None):
'''
Store configuration
args:
config (list[dict]): configurations for each project
'''
home = os.path.expanduser('~')
if suffix is not None:
config_path = os.path.join(home, '.transfer', suffix)
else:
config_path = os.path.joi... | Store configuration
args:
config (list[dict]): configurations for each project | entailment |
def update_config(updated_project):
'''
Update project in configuration
args:
updated_project (dict): Updated project configuration values
'''
home = os.path.expanduser('~')
if os.path.isfile(os.path.join(home, '.transfer', 'config.yaml')):
with open(os.path.join(home, '.trans... | Update project in configuration
args:
updated_project (dict): Updated project configuration values | entailment |
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:
resu... | An auxiliary function to construct a dictionary of Criteria | entailment |
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.")... | the size must be the same as the length of the array numbers and all elements must be strings | entailment |
def from_geometry(cls, molecule, do_orders=False, scaling=1.0):
"""Construct a MolecularGraph object based on interatomic distances
All short distances are computed with the binning module and compared
with a database of bond lengths. Based on this comparison, bonded
atoms are ... | Construct a MolecularGraph object based on interatomic distances
All short distances are computed with the binning module and compared
with a database of bond lengths. Based on this comparison, bonded
atoms are detected.
Before marking a pair of atoms A and B as bonded, it ... | entailment |
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.spl... | Construct a molecular graph from the blob representation | entailment |
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) | A compact text representation of the graph | entailment |
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 "%03... | Return a string based on the atom number | entailment |
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" % ord... | Return a string based on the bond order | entailment |
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.number... | Creates a subgraph of the current graph
See :meth:`molmod.graphs.Graph.get_subgraph` for more information. | entailment |
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 nu... | 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 gr... | entailment |
def check_next_match(self, match, new_relations, subject_graph, one_match):
"""Check if the (onset for a) match can be a valid (part of a) ring"""
if not CustomPattern.check_next_match(self, match, new_relations, subject_graph, one_match):
return False
if self.strong:
# c... | Check if the (onset for a) match can be a valid (part of a) ring | entailment |
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:
# ... | Check the completeness of the ring match | entailment |
def get_kind(self, value):
"""Return the kind (type) of the attribute"""
if isinstance(value, float):
return 'f'
elif isinstance(value, int):
return 'i'
else:
raise ValueError("Only integer or floating point values can be stored.") | Return the kind (type) of the attribute | entailment |
def dump(self, f, name):
"""Write the attribute to a file-like object"""
# print the header line
value = self.get()
kind = self.get_kind(value)
print("% 40s kind=%s value=%s" % (name, kind, value), file=f) | Write the attribute to a file-like object | entailment |
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 | Return the value of the attribute | entailment |
def dump(self, f, name):
"""Write the attribute to a file-like object"""
array = self.get()
# print the header line
print("% 40s kind=%s shape=(%s)" % (
name,
array.dtype.kind,
",".join([str(int(size_axis)) for size_axis in array.shape]),
), ... | Write the attribute to a file-like object | entailment |
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 ... | Load the array data from a file-like object | entailment |
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, StateAtt... | 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 | entailment |
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... | 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 | entailment |
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 lis... | 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
... | entailment |
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) | Dump the registered fields to a file
Argument:
| ``filename`` -- the file to write to | entailment |
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 give... | 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. | entailment |
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_leng... | 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 ..."
... | entailment |
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 ... | Completes the bond length database with approximations based on VDW radii | entailment |
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
... | 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... | entailment |
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 argume... | 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=B... | entailment |
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 vect... | 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. | entailment |
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 parall... | 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_acti... | entailment |
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_i... | The indexes of the active and the inactive cell vectors | entailment |
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 l... | 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... | entailment |
def parameters(self):
"""The cell parameters (lengths and angles)"""
length_a = np.linalg.norm(self.matrix[:, 0])
length_b = np.linalg.norm(self.matrix[:, 1])
length_c = np.linalg.norm(self.matrix[:, 2])
alpha = np.arccos(np.dot(self.matrix[:, 1], self.matrix[:, 2]) / (length_b *... | The cell parameters (lengths and angles) | entailment |
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]) | An equivalent unit cell with the active cell vectors coming first | entailment |
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 Rot... | 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 | entailment |
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 | Computes the distances between neighboring crystal planes | entailment |
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(... | Returns a new unit cell with an additional cell vector | entailment |
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 cen... | 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 co... | entailment |
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 ce... | 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 computin... | entailment |
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 subseque... | 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... | entailment |
def tune_geometry(graph, mol, unit_cell=None, verbose=False):
"""Fine tune a molecular geometry, starting from a (very) poor guess 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... | Fine tune a molecular geometry, starting from a (very) poor guess 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.
Arguments:
| ``graph`` -- The molecular graph of ... | entailment |
def update_coordinates(self, coordinates=None):
"""Update the coordinates (and derived quantities)
Argument:
coordinates -- new Cartesian coordinates of the system
"""
if coordinates is not None:
self.coordinates = coordinates
self.numc = len(self.c... | Update the coordinates (and derived quantities)
Argument:
coordinates -- new Cartesian coordinates of the system | entailment |
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):
... | Compute the energy of the system | entailment |
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.yi... | Compute the gradient of the energy for one atom | entailment |
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 | Compute the gradient of the energy for all atoms | entailment |
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... | Compute the hessian of the energy for one atom pair | entailment |
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 resul... | Compute the hessian of the energy | entailment |
def yield_pair_energies(self, index1, index2):
"""Yields pairs ((s(r_ij), v(bar{r}_ij))"""
d_1 = 1/self.distances[index1, index2]
if self.charges is not None:
c1 = self.charges[index1]
c2 = self.charges[index2]
yield c1*c2*d_1, 1
if self.dipoles is not... | Yields pairs ((s(r_ij), v(bar{r}_ij)) | entailment |
def yield_pair_gradients(self, index1, index2):
"""Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij))"""
d_2 = 1/self.distances[index1, index2]**2
if self.charges is not None:
c1 = self.charges[index1]
c2 = self.charges[index2]
yield -c1*c2*d_2, np.zeros(3)
... | Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij)) | entailment |
def yield_pair_hessians(self, index1, index2):
"""Yields pairs ((s''(r_ij), grad_i (x) grad_i v(bar{r}_ij))"""
d_1 = 1/self.distances[index1, index2]
d_3 = d_1**3
if self.charges is not None:
c1 = self.charges[index1]
c2 = self.charges[index2]
yield 2*... | Yields pairs ((s''(r_ij), grad_i (x) grad_i v(bar{r}_ij)) | entailment |
def esp(self):
"""Compute the electrostatic potential at each atom due to other atoms"""
result = np.zeros(self.numc, float)
for index1 in range(self.numc):
result[index1] = self.esp_component(index1)
return result | Compute the electrostatic potential at each atom due to other atoms | entailment |
def efield(self):
"""Compute the electrostatic potential at each atom due to other atoms"""
result = np.zeros((self.numc,3), float)
for index1 in range(self.numc):
result[index1] = self.efield_component(index1)
return result | Compute the electrostatic potential at each atom due to other atoms | entailment |
def yield_pair_energies(self, index1, index2):
"""Yields pairs ((s(r_ij), v(bar{r}_ij))"""
strength = self.strengths[index1, index2]
distance = self.distances[index1, index2]
yield strength*distance**(-6), 1 | Yields pairs ((s(r_ij), v(bar{r}_ij)) | entailment |
def yield_pair_gradients(self, index1, index2):
"""Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij))"""
strength = self.strengths[index1, index2]
distance = self.distances[index1, index2]
yield -6*strength*distance**(-7), np.zeros(3) | Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij)) | entailment |
def yield_pair_energies(self, index1, index2):
"""Yields pairs ((s(r_ij), v(bar{r}_ij))"""
A = self.As[index1, index2]
B = self.Bs[index1, index2]
distance = self.distances[index1, index2]
yield A*np.exp(-B*distance), 1 | Yields pairs ((s(r_ij), v(bar{r}_ij)) | entailment |
def yield_pair_gradients(self, index1, index2):
"""Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij))"""
A = self.As[index1, index2]
B = self.Bs[index1, index2]
distance = self.distances[index1, index2]
yield -B*A*np.exp(-B*distance), np.zeros(3) | Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij)) | entailment |
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(fea... | 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. | entailment |
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())... | Dump a single molecule to a CML file
Arguments:
| ``f`` -- a file-like object
| ``molecule`` -- a Molecule instance | entailment |
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:
cl... | 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. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.