Search is not available for this dataset
text
stringlengths
75
104k
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 ...
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...
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]+...
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
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
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
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...
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" ...
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...
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...
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) ...
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() ...
def timing_game(self): """Timing game.""" self.ctrl_wg.game_timer.display(self.time) self.time += 1
def reset_game(self): """Reset game board.""" self.ms_game.reset_game() self.update_grid() self.time = 0 self.timer.start(1000)
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...
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;}")
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]...
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 ...
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...
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( ...
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...
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 ...
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...
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...
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...
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 ...
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)
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)
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)
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...
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...
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: ...
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...
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...
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...
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...
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...
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': ...
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', ...
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...
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()) ...
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...
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...
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...
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...
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.")...
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 ...
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...
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)
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...
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...
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...
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...
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...
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: # ...
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.")
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)
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
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]), ), ...
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 ...
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...
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...
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...
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)
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...
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...
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 ...
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 ...
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...
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...
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...
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...
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...
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 *...
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])
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...
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
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(...
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...
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...
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...
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...
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...
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): ...
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...
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
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...
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...
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...
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) ...
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*...
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
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
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
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)
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
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)
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...
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())...
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...