def bfs(initial_state): print('Solving puzzle with BFS') explored_states = set() cost = 0 frontier = [State(initial_state, None, cost, None)] if frontier[0].state == desired_state: return Result(frontier[0], frontier[0].cost, False, True) while frontier: current_node = frontier.pop(0) explored_states.add(current_node.str_state) cost += 1 blank_pos = find_blank_pos(current_node.state) for move in allowed_moves(blank_pos): #print('trying move: ', move) new_state = globals()[move](current_node.state, blank_pos) #print('child node state: ', str(new_state)) new_moves_list = list(current_node.move_list) new_moves_list.append(move) #print('new move list: ', str(new_moves_list)) child = State(new_state, current_node, cost, new_moves_list) if child.str_state not in explored_states: if child.state == desired_state: #return child return Result(child, child.cost, False, True) frontier.append(child)
def dldfs(initial_state, limit): visited_nodes.clear() cost = 0 frontier = [State(initial_state, None, cost, None)] while frontier: #print('frontier size: ', len(frontier)) if frontier[0].depth <= limit: #print('Limit: ', limit) current_node = frontier.pop(0) #print('current node depth: ',current_node.depth) visited_nodes.add(current_node.str_state) if current_node.state == desired_state: return Result(current_node, current_node.cost, False, True) cost += 1 blank_pos = find_blank_pos(current_node.state) for move in allowed_moves(blank_pos): new_state = globals()[move](current_node.state, blank_pos) new_moves_list = list(current_node.move_list) new_moves_list.append(move) #print('new move list: ', str(new_moves_list)) child = State(new_state, current_node, cost, new_moves_list, current_node.depth + 1) #print('child node depth: ', child.depth) if child.str_state not in visited_nodes: frontier.insert(0, child) #visited_nodes.add(child.str_state) else: #print('Sigo con el siguiente de la frontera, este supera el limite') frontier.pop(0) return Result(None, None, True, False)
def walk(combination, ptr, actionsSoFar, remainingTargets): start = ptr targets = list(remainingTargets) actions = list(actionsSoFar) if ptr >= len(combination): return Result(self.source, actions, [], targets) alternate = None total = int(combination[ptr]) while ptr < len(combination): if total in targets: altTargets = list(targets) altTargets.remove(total) altActions = list(actions) action = ''.join([str(n) for n in combination[start:ptr + 1]]) altActions.append(action) alternate = walk(combination, ptr + 2, altActions, altTargets) if ptr < len(combination) - 2: op = combination[ptr + 1] nextDigit = int(combination[ptr + 2]) if op == '+': total = total + nextDigit elif op == '-': total = total - nextDigit else: total = total * nextDigit ptr += 2 leftovers = str(combination[start:]).translate(self.all, self.nodigits) result = Result(self.source, actions, list(leftovers), targets) if alternate is not None and alternate.score() > result.score(): return alternate return result
def read_result_from_file(result_file, docnolist_file): docnolist = parse_corpus(docnolist_file) docid_map = dict(zip(docnolist, range(len(docnolist)))) res_all = parse_corpus(result_file) res_dict = OrderedDict() prev_qid, runid = -1, -1 docid_list = [] score_list = [] for line in res_all: tokens = line.split() qid, docid, score, runid = int(tokens[0]), docid_map.get( tokens[2]), float(tokens[4]), tokens[5] if qid != prev_qid: if len(docid_list) > 0: result = Result(qid, docid_list, score_list, runid) res_dict.update({prev_qid: result}) docid_list, score_list = [docid], [score] prev_qid = qid else: docid_list.append(docid) score_list.append(score) res = Result(prev_qid, docid_list, score_list, runid) res_dict.update({prev_qid: res}) return res_dict
def __init__(self, data, model, learning_rate=0.01, l1_rate=0., l2_rate=0.): assert isinstance(data, Data) assert isinstance(model, Model) self.data = data self.model = model self.result = Result() self.params_result = Result(os.path.join(self.result.dir, 'params')) weights = [ p for p in self.model.params if 'weight' in p.name or 'filter' in p.name ] l1 = np.sum([abs(w).sum() for w in weights]) l2 = np.sum([(w**2).sum() for w in weights]) self._cost = function( inputs=(self.model.input_symbol, self.model.answer_symbol), outputs=self.model.cost(True) + l1_rate * l1 + l2_rate * l2, updates=self._update(learning_rate)) self._train_error = function(inputs=(self.model.input_symbol, self.model.answer_symbol), outputs=self.model.error(True), updates=[]) self._test_error = function(inputs=(self.model.input_symbol, self.model.answer_symbol), outputs=self.model.error(False), updates=[])
def parse_output(self, output_lines, variable_map, core_file_name=None): if output_lines[0][2:] == 'SATISFIABLE': # get values from remaining lines # be aware that only the last line is 0-terminated! output_values = {} for l in output_lines[1:]: for v in l.split(" ")[1:]: var_num = int(v.strip("-")) - 1 if var_num == -1 or var_num not in variable_map: break if v.startswith("-"): output_values[variable_map[var_num]] = False else: output_values[variable_map[var_num]] = True return Result(True, output_values, []) elif output_lines[0][2:] == 'UNSATISFIABLE': core = [] if self.options.get('calculate_unsat_core', True) != False: with open(core_file_name, "r") as f: corelines = f.read().strip().split("\n")[1:] for l in corelines: literals = l.split(" ")[:-1] if len(literals ) == 1: # watching out for clauses with one literal index = abs(int(literals[0])) - 1 var = self.vars[index] if var in self.core_map: core.append(self.core_map[var].ab_predicate) return Result(False, [], core) else: raise RuntimeError("picosat returned unexpected output: " + "\n".join(output_lines))
def flag(self, i, j): """Toggle flag at position (i,j).""" if not self.valid_position(i, j): # Return invalid input message return Result( message="Invalid position ({},{}) on {}x{} board.".format( i, j, self.m, self.n), code=0) target = self.board[i][j] if target.revealed: return Result(message="Cell ({},{}) already revealed.".format( i, j), code=0) # Toggle flag: delta = target.toggle_flag() self.num_mines += delta # Check for completion (num_mines == 0) if self.num_mines == 0: # If complete reveal board and return success result self._reveal_board() return Result("Success!", 1) # Otherwise return continue result return Result("", 0)
def check(self, i, j): """Reveal position (i,j). Also reveal any neighboring cells with counts of 0. """ if not self.valid_position(i, j): # Return invalid input message return Result( message="Invalid position ({},{}) on {}x{} board.".format( i, j, self.m, self.n), code=0) target = self.board[i][j] if target.revealed: return Result(message="Cell ({},{}) already revealed.".format( i, j), code=0) if target.mine: target.fatal = True return Result(message="Mine!", code=-1) # Reveal cell # Recursively reveal all empty neighbors target.reveal() return Result(message="", code=0)
def run(self, methods, args): # Run clusterings results = [] vectorizer = None if args["vectorizer"] == "count": vectorizer = CountVectorizer( min_df=args["min_df"], max_df=args["max_df"], lowercase=True, analyzer="word", stop_words="english", ) elif args["vectorizer"] == "tfidf": vectorizer = TfidfVectorizer( min_df=args["min_df"], max_df=args["max_df"], lowercase=True, analyzer="word", stop_words="english", ) self.create_data_matrix(vectorizer) if "kmeans" in methods: labels, processing_time = self.kmeans() results.append(Result("KMeans", labels, processing_time)) if "hdbscan" in methods: labels, processing_time = self.hdbscan(args) results.append(Result("HDBSCAN", labels, processing_time)) return results
def testOne(self, inFile, solFile): """ run the executable using inFile as the inputs and checking the output against solFile @inFIle: the name of the file containing the inputs @solFile: the name of the file containg the solution @returns: a Result """ (progStatus, studentAnswer) = self._runOne(inFile, self.userOut) #run the program testName = os.path.basename(inFile) #the name of the test if (progStatus == Tester._PROGRAM_CRASHED): return Result(testName, False, 'Crashed') elif (progStatus == Tester._PROGRAM_TIMED_OUT): return Result(testName, False, 'Timed Out') else: #program completed successfully if (self.outputType == Tester.OUTPUT_STDOUT): (correct, out, sol) = self._checkSolution(studentAnswer, solFile) if (correct): studentLogger.info('%s %s passed test %s', self.executable, ' '.join(self.cmdArgs), os.path.basename(inFile)) else: studentLogger.info( '%s %s failed test %s. Program output: %s \n Solution: %s \n\n', self.executable, ' '.join(self.cmdArgs), os.path.basename(inFile), out, sol) return Result(testName, correct, self.endTime - self.startTime) else: #haven't done anything where solutions are contained in files raise NotImplementedError
def executeMany(self, sql_cmd, values): try: self.reconnect() self.cursor.executemany(sql_cmd, values) self.conn.commit() return Result(0) except Exception as e: error_msg = "error when executing MySQL command(many values): %s" % e Log.wError(error_msg) return Result(1).setInfo(error_msg)
def respond_to_greeting(self): if self.traits.hostile: result = Result("The {} snorts derisively at your greeting".format( self.name)) elif self.traits.friendly: result = Result( "The {} gives you a friendly wave in return".format(self.name)) else: result = Result( "The {} acknowledges your greeting with a curt nod".format( self.name)) return result
def evaluate(transcription_path, ground_truth_path): try: result = test_transcriptions.test_files(transcription_path, ground_truth_path) cer, wer = result.data result = Result(result.status, EvalData(transcription_path, cer, wer), result.message) except: result = Result(Status.FAILURE, "Something unexpectedly failed during evaluation.") return result
def query(self, sql_cmd): try: self.reconnect() self.cursor.execute(sql_cmd) data = self.cursor.fetchall() self.conn.commit() result = Result(0) result.setItem('data', data) return result except Exception as e: error_msg = "error when quering MySQL: %s" % e Log.wError(error_msg) return Result(1).setInfo(error_msg)
def get_items(league, stash_tabs=None, filter_tabs=False): stash_tabs = [] if stash_tabs == None else stash_tabs stash_tabs = [unicode(stash_tab) for stash_tab in stash_tabs] path = get_fname_by_league(league) try: _json = read_item_db(os.path.join(datadir, path)) _json = [ val for val in _json if ("name" in val.keys()) and ("_tab_label" in val.keys()) ] if filter_tabs: _json = [ item for item in _json if item["_tab_label"] in stash_tabs ] assert len(_json) > 0 except BaseException as e: print(e) return Result(False) for item in _json: item["name"] = item["name"].rsplit(">")[-1] item["typeLine"] = item["typeLine"].rsplit(">")[-1] if "frameType" in item: item["rarity"] = rarities[item["frameType"]] if item.has_key("sockets"): group = None links = [] for socket in item["sockets"]: if socket["group"] == group: links.append("-") else: links.append(" ") links.append(attr_to_col[socket["attr"]]) group = socket["group"] links = "".join(links)[1:] item["links"] = links return Result(True, items=_json, fname=os.path.split(path)[-1], league=_json[0]["league"])
def move_character(self, character_id, destination): # get the current graph and add the current character's position as a node graph = self.pathfinding_grid.copy() # use the graph's shortest path method try: path = graph.shortest_path(self.characters[character_id].position, destination) self.deltas.add( MoveDelta(self.characters[character_id], destination, path)) return Result(ResultIds.SUCCESS) # if it is not reachable, set the result to a failure except graph_2d.ImpossiblePath: # otherwise set the result to success return Result(ResultIds.ERROR) return r
def run(self): tc = Testcase() file_list = tc.get_csv_list() r = True tc_result = Result(self.time) for f in file_list: logger = Logger(f, self.time).setup_logging() steps = tc.get_steps(f) csv_lines = tc.get_line(f) #result init r = True exe = Execution(steps[0]) for step, line in (zip(steps, csv_lines)): try: logger.info(str(line).encode('utf-8')) exe.update_step(step) exe.execute() except Exception as e: r = False logger.exception(e) break exe.quit() tc_result.set_result(f, r) env = Environment( loader=PackageLoader("template_package", 'templates')) template = env.get_template('template.html') if not os.path.exists(setting.TEST_RESULTS_FOLDER): os.makedirs(setting.TEST_RESULTS_FOLDER) # 创建result文件 result_html = setting.TEST_RESULTS_FOLDER + os.sep + tc_result.get_result( )['time'] + '.html' with codecs.open(result_html, 'w', 'utf-8') as res: res.write(template.render(result=tc_result.get_result()))
def concatenate_records(self, compound_key, records_list): """ NB: had a version of this which used a reduce construct to concatenate the alignments - reduce(lambda x,y: x+y, records_list) - but this led to problems of the original object being modified. Deepcopying the first record, ensuring a new memory address for the concatenation, seems more robust. """ partition = self.partitions[ compound_key] # partition = list like [ 1, 1, 2, 1, 1, 2, 3, 3] memberships = self.get_memberships(partition) clusters = {} shorten = lambda k: ''.join([str(k[x])[:3] for x in range(len(k))]) index = 1 # index for naming clusters for cluster in memberships: members = [records_list[i] for i in cluster] first = deepcopy(members[0]) # use of deepcopy here is important for rec in members[1:]: first += rec first.name = shorten(compound_key) + '_{0}'.format(index) clusters[index] = {'concatenation': first, 'members': members} index += 1 self.clusters[compound_key] = Result(clusters) return clusters
def get(self, row: str, table_name: str, table_namespace: str = "default", columns: Mapping[str, List[str]] = None, min_time: Optional[int] = None, max_time: Optional[int] = None, max_versions: Optional[int] = None) -> 'Result': if min_time is not None: _min_time = Int64Value(value=min_time) else: _min_time = Int64Value() if max_time is not None: _max_time = Int64Value(value=max_time) else: _max_time = Int64Value() if max_versions is not None: _max_versions = Int32Value(value=max_versions) else: _max_versions = Int32Value() query = Get( table=Table(name=table_name, namespace=table_namespace), row=row, columns={f: Columns(columns=c) for f, c in columns.items()}, max_versions=_max_versions, min_time=_min_time, max_time=_max_time) return Result(self._client.get(query))
def solve(maze): name = 'breadthfirst' visited = [] queue = deque([maze.start]) start_time = time.time() while len(queue) > 0: current = queue.popleft() visited.append(current) if current == maze.end: break # neighbours = [x for x in current.Neighbours if x is not None and x not in visited and x not in queue] neighbours = [ x for x in current.Neighbours.values() if x not in visited and x not in queue ] for x in neighbours: x.Previous = current queue.append(x) completion_time = time.time() - start_time current = maze.end path = deque() while current is not None: path.appendleft(current) current = current.Previous return Result(name, visited, path, path[-1].Distance, completion_time)
def initialize(self): # Set the display position of the mainwindow. desktop = QApplication.desktop() x = (desktop.width() - self.width()) // 2 y = (desktop.height()-65 - self.height()) // 2 self.move(x, y) # Desine the translator to translate interface languages. self.trans = QTranslator(self) # Define the Result class to record the results in the process. self.result = Result() # Define the fdem forward simulation thread class. self.thread_cal_fdem = ThreadCalFdem() # Define the fdem inversion thread class. self.thread_inv_fdem = ThreadInvFdem() # Define the figure to show data in the interface. self.fig_scenario = Figure(figsize=(4.21, 3.91)) self.canvas_scenario = FigureCanvasQTAgg(self.fig_scenario) self.gl_detection_scenario.addWidget(self.canvas_scenario) self.fig_discretize = Figure(figsize=(4.21, 3.91)) self.canvas_discretize = FigureCanvasQTAgg(self.fig_discretize) self.gl_discretize.addWidget(self.canvas_discretize) self.fig_magnetic_field = Figure(figsize=(4.21, 3.91)) self.canvas_magnetic_field = FigureCanvasQTAgg(self.fig_magnetic_field) self.gl_magnetic_field_data.addWidget(self.canvas_magnetic_field) self.pbar_rfs.setVisible(False) self.pbar_rfi.setVisible(False)
def dhondt(year, min_seats=6, parliament_size=751, max_seats=96): pop = get_pop(year) tmp = deepcopy(pop) rem = parliament_size for item in tmp: rem -= min_seats tmp[item] = Result(pop[item]) tmp[item].seats = min_seats tmp[item].seats_before_rounding = min_seats tmp[item].tmppop = tmp[item].population tmp[item].tmpdiv = 1 ks = list(tmp.keys()) while rem > 0: ks.sort(key=lambda x: -tmp[x].tmppop) i = 0 while tmp[ks[i]].seats == max_seats: i += 1 tmp[ks[i]].seats += 1 tmp[ks[i]].seats_before_rounding += 1 tmp[ks[i]].tmpdiv += 1 tmp[ks[i]].tmppop = tmp[ks[i]].population/tmp[ks[i]].tmpdiv rem -= 1 return tmp
def hamilton(year, min_seats=6, parliament_size=751, max_seats=96): pop = get_pop(year) tmp = deepcopy(pop) for item in tmp: tmp[item] = Result(pop[item]) total_pop = sum([pop[x] for x in pop]) rem = parliament_size for item in tmp: tmp[item].seats_before_rounding = (tmp[item].population/total_pop)*parliament_size tmp[item].seats = floor(tmp[item].seats_before_rounding) tmp[item].seats = min(tmp[item].seats, max_seats) tmp[item].seats = max(tmp[item].seats, min_seats) rem -= tmp[item].seats srt = by_value(tmp, lambda x: -(x[1].seats_before_rounding-x[1].seats)) order = list(srt.keys()) i = 0 while rem > 0: if tmp[order[i]].seats < max_seats: tmp[order[i]].seats += 1 rem -= 1 i = (i + 1) % len(tmp) return tmp
def spline(year, min_seats=6, parliament_size=751, max_seats=96, round=ceil): pop = get_pop(year) tmp = deepcopy(pop) for item in tmp: tmp[item] = Result(pop[item]) d = sum(pop.values()) / parliament_size min_pop = min(pop.values()) x = None while True: for item in pop: tmp[item].seats_before_rounding = min(min_seats + (pop[item]-min_pop) / d, max_seats) tmp[item].seats = round(tmp[item].seats_before_rounding) seats = [x.seats for x in tmp.values()] if sum(seats) == parliament_size: break elif sum(seats) > parliament_size: d += d * 0.00001 if x is False: raise RuntimeError("Impossible") x = True else: d -= d * 0.00001 if x is True: raise RuntimeError("Impossible") x = False return tmp
def task3(results): with open('./output/group7.csv', 'w+') as out: out.write( 'subject_id,MFD_true,MFD_SD_true,MFD_false,MFD_SD_false,MSA_true,MSA_SD_true,MSA_false,MSA_SD_false,MFD_overall,MFD_overall_SD,MSA_overall,MSA_overall_SD\r\n' ) for subject in subjects[:-1]: true_data = results[subject]['true'] false_data = results[subject]['false'] params = [] params.append(subject) params.append(true_data.get_mfd()) params.append(true_data.get_mfd_sd()) params.append(false_data.get_mfd()) params.append(false_data.get_mfd_sd()) params.append(true_data.get_msa()) params.append(true_data.get_msa_sd()) params.append(false_data.get_msa()) params.append(false_data.get_msa_sd()) overall_result = Result('overall', None) overall_result.append_fixation_duration( true_data.fixation_durations) overall_result.append_fixation_duration( false_data.fixation_durations) overall_result.append_saccade_amplitude( true_data.saccade_amplitudes) overall_result.append_saccade_amplitude( false_data.saccade_amplitudes) params.append(overall_result.get_mfd()) params.append(overall_result.get_mfd_sd()) params.append(overall_result.get_msa()) params.append(overall_result.get_msa_sd()) out.write( '{},{},{},{},{},{},{},{},{},{},{},{},{}\r\n'.format(*params))
def __init__(self, xml_state, target_dir, root_dir): self.media_dir = None self.arch = platform.machine() self.root_dir = root_dir self.target_dir = target_dir self.xml_state = xml_state self.live_type = xml_state.build_type.get_flags() self.types = Defaults.get_live_iso_types() self.hybrid = xml_state.build_type.get_hybrid() self.volume_id = xml_state.build_type.get_volid() self.machine = xml_state.get_build_type_machine_section() self.mbrid = ImageIdentifier() self.mbrid.calculate_id() if not self.live_type: self.live_type = Defaults.get_default_live_iso_type() self.boot_image_task = BootImageTask('kiwi', xml_state, target_dir) self.firmware = FirmWare(xml_state) self.system_setup = SystemSetup(xml_state=xml_state, description_dir=None, root_dir=self.root_dir) self.isoname = ''.join([ target_dir, '/', xml_state.xml_data.get_name(), '.' + platform.machine(), '-' + xml_state.get_image_version(), '.iso' ]) self.live_image_file = ''.join([ target_dir, '/', xml_state.xml_data.get_name(), '-read-only.', self.arch, '-', xml_state.get_image_version() ]) self.result = Result()
def delete(self, ignore_not_found=True, cmd_args=None): """ :param ignore_not_found: If True, named resources which are not present will not raise an error. :param base_args: Additional delete arguments :param wait_for: Include an `oc wait --for=delete ...` for each resource deleted :param cmd_args: An optional list of additional arguments to pass on the command line :return: Returns a list of qualified object names which were deleted. """ names = self.qnames() r = Result("delete") if len(names) == 0: return [] base_args = list() if ignore_not_found: base_args.append("--ignore-not-found") base_args.append("-o=name") r.add_action( oc_action(self.context, "delete", all_namespaces=self.all_namespaces, cmd_args=[ self._selection_args(needs_all=True), base_args, cmd_args ])) r.fail_if("Error deleting objects") return split_names(r.out())
def run_model(x_train, x_test, y_train, y_test): clf = tree.DecisionTreeClassifier() clf = clf.fit(x_train, y_train) y_pred = clf.predict(x_test) y_prob_pred = clf.predict_proba(x_test.round()) return Result(result=y_pred, y_test=y_test)
def annotate(self, annotations, overwrite=True, cmd_args=None): """ Applies a set of annotations to selected objects. :param annotations: A dictionary of annotations to apply. :param overwrite: If true, any existing annotations will be overwritten. If false, existing annotations will cause a failure. :param cmd_args: An optional list of additional arguments to pass on the command line """ r = Result("annotate") base_args = list() if overwrite: base_args.append("--overwrite") for l, v in six.iteritems(annotations): if not v: if not l.endswith("-"): l += "-" # Indicate removal on command line if caller has not applied "-" suffix base_args.append(l) else: base_args.append('{}={}'.format(l, v)) r.add_action( oc_action(self.context, "annotate", all_namespaces=self.all_namespaces, cmd_args=[ self._selection_args(needs_all=True), base_args, cmd_args ])) r.fail_if("Error running annotate") return self
def __call__(self, contrast_data): #t = time.time() # sample possible MNI coordinates permuted_order = np.random.permutation(self.n_mni_voxels) random_mean = np.zeros([1, 100]) for i in range(100): random_xyz = [ self.all_non_zero[0][permuted_order[i]] - self.mni_dim[0] / 2, self.all_non_zero[1][permuted_order[i]] - self.mni_dim[1] / 2, self.all_non_zero[2][permuted_order[i]] - self.mni_dim[2] / 2 ] random_mean[0][i] = self.check_coordinate(Coordinates(random_xyz), contrast_data)['mean'] # some subjects have nans in some location because they might not have voxels in that region (?) random_mean = np.nan_to_num(random_mean) results = [ self.check_coordinate_rank(c, contrast_data, random_mean) for c in contrast_data.contrast.coordinates ] html = create_html_table(results, title="Rank of ROI") #print (time.time() - t), "per contrast" # takes about 130 seconds by subject by contrast if 100 random locations return self.make_output(Result(html, contrast_data))