text_prompt
stringlengths 157
13.1k
| code_prompt
stringlengths 7
19.8k
⌀ |
---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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;}") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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]
if p_wg.ms_game.game_status == 2:
p_wg.ms_game.play_move("click", loc[1], loc[0])
p_wg.update_grid()
elif event.button() == QtCore.Qt.RightButton:
p_wg = self.parent()
p_layout = p_wg.layout()
idx = p_layout.indexOf(self)
loc = p_layout.getItemPosition(idx)[:2]
if p_wg.ms_game.game_status == 2:
if self.id == 9:
self.info_label(10)
p_wg.ms_game.play_move("question", loc[1], loc[0])
p_wg.update_grid()
elif self.id == 11:
self.info_label(9)
p_wg.ms_game.play_move("flag", loc[1], loc[0])
p_wg.update_grid()
elif self.id == 10:
self.info_label(11)
p_wg.ms_game.play_move("unflag", loc[1], loc[0])
p_wg.update_grid() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.ms_game.tcp_close()
elif data == "print\n":
self.ms_game.tcp_send(self.ms_game.get_board())
self.ms_game.tcp_send("> ")
elif data == "":
self.ms_game.tcp_send("> ")
else:
self.transfer.emit(data)
self.ms_game.tcp_send("> ")
if self.ms_game.game_status == 1:
self.ms_game.tcp_send("[MESSAGE] YOU WIN!\n")
self.ms_game.tcp_close()
elif self.ms_game.game_status == 0:
self.ms_game.tcp_send("[MESSAGE] YOU LOSE!\n")
self.ms_game.tcp_close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
self.botframe = frame
frame = frame.f_back
self.set_step()
sys.settrace(self.trace_dispatch) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 to be accepted
show_range (boolean, Default True): Print hint to user the range
returns:
int_in (int): Input integer
'''
int_in = low - 1
while (int_in < low) or (int_in > high):
if show_range:
suffix = ' (integer between ' + str(low) + ' and ' + str(high) + ')'
else:
suffix = ''
inp = input('Enter a ' + message + suffix + ': ')
if re.match('^-?[0-9]+$', inp) is not None:
int_in = int(inp)
else:
print(colored('Must be an integer, try again!', 'red'))
return int_in |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 accepted
returns:
float_in (int): Input float
'''
float_in = low - 1.0
while (float_in < low) or (float_in > high):
inp = input('Enter a ' + message + ' (float between ' + str(low) + ' and ' + str(high) + '): ')
if re.match('^([0-9]*[.])?[0-9]+$', inp) is not None:
float_in = float(inp)
else:
print(colored('Must be a float, try again!', 'red'))
return float_in |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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':
return True
elif inp.lower() == 'false':
return False
else:
print(colored('Must be either true or false, try again!', 'red')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 = 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:
projects = yaml.load(fp.read())
if len(projects) == 1:
project = projects[0]
else:
if user_provided_project in [project['name'] for project in projects]:
for inner_project in projects:
if user_provided_project == inner_project['name']:
project = inner_project
else:
print('Select your project')
for i, project in enumerate(projects):
print('[' + str(i) + ']: ' + project['name'])
project_index = int_input('project', -1, len(projects), show_range = False)
project = projects[project_index]
else:
print('Transfer is not configured.')
print('Please run:')
print('')
print(colored(' transfer --configure', 'green'))
return
print(colored('Project selected: ' + project['name'], 'cyan'))
return project |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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, '.transfer', 'config.yaml'), 'r') as fp:
projects = yaml.load(fp.read())
replace_index = -1
for i, project in enumerate(projects):
if project['name'] == updated_project['name']:
replace_index = i
if replace_index > -1:
projects[replace_index] = updated_project
store_config(projects)
else:
print('Not saving configuration')
print(colored('Project: ' + updated_project['name'] + ' was not found in configured projects!', 'red'))
else:
print('Transfer is not configured.')
print('Please run:')
print('')
print(colored(' transfer --configure', 'cyan'))
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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: """ |
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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_hessian(self):
"""Return the hessian""" |
force_const = self.fields.get("Cartesian Force Constants")
if force_const is None:
return None
N = len(self.molecule.numbers)
result = np.zeros((3*N, 3*N), float)
counter = 0
for row in range(3*N):
result[row, :row+1] = force_const[counter:counter+row+1]
result[:row+1, row] = force_const[counter:counter+row+1]
counter += row + 1
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def quaternion_rotation(quat, vector):
"""Apply the rotation represented by the quaternion to the vector Warning: This only works correctly for normalized quaternions. """ |
dp = np.dot(quat[1:], vector)
cos = (2*quat[0]*quat[0] - 1)
return np.array([
2 * (quat[0] * (quat[2] * vector[2] - quat[3] * vector[1]) + quat[1] * dp) + cos * vector[0],
2 * (quat[0] * (quat[3] * vector[0] - quat[1] * vector[2]) + quat[2] * dp) + cos * vector[1],
2 * (quat[0] * (quat[1] * vector[1] - quat[2] * vector[0]) + quat[3] * dp) + cos * vector[2]
], float) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rotation_matrix_to_quaternion(rotation_matrix):
"""Compute the quaternion representing the rotation given by the matrix""" |
invert = (np.linalg.det(rotation_matrix) < 0)
if invert:
factor = -1
else:
factor = 1
c2 = 0.25*(factor*np.trace(rotation_matrix) + 1)
if c2 < 0:
#print c2
c2 = 0.0
c = np.sqrt(c2)
r2 = 0.5*(1 + factor*np.diagonal(rotation_matrix)) - c2
#print "check", r2.sum()+c2
r = np.zeros(3, float)
for index, r2_comp in enumerate(r2):
if r2_comp < 0:
continue
else:
row, col = off_diagonals[index]
if (rotation_matrix[row, col] - rotation_matrix[col, row] < 0):
r[index] = -np.sqrt(r2_comp)
else:
r[index] = +np.sqrt(r2_comp)
return factor, np.array([c, r[0], r[1], r[2]], float) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def quaternion_to_rotation_matrix(quaternion):
"""Compute the rotation matrix representated by the quaternion""" |
c, x, y, z = quaternion
return np.array([
[c*c + x*x - y*y - z*z, 2*x*y - 2*c*z, 2*x*z + 2*c*y ],
[2*x*y + 2*c*z, c*c - x*x + y*y - z*z, 2*y*z - 2*c*x ],
[2*x*z - 2*c*y, 2*y*z + 2*c*x, c*c - x*x - y*y + z*z]
], float) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cosine(a, b):
"""Compute the cosine between two vectors The result is clipped within the range [-1, 1] """ |
result = np.dot(a, b) / np.linalg.norm(a) / np.linalg.norm(b)
return np.clip(result, -1, 1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_unit(size=3):
"""Return a random unit vector of the given dimension Optional argument: size -- the number of dimensions of the unit vector [default=3] """ |
while True:
result = np.random.normal(0, 1, size)
length = np.linalg.norm(result)
if length > 1e-3:
return result/length |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_orthonormal(normal):
"""Return a random normalized vector orthogonal to the given vector""" |
u = normal_fns[np.argmin(np.fabs(normal))](normal)
u /= np.linalg.norm(u)
v = np.cross(normal, u)
v /= np.linalg.norm(v)
alpha = np.random.uniform(0.0, np.pi*2)
return np.cos(alpha)*u + np.sin(alpha)*v |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def triangle_normal(a, b, c):
"""Return a vector orthogonal to the given triangle Arguments: a, b, c -- three 3D numpy vectors """ |
normal = np.cross(a - c, b - c)
norm = np.linalg.norm(normal)
return normal/norm |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dot(r1, r2):
"""Compute the dot product Arguments: | ``r1``, ``r2`` -- two :class:`Vector3` objects (Returns a Scalar) """ |
if r1.size != r2.size:
raise ValueError("Both arguments must have the same input size.")
if r1.deriv != r2.deriv:
raise ValueError("Both arguments must have the same deriv.")
return r1.x*r2.x + r1.y*r2.y + r1.z*r2.z |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cross(r1, r2):
"""Compute the cross product Arguments: | ``r1``, ``r2`` -- two :class:`Vector3` objects (Returns a Vector3) """ |
if r1.size != r2.size:
raise ValueError("Both arguments must have the same input size.")
if r1.deriv != r2.deriv:
raise ValueError("Both arguments must have the same deriv.")
result = Vector3(r1.size, r1.deriv)
result.x = r1.y*r2.z - r1.z*r2.y
result.y = r1.z*r2.x - r1.x*r2.z
result.z = r1.x*r2.y - r1.y*r2.x
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bond_length_low(r, deriv):
"""Similar to bond_length, but with a relative vector""" |
r = Vector3(3, deriv, r, (0, 1, 2))
d = r.norm()
return d.results() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bend_cos_low(a, b, deriv):
"""Similar to bend_cos, but with relative vectors""" |
a = Vector3(6, deriv, a, (0, 1, 2))
b = Vector3(6, deriv, b, (3, 4, 5))
a /= a.norm()
b /= b.norm()
return dot(a, b).results() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bend_angle_low(a, b, deriv):
"""Similar to bend_angle, but with relative vectors""" |
result = _bend_cos_low(a, b, deriv)
return _cos_to_angle(result, deriv) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _opdist_low(av, bv, cv, deriv):
"""Similar to opdist, but with relative vectors""" |
a = Vector3(9, deriv, av, (0, 1, 2))
b = Vector3(9, deriv, bv, (3, 4, 5))
c = Vector3(9, deriv, cv, (6, 7, 8))
n = cross(a, b)
n /= n.norm()
dist = dot(c, n)
return dist.results() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _opbend_cos_low(a, b, c, deriv):
"""Similar to opbend_cos, but with relative vectors""" |
a = Vector3(9, deriv, a, (0, 1, 2))
b = Vector3(9, deriv, b, (3, 4, 5))
c = Vector3(9, deriv, c, (6, 7, 8))
n = cross(a,b)
n /= n.norm()
c /= c.norm()
temp = dot(n,c)
result = temp.copy()
result.v = np.sqrt(1.0-temp.v**2)
if result.deriv > 0:
result.d *= -temp.v
result.d /= result.v
if result.deriv > 1:
result.dd *= -temp.v
result.dd /= result.v
temp2 = np.array([temp.d]).transpose()*temp.d
temp2 /= result.v**3
result.dd -= temp2
return result.results() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _opbend_angle_low(a, b, c, deriv=0):
"""Similar to opbend_angle, but with relative vectors""" |
result = _opbend_cos_low(a, b, c, deriv)
sign = np.sign(np.linalg.det([a, b, c]))
return _cos_to_angle(result, deriv, sign) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cos_to_angle(result, deriv, sign=1):
"""Convert a cosine and its derivatives to an angle and its derivatives""" |
v = np.arccos(np.clip(result[0], -1, 1))
if deriv == 0:
return v*sign,
if abs(result[0]) >= 1:
factor1 = 0
else:
factor1 = -1.0/np.sqrt(1-result[0]**2)
d = factor1*result[1]
if deriv == 1:
return v*sign, d*sign
factor2 = result[0]*factor1**3
dd = factor2*np.outer(result[1], result[1]) + factor1*result[2]
if deriv == 2:
return v*sign, d*sign, dd*sign
raise ValueError("deriv must be 0, 1 or 2.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _sin_to_angle(result, deriv, side=1):
"""Convert a sine and its derivatives to an angle and its derivatives""" |
v = np.arcsin(np.clip(result[0], -1, 1))
sign = side
if sign == -1:
if v < 0:
offset = -np.pi
else:
offset = np.pi
else:
offset = 0.0
if deriv == 0:
return v*sign + offset,
if abs(result[0]) >= 1:
factor1 = 0
else:
factor1 = 1.0/np.sqrt(1-result[0]**2)
d = factor1*result[1]
if deriv == 1:
return v*sign + offset, d*sign
factor2 = result[0]*factor1**3
dd = factor2*np.outer(result[1], result[1]) + factor1*result[2]
if deriv == 2:
return v*sign + offset, d*sign, dd*sign
raise ValueError("deriv must be 0, 1 or 2.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def results(self):
"""Return the value and optionally derivative and second order derivative""" |
if self.deriv == 0:
return self.v,
if self.deriv == 1:
return self.v, self.d
if self.deriv == 2:
return self.v, self.d, self.dd |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inv(self):
"""In place invert""" |
self.v = 1/self.v
tmp = self.v**2
if self.deriv > 1:
self.dd[:] = tmp*(2*self.v*np.outer(self.d, self.d) - self.dd)
if self.deriv > 0:
self.d[:] = -tmp*self.d[:] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def norm(self):
"""Return a Scalar object with the norm of this vector""" |
result = Scalar(self.size, self.deriv)
result.v = np.sqrt(self.x.v**2 + self.y.v**2 + self.z.v**2)
if self.deriv > 0:
result.d += self.x.v*self.x.d
result.d += self.y.v*self.y.d
result.d += self.z.v*self.z.d
result.d /= result.v
if self.deriv > 1:
result.dd += self.x.v*self.x.dd
result.dd += self.y.v*self.y.dd
result.dd += self.z.v*self.z.dd
denom = result.v**2
result.dd += (1 - self.x.v**2/denom)*np.outer(self.x.d, self.x.d)
result.dd += (1 - self.y.v**2/denom)*np.outer(self.y.d, self.y.d)
result.dd += (1 - self.z.v**2/denom)*np.outer(self.z.d, self.z.d)
tmp = -self.x.v*self.y.v/denom*np.outer(self.x.d, self.y.d)
result.dd += tmp+tmp.transpose()
tmp = -self.y.v*self.z.v/denom*np.outer(self.y.d, self.z.d)
result.dd += tmp+tmp.transpose()
tmp = -self.z.v*self.x.v/denom*np.outer(self.z.d, self.x.d)
result.dd += tmp+tmp.transpose()
result.dd /= result.v
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_line(self):
"""Get a line or raise StopIteration""" |
line = self._f.readline()
if len(line) == 0:
raise StopIteration
return line |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_frame(self):
"""Read one frame""" |
# Read the first line, ignore the title and try to get the time. The
# time field is optional.
line = self._get_line()
pos = line.rfind("t=")
if pos >= 0:
time = float(line[pos+2:])*picosecond
else:
time = 0.0
# Read the second line, the number of atoms must match with the first
# frame.
num_atoms = int(self._get_line())
if self.num_atoms is not None and self.num_atoms != num_atoms:
raise ValueError("The number of atoms must be the same over the entire file.")
# Read the atom lines
pos = np.zeros((num_atoms, 3), np.float32)
vel = np.zeros((num_atoms, 3), np.float32)
for i in range(num_atoms):
words = self._get_line()[22:].split()
pos[i, 0] = float(words[0])
pos[i, 1] = float(words[1])
pos[i, 2] = float(words[2])
vel[i, 0] = float(words[3])
vel[i, 1] = float(words[4])
vel[i, 2] = float(words[5])
pos *= nanometer
vel *= nanometer/picosecond
# Read the cell line
cell = np.zeros((3, 3), np.float32)
words = self._get_line().split()
if len(words) >= 3:
cell[0, 0] = float(words[0])
cell[1, 1] = float(words[1])
cell[2, 2] = float(words[2])
if len(words) == 9:
cell[1, 0] = float(words[3])
cell[2, 0] = float(words[4])
cell[0, 1] = float(words[5])
cell[2, 1] = float(words[6])
cell[0, 2] = float(words[7])
cell[1, 2] = float(words[8])
cell *= nanometer
return time, pos, vel, cell |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _skip_frame(self):
"""Skip one frame""" |
self._get_line()
num_atoms = int(self._get_line())
if self.num_atoms is not None and self.num_atoms != num_atoms:
raise ValueError("The number of atoms must be the same over the entire file.")
for i in range(num_atoms+1):
self._get_line() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_ics(graph):
"""Make a list of internal coordinates based on the graph Argument: | ``graph`` -- A Graph instance. The list of internal coordinates will include all bond lengths, all bending angles, and all dihedral angles. """ |
ics = []
# A) Collect all bonds.
for i0, i1 in graph.edges:
ics.append(BondLength(i0, i1))
# B) Collect all 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]:
ics.append(BendingAngle(i0, i1, i2))
# C) Collect all dihedrals.
for i1, i2 in graph.edges:
for i0 in graph.neighbors[i1]:
if i0==i2:
# All four indexes must be different.
continue
for i3 in graph.neighbors[i2]:
if i3==i1 or i3==i0:
# All four indexes must be different.
continue
ics.append(DihedralAngle(i0, i1, i2, i3))
return ics |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_jacobian(ics, coordinates):
"""Construct a Jacobian for the given internal and Cartesian coordinates Arguments: | ``ics`` -- A list of internal coordinate objects. | ``coordinates`` -- A numpy array with Cartesian coordinates, shape=(N,3) The return value will be a numpy array with the Jacobian matrix. There will be a column for each internal coordinate, and a row for each Cartesian coordinate (3*N rows). """ |
N3 = coordinates.size
jacobian = numpy.zeros((N3, len(ics)), float)
for j, ic in enumerate(ics):
# Let the ic object fill in each column of the Jacobian.
ic.fill_jacobian_column(jacobian[:,j], coordinates)
return jacobian |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fill_jacobian_column(self, jaccol, coordinates):
"""Fill in a column of the Jacobian. Arguments: | ``jaccol`` -- The column of Jacobian to which the result must be added. | ``coordinates`` -- A numpy array with Cartesian coordinates, shape=(N,3) """ |
q, g = self.icfn(coordinates[list(self.indexes)], 1)
for i, j in enumerate(self.indexes):
jaccol[3*j:3*j+3] += g[i]
return jaccol |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_similarity(a, b, margin=1.0, cutoff=10.0):
"""Compute the similarity between two molecules based on their descriptors Arguments: a -- the similarity measure of the first molecule b -- the similarity measure of the second molecule margin -- the sensitivity when comparing distances (default = 1.0) cutoff -- don't compare distances longer than the cutoff (default = 10.0 au) When comparing two distances (always between two atom pairs with identical labels), the folowing formula is used: dav = (distance1+distance2)/2 delta = abs(distance1-distance2) When the delta is within the margin and dav is below the cutoff: (1-dav/cutoff)*(cos(delta/margin/np.pi)+1)/2 and zero otherwise. The returned value is the sum of such terms over all distance pairs with matching atom types. When comparing similarities it might be useful to normalize them in some way, e.g. similarity(a, b)/(similarity(a, a)*similarity(b, b))**0.5 """ |
return similarity_measure(
a.table_labels, a.table_distances,
b.table_labels, b.table_distances,
margin, cutoff
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def load_chk(filename):
'''Load a checkpoint file
Argument:
| filename -- the file to load from
The return value is a dictionary whose keys are field labels and the
values can be None, string, integer, float, boolean or an array of
strings, integers, booleans or floats.
The file format is similar to the Gaussian fchk format, but has the extra
feature that the shapes of the arrays are also stored.
'''
with open(filename) as f:
result = {}
while True:
line = f.readline()
if line == '':
break
if len(line) < 54:
raise IOError('Header lines must be at least 54 characters long.')
key = line[:40].strip()
kind = line[47:52].strip()
value = line[53:-1] # discard newline
if kind == 'str':
result[key] = value
elif kind == 'int':
result[key] = int(value)
elif kind == 'bln':
result[key] = value.lower() in ['true', '1', 'yes']
elif kind == 'flt':
result[key] = float(value)
elif kind[3:5] == 'ar':
if kind[:3] == 'str':
dtype = np.dtype('U22')
elif kind[:3] == 'int':
dtype = int
elif kind[:3] == 'bln':
dtype = bool
elif kind[:3] == 'flt':
dtype = float
else:
raise IOError('Unsupported kind: %s' % kind)
shape = tuple(int(i) for i in value.split(','))
array = np.zeros(shape, dtype)
if array.size > 0:
work = array.ravel()
counter = 0
while True:
short = f.readline().split()
if len(short) == 0:
raise IOError('Insufficient data')
for s in short:
if dtype == bool:
work[counter] = s.lower() in ['true', '1', 'yes']
elif callable(dtype):
work[counter] = dtype(s)
else:
work[counter] = s
counter += 1
if counter == array.size:
break
if counter == array.size:
break
result[key] = array
elif kind == 'none':
result[key] = None
else:
raise IOError('Unsupported kind: %s' % kind)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear(self):
"""Clear the contents of the data structure""" |
self.title = None
self.numbers = np.zeros(0, int)
self.atom_types = [] # the atom_types in the second column, used to associate ff parameters
self.charges = [] # ff charges
self.names = [] # a name that is unique for the molecule composition and connectivity
self.molecules = np.zeros(0, int) # a counter for each molecule
self.bonds = np.zeros((0, 2), int)
self.bends = np.zeros((0, 3), int)
self.dihedrals = np.zeros((0, 4), int)
self.impropers = np.zeros((0, 4), int)
self.name_cache = {} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_from_file(self, filename):
"""Load a PSF file""" |
self.clear()
with open(filename) as f:
# A) check the first line
line = next(f)
if not line.startswith("PSF"):
raise FileFormatError("Error while reading: A PSF file must start with a line 'PSF'.")
# B) read in all the sections, without interpreting them
current_section = None
sections = {}
for line in f:
line = line.strip()
if line == "":
continue
elif "!N" in line:
words = line.split()
current_section = []
section_name = words[1][2:]
if section_name.endswith(":"):
section_name = section_name[:-1]
sections[section_name] = current_section
else:
current_section.append(line)
# C) interpret the supported sections
# C.1) The title
self.title = sections['TITLE'][0]
molecules = []
numbers = []
# C.2) The atoms and molecules
for line in sections['ATOM']:
words = line.split()
self.atom_types.append(words[5])
self.charges.append(float(words[6]))
self.names.append(words[3])
molecules.append(int(words[2]))
atom = periodic[words[4]]
if atom is None:
numbers.append(0)
else:
numbers.append(periodic[words[4]].number)
self.molecules = np.array(molecules)-1
self.numbers = np.array(numbers)
self.charges = np.array(self.charges)
# C.3) The bonds section
tmp = []
for line in sections['BOND']:
tmp.extend(int(word) for word in line.split())
self.bonds = np.reshape(np.array(tmp), (-1, 2))-1
# C.4) The bends section
tmp = []
for line in sections['THETA']:
tmp.extend(int(word) for word in line.split())
self.bends = np.reshape(np.array(tmp), (-1, 3))-1
# C.5) The dihedral section
tmp = []
for line in sections['PHI']:
tmp.extend(int(word) for word in line.split())
self.dihedrals = np.reshape(np.array(tmp), (-1, 4))-1
# C.6) The improper section
tmp = []
for line in sections['IMPHI']:
tmp.extend(int(word) for word in line.split())
self.impropers = np.reshape(np.array(tmp), (-1, 4))-1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_name(self, graph, group=None):
"""Convert a molecular graph into a unique name This method is not sensitive to the order of the atoms in the graph. """ |
if group is not None:
graph = graph.get_subgraph(group, normalize=True)
fingerprint = graph.fingerprint.tobytes()
name = self.name_cache.get(fingerprint)
if name is None:
name = "NM%02i" % len(self.name_cache)
self.name_cache[fingerprint] = name
return name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_molecule(self, molecule, atom_types=None, charges=None, split=True):
"""Add the graph of the molecule to the data structure The molecular graph is estimated from the molecular geometry based on interatomic distances. Argument: | ``molecule`` -- a Molecule instance Optional arguments: | ``atom_types`` -- a list with atom type strings | ``charges`` -- The net atom charges | ``split`` -- When True, the molecule is split into disconnected molecules [default=True] """ |
molecular_graph = MolecularGraph.from_geometry(molecule)
self.add_molecular_graph(molecular_graph, atom_types, charges, split, molecule) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_molecular_graph(self, molecular_graph, atom_types=None, charges=None, split=True, molecule=None):
"""Add the molecular graph to the data structure Argument: | ``molecular_graph`` -- a MolecularGraph instance Optional arguments: | ``atom_types`` -- a list with atom type strings | ``charges`` -- The net atom charges | ``split`` -- When True, the molecule is split into disconnected molecules [default=True] """ |
# add atom numbers and molecule indices
new = len(molecular_graph.numbers)
if new == 0: return
prev = len(self.numbers)
offset = prev
self.numbers.resize(prev + new)
self.numbers[-new:] = molecular_graph.numbers
if atom_types is None:
atom_types = [periodic[number].symbol for number in molecular_graph.numbers]
self.atom_types.extend(atom_types)
if charges is None:
charges = [0.0]*len(molecular_graph.numbers)
self.charges.extend(charges)
self.molecules.resize(prev + new)
# add names (autogenerated)
if split:
groups = molecular_graph.independent_vertices
names = [self._get_name(molecular_graph, group) for group in groups]
group_indices = np.zeros(new, int)
for group_index, group in enumerate(groups):
for index in group:
group_indices[index] = group_index
self.names.extend([names[group_index] for group_index in group_indices])
if prev == 0:
self.molecules[:] = group_indices
else:
self.molecules[-new:] = self.molecules[-new]+group_indices+1
else:
if prev == 0:
self.molecules[-new:] = 0
else:
self.molecules[-new:] = self.molecules[-new]+1
name = self._get_name(molecular_graph)
self.names.extend([name]*new)
self._add_graph_bonds(molecular_graph, offset, atom_types, molecule)
self._add_graph_bends(molecular_graph, offset, atom_types, molecule)
self._add_graph_dihedrals(molecular_graph, offset, atom_types, molecule)
self._add_graph_impropers(molecular_graph, offset, atom_types, molecule) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.