dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def all2edges(self,node_attr,edge_attr,global_attr): #update edges # node:[num_node,num_feature] # edge:[num_node*num_node, feature] # node2edge #sender2edges #reciver2edges num_nodes=node_attr.shape[0] rel_rec,rel_send=getrel(num_nodes) x1=node_at...
The code processes node, edge, and global attributes in a graph neural network. It updates edges using node and global features, then updates global features with nodes and edges, followed by updating nodes with all components. The final output is the updated node features, passing through an MLP to produce a tensor of...
def forward(self, inputs, edge_attr, global_attr): #the input contains: x, e, g #output tensor:size of out_channels x_n = inputs # update edges edges=self.all2edges(x_n,edge_attr,global_attr) # update global globals=self.all2globals(x_n,edges,global_attr) ...
def fix_balance_condition(a, b, C): diff = np.sum(a) - np.sum(b) if diff: if diff > 0: b = np.append(b, diff) print(C) print(np.zeros(a.size)) C = np.c_[C, np.zeros(a.size)] else: a = np.append(a, abs(diff)) C = np.r_[C, np...
The code solves a transportation problem by balancing supply and demand using `fix_balance_condition`, then computes the optimal distribution plan `X` with `solve_transport_task` and calculates the total cost using `cost(C, X)`. It prints the balanced supply, demand, cost matrix, optimal plan, and total cost.
def main(): # a = np.array([100, 300, 300]) # b = np.array([300, 200, 200]) # C = np.array([ # [8, 4, 1], # [8, 4, 3], # [9, 7, 5] # ]) # a = np.array([20, 30, 25]) # b = np.array([10, 10, 10, 10, 10]) # C = np.array([ # [2, 8, -5, 7, 10], # [11, 5, 8...
def make(self): """ fills the first three boxes and first column of a blank grid, then uses generate() to generate a final puzzle """ # step zero: initialize puzzle with all candidates for i in range(self.size**2): self.puzzle.append(self.candidates) # step one: fil...
This class initializes a Sudoku puzzle, tracks candidate values, solves the puzzle, and calculates difficulty based on branching factors and empty cells. It ensures the puzzle has a unique solution, storing valid solutions and computing a difficulty score if uniquely solvable.
def __init__(self, size=9, label=time.time(), puzzle=[]): # instance attributes: self.puzzle = [] self.size = size self.box_size = int(math.sqrt(size)) self.label = str(label) self.candidates = '' for i in range(self.size): self.candidates += str(i + 1...
def package(c): '''Package jar file''' local("mvn clean package") def root_conn(): return Connection( host='{0}@{1}'.format(SUDO_USER, SERVER_HOST), connect_kwargs={"password": SUDO_PASSWORD} ) def upload_jar(c): '''Upload jar file to server''' print("Uploading jar file to server...
The main task of the code is to deploy an application to a server by packaging it, uploading a JAR file, restarting the service, and checking its status. It uses a connection context manager to execute these operations on the server, ensuring the deployment process is initiated and verified.
def deploy(c): '''Deploy to server''' print("Deploying to server") package(c) with root_conn() as conn: upload_jar(conn) restart(conn) status(conn)
def _set_load_json_name(self): if os.path.exists( f'{self.code_file_dir}/{BaseEasyLogging.log_para_config_local_json_name}'): self.log_para_config_json_name = BaseEasyLogging.log_para_config_local_json_name if os.path.exists( f'{self.code_file_dir}/{BaseEasyLo...
This code initializes a logging configuration system by loading parameter and path settings from JSON files. It sets up file paths, checks if configuration files exist, loads their contents into dictionaries, merges parameter and path configurations, and prepares a core logger config dictionary for further use.
def __init__(self): self.log_para_config_json_name = BaseEasyLogging.log_para_config_json_name # load file name self.log_path_config_json_name = BaseEasyLogging.log_path_config_json_name # load file name self.code_file_dir = Path(os.path.dirname(__file__)) # current .py file dir # sel...
def _runInitializedEvents(self): if self._debug: print("Running Initialized events {0}...".format(time.time())) self._runEvents(self._initializedEvents) def _runRotaryButtonPressedEvents(self): if self._debug: print("Running Rotary Pressed Event at {0}".format(time.time())) if self._even...
The main task of the code is to run an infinite loop that monitors a rotary encoder's state, triggers button-pressed events when conditions are met, executes idle events when the system is idle, and ensures proper cleanup of resources. It continuously checks for input, manages event execution, and maintains a 0.1-secon...
def runForever(self): self._runInitializedEvents() # give the display to the rotary encoder to update if self._debug: print("RUNNING FOREVER!!") try: while True: # this if statement is for the count up to happen if self._currentTimeCount and se...
def cli_management(): # argument pass to the application parser = argparse.ArgumentParser( prog="etcd-management", description="Manage etcd rke2 pods", epilog="Have a good day ;) ") parser.add_argument("-v", "--verbose", help='Add debug information',action='store_true') #group ...
The main task of the code is to manage etcd cluster operations via CLI arguments, including retrieving endpoints, enabling debug logging, listing node states/nodes, fetching the leader, and migrating leadership. It processes flags like --verbose, --state, --list, --leader, and --migrate to perform corresponding actions...
def main(): # mange cli arguments args=cli_management() # get etcd endpoints get_endpoints() if args.verbose: #Activate logging logger= logging.getLogger() logger.setLevel('DEBUG') logger.debug('debug ON') if args.state: list_nodes_state() if args.list: list_nodes() if args.leader: get_lead...
def answer_question(self, node): # if False: if node.depth == 1 and node.hasHint(): dict_answer_candidates = {} for i, hint in enumerate(node.hints): format_hint = '(1) ' + hint + '.' # generate prompt prompt, tip, system_define ...
This function processes a node by answering it and updating its state. If the answer's confidence is high or the node is a leaf (and has hints or isn't at depth 1), it logs the result and returns the answer. Otherwise, it generates follow-up questions, logs them, and returns these questions for further processing.
def self_questioning(self, node): raw_answer, answer, used_hints, confidence = self.answer_question(node) node.update_answer(answer, used_hints, confidence) # raise question if (confidence == 'high' or node.isLeaf) and (node.hasHint() or node.depth != 1): # if (confidence ...
def self_questioning(self, node): raw_answer, answer, used_hints, confidence = self.answer_question(node) node.update_answer(answer, used_hints, confidence) # raise question if (confidence == 'high' or node.isLeaf) and (node.hasHint() or node.depth != 1): # if (confidence ...
The code recursively explores subquestions by generating deeper nodes, collecting hints from answers, and updating the node's state. It continues iterating until no further questions are needed, then returns the final answer.
def run(self, node): # self questioning continue_deeper, output = self.self_questioning(node) if continue_deeper: # output is subquestion list for deep_question in output: deep_node = SocraticNode(deep_question, node.turn, node.depth+1, self.max_turn, self.max_depth, ...
def played_maps(request): mapholders = request.html.find('.mapholder') maps_info = [] for maph in mapholders: map_info = played_map(maph) if not map_info: continue maps_info.append(map_info) return len(mapholders), maps_info def teams_box(request): teams_box = re...
The main task of the code is to scrape and aggregate match-related data from HLTV.org, including best-of format, map details, team information, demo links, player statistics, and map veto data, compiling it into a structured dictionary for return. The function uses a session to fetch a match page, extracts specific dat...
def main(session, headers, match_url): print('match_main_page', match_url.split('/')[3]) url = 'https://www.hltv.org' + match_url request = session.get(url, headers=headers) best_of, maps_info = played_maps(request) t_box = teams_box(request) d_href = demo_href(request) tmp = { 'u...
def playingEvents(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False if event.type == pygame.MOUSEBUTTONDOWN: selected = self.mouseOnGrid() if selected: self.selected = selected ...
The code defines a `run` method that executes a game loop, continuously processing events, updating game state, and rendering visuals while `self.running` is True. It terminates the Pygame window and exits the program when the loop ends.
def run(self): while self.running: self.playingEvents() self.playingUpdate() self.playingDraw() pygame.quit() sys.exit()
def check_fleet_edges(ai_settings, aliens): # Respond appropriately if any aliens have reached at edge for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) break def ship_hit(ai_settings, stats, screen, ship, aliens, bullets): # R...
The function updates alien positions, checks for collisions with the ship or screen bottom, and triggers responses like ship damage or game over events.
def update_aliens(ai_settings, stats, screen, ship, aliens, bullets): '''check if the fleet is at an edge, and then updates its positions''' check_fleet_edges(ai_settings, aliens) # update positions of aliens aliens.update() # Look for alien ship collision if pygame.sprite.spritecollideany(...
def eval(self): self.eval_run = True def reset(self): self.off_track_t = 0 self.done = 0 self.cumulative_reward = 0 self.env.reset() for _ in range(50): self.off_track_t = 0 self.step(np.zeros(self.num_actions), startup=True) self.state =...
The code evaluates the performance of a policy (either a neural network or predefined labels) by simulating multiple trajectories. It initializes the environment, generates actions using the provided network or labels, executes episodes, and collects cumulative rewards. The function returns the average reward across al...
def evaluate(self, set, net=None): if net is not None: net.eval() self.eval() self.reset() eval_perf = [] while len(eval_perf) < set.eval_num_traj: # get the initial state and action obs, _, _, lbl = self.get_state() if net is no...
def eval(self): self.eval_run = True def reset(self): self.off_track_t = 0 self.done = 0 self.cumulative_reward = 0 self.env.reset() for _ in range(50): self.off_track_t = 0 self.step(np.zeros(self.num_actions), startup=True) self.state =...
This function displays the agent's environment interactions using either the environment's render method or an OpenCV window for transformed observations. It evaluates the agent/network, executes actions, updates the environment, and visualizes results. If a neural network is provided, it uses it for action inference; ...
def display(self, set, net=None, transformed=False): if net is not None: net.eval() self.eval() self.reset() action = np.zeros((set.num_actions)) if transformed: cv2.namedWindow("display", cv2.WINDOW_NORMAL) while True: obs, rwd, dn...
def vna_address_menu(): print("\nBeginning connection procedure...\n") # Default VISA Address values. # Change these to change default values. default_tcpip_address = '10.10.10.155' default_port_number = 5025 # Values used to create VISA Address. tcpip_address = None port_number = None...
The main task of the code is to provide a menu-driven interface for controlling a Vector Network Analyzer (VNA), performing measurements (S-parameters, TDR), plotting data, configuring settings, and managing email alerts. It maintains a VNA connection state, handles user input for operations like measurement types, dat...
def main_menu(): # vna_session is the current connection to the VNA. # vna_session begins as none until connection is created. # vna_session is used to control VNA. vna_session = None # main_menu_success is used to break main_menu loop. main_menu_success = False # main_menu_printed is used...
def getAllPaths(self, s, d): source = self.get_vertex(s) destination = self.get_vertex(d) # Create an array to store paths path = [] # Call the recursive helper function to print all paths self.getAllPathsUtil(source, destination, path) def getPathCost(self, path): ...
The main task of the code is to find the shortest valid path from a source to destination within a given cost, while avoiding critical or occupied nodes. It first identifies the shortest path under the budget, then constructs a final path by skipping critical/occupied nodes by appending the last node (waiting), ensurin...
def getPekingPath(self, source, destination, cost): self.getAllPaths(source, destination) self.paths.sort(key=len) shortestPathInBudget = [] for path in self.paths: if self.getPathCost(path) <= cost: shortestPathInBudget = path break fi...
def design_base(wall_t,wall_width,base_width,base_thickness,base_length,span_length,key_depth,folder_path): x=span_length/2 + base_length s =base_width-wall_width y=s/3 y=y+(wall_width/2) point=[] point.append(Base.Vector(-x,y,0)) point.append(Base.Vector(-x+base_length,y,0)) point.append(Base.Vector(-x+base_le...
The code reads CSV data containing structural dimensions, converts them using a scale factor (304.5), and generates simulation designs by calling functions like `design_base`, `design_plate`, `design_frame`, and `design_shield` with calculated parameters. It creates a folder for outputs based on wall height and execute...
def main(): barrier_data = file("/home/nsambataufeeq/usb/barrier/barrier.csv","r") des_data = csv.reader(barrier_data) for row in des_data: wall_height = int(row[0]) wall_t = float(row[1]) wall_t = 304.5*wall_t wall_width= 304.5*1 base_width = float(row[2]) base_width = 304.5*base_width base_thickness ...
def get_process_dict() -> dict[str, int | str]: nvidia_out = system_call('nvidia-smi') lines = str(nvidia_out).split('\\n') process_lines = get_sep_lines(nvidia_out)[1] process_dict = {} for i in np.arange(process_lines, len(lines)): if '===' in lines[i] or '---' in lines[i]: con...
The code generates pie charts to visualize GPU usage distribution across multiple GPUs, highlighting the user with the highest usage. It arranges subplots in a grid, with each chart displaying GPU utilization percentages, exploded slices for emphasis, and titles indicating the GPU ID. The function aggregates process an...
def plot_gpu_usage() -> None: process_dict = get_process_dict() gpu_dict = get_gpu_dict() num_rows = 2 num_cols = int(np.ceil(len(gpu_dict.keys()) / num_rows)) fig, axs = plt.subplots( num_cols, num_rows, figsize=(num_rows*5, num_cols*5), ) gpu_list = list(gpu_dict.keys()) count...
def get_process_dict() -> dict[str, int | str]: nvidia_out = system_call('nvidia-smi') lines = str(nvidia_out).split('\\n') process_lines = get_sep_lines(nvidia_out)[1] process_dict = {} for i in np.arange(process_lines, len(lines)): if '===' in lines[i] or '---' in lines[i]: con...
The main task of the code is to print GPU memory usage by user, sorted in descending order, along with associated processes. It retrieves GPU and process data, iterates through GPUs, calculates usage, sorts users by memory consumption, and formats output showing each user's MiB/GiB usage and their processes.
def print_gpu_usage() -> None: process_dict = get_process_dict() gpu_dict = get_gpu_dict() gpu_list = list(gpu_dict.keys()) for cur_gpu in gpu_list: print('GPU: ' + str(cur_gpu)) usage_dict, process_list_dict = get_gpu_usage( gpu_dict, process_dict, cur_gpu, ) ...
def find_max_information_gain(features, targets): """ return index of maximal info gain for features""" max_info_index = 0 max_information_gain = 0 for i in range(len(features[0])): if information_gain(features, i, targets) > max_information_gain: max_info_index = i max_i...
This code recursively builds a decision tree by selecting the feature with maximum information gain, splitting the dataset based on that feature's values, and creating child nodes for each split. It stops splitting when a feature has only one unique value, then assigns the most common target label as a leaf node. The r...
def fit_recursion(self, node, features, targets): max_info_index = find_max_information_gain(features, targets) values_for_index = set((features[:, max_info_index])) if len(values_for_index) == 1: # No added value for maximal information gain -> we reached our stop point ...
def check_call_cmd(*cmd, **kwargs): """ Verbose prints the directory location the given command is called from and the command, then executes the command using check_call. Parameter descriptions: dir Directory location command is to be called from cmd List of par...
The code executes unit tests repeatedly using a constructed command, invokes valgrind and coverage tools, and handles errors by logging test-suite outputs before raising an exception if tests fail.
def test(self): try: cmd = make_parallel + ["check"] for i in range(0, args.repeat): check_call_cmd(*cmd) maybe_make_valgrind() maybe_make_coverage() except CalledProcessError: for root, _, files in os.walk(os.getcwd()): ...
def check_call_cmd(*cmd, **kwargs): """ Verbose prints the directory location the given command is called from and the command, then executes the command using check_call. Parameter descriptions: dir Directory location command is to be called from cmd List of par...
The main task of the code is to configure a CMake build with Clang compilers, run `clang-tidy` for static analysis on the project, and execute additional tools like Valgrind, coverage checks, and `cppcheck` for comprehensive code quality analysis. It creates a temporary build directory, sets up Clang-specific compilati...
def analyze(self): if os.path.isfile(".clang-tidy"): with TemporaryDirectory(prefix="build", dir=".") as build_dir: # clang-tidy needs to run on a clang-specific build check_call_cmd( "cmake", "-DCMAKE_C_COMPILER=clang", ...
def _maybe_valgrind(self): """ Potentially runs the unit tests through valgrind for the package via `meson test`. The package can specify custom valgrind configurations by utilizing add_test_setup() in a meson.build """ if not is_valgrind_safe(): sys.stderr.wr...
The code's main task is to analyze code quality by running clang-tidy (if configured), static analysis with scan-build, sanitizer tests (address/undefined), coverage checks, and cppcheck. It conditionally executes these steps based on project configuration files (.clang-tidy, .openbmc-no-clang) and environment safety, ...
def analyze(self): self._maybe_valgrind() # Run clang-tidy only if the project has a configuration if os.path.isfile(".clang-tidy"): os.environ["CXX"] = "clang++" with TemporaryDirectory(prefix="build", dir=".") as build_dir: check_call_cmd("meson", "setu...
def Si_chip(techs, types, areas,scaling_factors,Transistors_per_gate=8,Power_per_core=10,Carbon_per_kWh=700,packaging=False, always_chiplets=False,wastage_add = False,wafer_dia=450, rcy_mat_frac = 0,rcy_cpa_frac = 0.4): area = np.array(areas) cpa = np.array([scaling_factors['cpa'].loc[c, 'cpa'] for...
This function calculates the total carbon footprint of chip designs by evaluating manufacturing, packaging, operational power, and lifecycle factors across multiple technology combinations. It computes emissions from silicon chips, interposers, application development, and recycling, returning detailed carbon dataframe...
def calculate_CO2(design, scaling_factors, techs, design_name='', num_iter=90, package_type='RDL', always_chiplets=False, lifetime = 2*365*24, activity=[0.2, 0.667, 0.1], Ns = 1e5, Nc=None, plot=False,package_factor=1, return_ap=False, in_combinations=None, transistors_per_gate=8, po...
def load_heap() -> DHeap: """ Get input necessary to amke a heap from user (d, file with list) and make a max heap. :return: Created max heap object. """ d = get_d_from_user() filename = get_file_name_from_user() print(f"Reading heap from path {filename}...") input_list = get_list_from_f...
The main task of the code is to create a user interface loop that allows users to interact with a heap data structure. It displays the heap as a tree or list based on size, presents a menu of actions, executes user-selected operations (e.g., reloading the heap or performing heap-specific tasks), and handles errors grac...
def user_loop(): """ Main loop of the user interface. Will create the heap with user input, and allow the user to make actions on the heap until the user chooses to exit. """ print(BANNER) heap = load_heap() while True: if heap.heap_size > MAX_TREE_DISPLAY_ITEMS: print("...
def get_hour(): """ Sets a varialbe with the local hour number to read the correct forecast time. """ rtc = machine.RTC() current_time = rtc.datetime() current_hour = current_time[4] if DEBUG == 1: print(f"Unadjusted Hour = {current_hour}") if current_hour == 0: curr...
The main task of the code is to periodically fetch weather data from the Open-Meteo API at set intervals, update NeoPixel LED strip brightness and colors based on the weather conditions, and handle API errors. The loop checks elapsed time to trigger API requests, processes the weather data, adjusts LED settings, and re...
def main_loop(): """ Main program loop. """ # Add access to write the 'global' API timer global api_request_timer while True: try: # Check if the timer has elapsed to make an API request current_time = utime.time() if DEBUG == ...
def y_blocks(self): if self.x_blocks() == 0: return 0 return len(self.cells[0]) def x_blocks(self): return len(self.cells) def live_in_next(self, x, y): n = self.num_live_neighbours(x, y) if self.is_live(x, y): if n == 2 or n == 3: return T...
This code computes the next state of a cellular automaton grid. It creates a new 2D boolean array where each cell's value is determined by the `live_in_next` method, which likely evaluates neighbor states. The grid is then updated to this new state, representing one iteration of the automaton's evolution.
def next_interation(self): new = [[False for j in range(self.y_blocks())] for i in range(self.x_blocks())] for x in range(self.x_blocks()): for y in range(self.y_blocks()): new[x][y] = self.live_in_next(x, y) self.cells = new
def _create_graph_form_file(self, graph_file): G = nx.DiGraph() process_weights = True with open(graph_file) as f: print("READING GRAPH FROM FILE") for line in f: if line == '\n': process_weights = False elif process_wei...
This code processes a directed graph to identify the critical path in a project schedule. It initializes a graph from a file, verifies it's a DAG, computes topological order, calculates earliest/latest execution times, identifies critical nodes/edges, and outputs the critical path.
def __init__(self, graph_file): self.nodes_dict = defaultdict(dict) self.graph = self._create_graph_form_file(graph_file) self._is_dag(self.graph) self.topological_sort = self._get_topological_order() self._compute_earliest_execution() self.critical_nodes, self.critical_e...
def _create_graph_form_file(self, graph_file): G = nx.DiGraph() process_weights = True index = 0 with open(graph_file) as f: print("READING GRAPH FROM FILE") for line in f: if line == '\n': process_weights = False ...
The code initializes a graph from a file, constructs a directed acyclic graph (DAG) structure, verifies the graph's DAG property, and prepares to compute a modified topological order for task scheduling or dependency resolution.
def __init__(self, graph_file): self.nodes_dict = defaultdict(dict) # defaultdict(lambda: defaultdict(list)) self.graph = self._create_graph_form_file(graph_file) self._is_dag() self.task_order = None self._compute_d_modified()
def get_COGS_proper(to_upper=False): # Return list of all proper nouns in COGS # if to_upper=True, convert list to uppercase with open('COGS/vocab_proper_nouns.txt','r') as fid: words = fid.readlines() words = [w.rstrip('\n').strip() for w in words] words = [w for w in words if len(w)>0]...
This code initializes a DataCOGS dataset loader for a model that uses support examples and queries, configuring parameters like data split mode, word permutation types, and vocabulary mappings. It loads training/test data, sets up word sets (WI/WO) for permutation, validates token consistency, and prepares input/output...
def __init__(self, mode, remap_type, support_type='targeted', ns=my_ns_default, inc_support_in_query=True, p_shuffle=0.95, p_make_all_proper=0.01): # Input # mode : specifies split to use for queries ['train','test_iid','gen_lexical','gen_structural','dev','dev_tiny'] # remap_type : specifie...
def readfile_cogs(fn_in, make_output_upper=True): # Read COGS dataset from text file # # Input # fn_in : filename to read # make_output_upper (default=True) : convert the output tokens to uppercase, in order to # break correspondence with identical input tokens # # Output # Pa...
This code initializes a dataset handler for the COGS benchmark, loading task-command/output pairs based on the specified mode (train/test). It processes input/output sequences, computes maximum lengths, and prepares vocabulary structures for language modeling. The class supports multiple evaluation modes and sets up sy...
def __init__(self, mode): # Input # scan_type : name of scan split # mode : 'train' or 'test' # inc_support_in_query : (default=False) include all support examples as queries? If True, it messes up the log-likelihood calculations. assert mode in ['train','test_iid','gen_lex...
def clear_console(): os.system('cls' if os.name == 'nt' else 'clear') def startup(): print( """ _______ _ _______ _ _________ _______ _______ _______ _________ ______ ______ ( ___ )( ( /|( ___ )( ( /|\__ __/( )( ____ \|\ /|( ___ )\__ __/( __...
This code implements a command-line interface with tab completion, database connectivity, and keyboard input handling. It connects to an SQLite database, processes user input (including backspace, space, and Enter), and executes commands. The loop handles key events for editing commands, using tab for auto-completion, ...
def main(): clear_console() startup() global con global c con = sqlite3.connect(DB_PATH) c = con.cursor() cmd = "" temp = [] tempIdx = 0 write = sys.stdout.write print("> ", end="", flush=True) while True: key_event = keyboard.read_event(suppress=True) if ...
def set_start_state(self, joint_config=None, group_id=0): """ Set the starting state from which to plan Sets the MoveIt! starting position in preparation for planning Parameters ---------- joint_config (RobotState) -- the starting configuration to plan from....
The function plans a trajectory using MoveIt! to reach a specified joint configuration. It accepts a target as a list or dictionary of joint positions, an optional starting configuration, and a group ID. If no starting config is provided, it uses the robot's current state. The method returns a RobotTrajectory plan to a...
def plan_joint_pos(self, target, starting_config=None, group_id=0): """ Plan a trajectory to reach a given joint configuration Uses MoveIt! to plan a trajectory to reach a given joint configuration Parameters ---------- target : list or dict if a lis...
def plan_joint_waypoints(self, targets, group_id=0, starting_config=None): '''Generates a multi-segment plan to reach waypoints in joint space Uses MoveIt! to generate a plan from target to target. One plan is generated for each segment. .. warning:: The plans can be stitched t...
The main task of the code is to generate a multi-segment trajectory plan using MoveIt! to reach specified waypoints in either joint or end-effector space. It produces individual plans for each segment or merges them into a single trajectory, with a warning about potential acceleration limit issues when merging. The fun...
def plan_waypoints(self, targets, is_joint_pos=False, merge_plans=False, starting_config=None, group_id=0): '''Generates a multi-segment plan to reach waypoints in target space Uses MoveIt! to generate a plan from target to target. One plan is generated for each ...
def strongest_tap(est,n_strong,N_e,K,L,N_regions=100,M=2): time_h = np.fft.ifft(est,K,axis=0)[:L,:] strongest_tap = np.argsort(np.abs(time_h),axis=0)[-1*n_strong:,:].reshape(N_e,n_strong) top_time_h = np.zeros((n_strong,N_e),dtype=complex) for i in range(N_e): top_time_h[:,i] = time_h[strongest_...
The function `return_rate_strongest_tap` computes the normalized data rate (in Gbps) by first determining the strongest tap configuration (`Theta`) using `strongest_tap`, then calculating the cascaded channel matrix `G` and data rate `R` with `calculate_cascaded` and `calculate_datarate`, finally dividing `R` by $10^8$...
def return_rate_strongest_tap(H,N_e,K,L,sig,M=2): Theta = strongest_tap(H,1,N_e+1,K,L,N_regions = 100,M = M) # est,n_strong,N_e,K,L,N_regions=100,M=2 #Theta = vector_heuristic(H,M) G = calculate_cascaded(H,Theta) R = calculate_datarate(G,sig) return R/10**8
def initialize(self): """Initialize deviceInfo and available events.""" device_info = self.get_device_info() self.device_info=device_info if device_info is None: self.name = None self.cam_id = None self.event_states = None return ...
The main task of the code is to maintain an event stream connection with a camera device, process real-time alert notifications via XML parsing, handle connection failures with retries, and manage thread termination signals (kill/reset events). It continuously monitors the stream, initializes device info, and triggers ...
def alert_stream(self, reset_event, kill_event): """Open event stream.""" _LOGGING.debug('Stream Thread Started: %s, %s', self.name, self.cam_id) start_event = False parse_string = "" fail_count = 0 url = '%s/ISAPI/Event/notification/alertStream' % self.root_url ...
def hex2words(he): global GF256 he = [int("0x" + he[i: i+2], 16) for i in range(0, len(he), 2)] he = [GF256(list(he[i: i+4])) for i in range(0, len(he), 4)] return he def keyExpansion(key): i = 0 res = [] while(i < 8): res.append(key[i].copy()) i += 1 while(i < 60): ...
This code implements AES-256 encryption (ch=1) and decryption (ch=2) using Galois Field GF(2⁸) arithmetic. It performs key expansion, rounds of substitution, shifting, mixing columns, and key addition for encryption, while decryption uses inverse operations in reverse order. The function converts hex inputs to word arr...
def AES256(key, msg, ch): ''' ch=1 for Encryption ch=2 for Decryption ''' global GF256 GF256 = galois.GF(2**8, irreducible_poly=0x11b) num_of_rounds = 14 msg = hex2words(msg) key = hex2words(key) key = keyExpansion(key) if ch == 1: key_0 = key[:4] msg = add...
def _create_index(self, dst: str, depth: int, title: str) -> str: index = "/".join([self._dst, dst]) if dst != "." else self._dst assets = "/".join([".."] * (depth - 1)) if index not in self._indices: with mkdocs_gen_files.open(f"{index}/index.md", "a") as fh_index: m...
This code generates documentation examples by processing `.mjs` files from the source directory, organizing them into groups based on their folder structure, and creating index entries. It handles subfolder merging, checks for duplicates, extracts content/data, and generates output files with proper navigation paths ac...
def generate(self) -> None: # pylint: disable=too-many-locals config = MkdocsConfig.load(MKDOCS_PATH / "mkdocs.yml") dst = "." depth = self._depth index = self._create_index(dst, depth, self._name) groups = {} items = list(self._src.rglob("*.mjs")) items....
def _draw_left_arrow(self, screen): arrow = Sprite(files('resources')/"arrow_left.png", ARROW_LEFT_X, ARROW_Y) arrow.draw(screen) def _draw_righ_arrow(self, screen): arrow = Sprite(files('resources')/"arrow_right.png", ARROW_RIGHT_X, ARROW_Y) arrow.draw(screen) def _draw_period(self, scr...
The code renders UI elements for an experience entry, displaying navigation arrows (left/right) based on the selected item's position. It draws a period separator and conditionally renders experience details (title, company, description, keywords) if the entry is unlocked; otherwise, it shows a locked experience indica...
def draw(self, screen): self.line_count = 0 experience = self.config[self.selected_id] if self.selected_id > 0: self._draw_left_arrow(screen) if self.selected_id < len(self.config) - 1: self._draw_righ_arrow(screen) self._draw_period(screen) if "un...
def createlist(): for i in range(1,12,1): shuru.append(i) def SetMaxi(x): return x def SetTotalGhurbe(x): return x def FCHC(shuru, totcost, pashe, maxi, totalghurbe): now=shuru notun_cost = totcost(now) xx = 0 temp1 = [] while True: if newFun(xx,maxi,notun_cost,...
The code's main task is to determine the optimal position and solutions using the FCHC algorithm with constraints (maxi=500, totalghurbe=13). It initializes parameters, runs the algorithm, and prints the optimal result along with individual case solutions and their corresponding negative total costs.
def f(): createlist() maxi=SetMaxi(500) totalghurbe=SetTotalGhurbe(13) ans, temp1 = FCHC( shuru, totcost, pashe, maxi, totalghurbe) print("Optimal position : ", ans,"\nSolution:\n") for xx, pos in enumerate(temp1): print("Case ", xx + 1, ":", pos, ":", -totcost(po...
def _data_processing(config, params): config.batch_shape = params.get('batch_shape', (50, 50)) config.num_chunks = params.get('num_chunks', 1) image_bits = params.get('image_bits', 8) config.preprocess_fn = tools.bind( tools.preprocess.preprocess, bits=image_bits) config.postprocess_fn = tools.bind( ...
The function `make_config` constructs a configuration object by merging default parameters with provided ones, initializes components like data processing, model architecture, tasks, loss functions, and training schedules, validates parameter usage, and raises errors for unused overrides. It ensures all configuration k...
def make_config(params): config = tools.AttrDict() config.debug = params.get('debug', False) with params.unlocked: for name in params.get('defaults', ['dreamer']): for key, value in DEFAULTS[name].items(): if key not in params: params[key] = value config.loss_scales = tools.AttrDict(...
def expand_node(self, node): moves = self.get_legal_ops(node) for move in moves: state = self.sim_action(str(move), node.state, node.piece) node.successors.append(self.create_successor(node, state, move)) def selection(self, node): leaf = node while not self.is_le...
The code performs Monte Carlo Tree Search (MCTS) to determine the optimal move in a game. It initializes a root node, expands it, and iterates 5000 times to simulate and backpropagate results. Afterward, it calculates the win rate for each child node of the root, selects the move with the highest win rate, and returns ...
def search(self, state, piece): root = MCNode(state, None, piece) self.expand_node(root) i = 0 while i < 5000: leaf = self.selection(root) sim_result = self.rollout(leaf) self.backprop(sim_result) i += 1 scores = [] print("...
def get_dataframes(post_file, stock_file): post_df = pd.read_csv(post_file) stock_df = pd.read_csv(stock_file) return post_df, stock_df def merge_dfs(post_dfs, stock_dfs): data_set = [] schema = None schema_has_been_retrieved = False for index, row in stock_dfs.iterrows(): date = row...
The main task of the code is to process and merge data from two files into a structured dataset. It retrieves DataFrames from `post_file` and `stock_file`, merges them into a unified schema and dataset, then exports the merged data to a CSV file at `../data/data_set.csv` for storage or further analysis.
def main(): post_dfs, stock_dfs = get_dataframes(post_file, stock_file) schema, data_set = merge_dfs(post_dfs, stock_dfs) write_data_set(schema, data_set, "../data/data_set.csv")
def valid_moves(board): moves = [] for i, row in enumerate(board): for j, move in enumerate(board[i]): if move == '.': moves.append((i,j)) return moves def score_board(board) -> int: score = (0,0) #rows for row in board: score = add_tuples(score, score_line(row)) #columns for i in range(4): score =...
This function implements the minimax algorithm for a two-player game, recursively evaluating all valid moves. It alternates between maximizing and minimizing scores based on the current player, simulating game states by placing pieces and backtracking. When no moves remain, it calculates the board score difference (pla...
def minimax(board, player, opponent): moves = valid_moves(board) if len(moves) == 0: final_children.append(copy.deepcopy(board)) scores = score_board(board) final_scores.append(scores) return scores[0] - scores[1] max_score = -9999 min_score = 9999 for move in moves: board[move[0]][move[1]] = player ...
def cross_validation_split(dataset, n_folds): ''' Splits up data into an array of n_folds pandas.Dataframes ''' dataset_copy = dataset.copy() shuffled = dataset_copy.sample(frac=1) return np.array_split(shuffled, n_folds) def knn(train, test, k): ''' Gets classification for all instances...
This function evaluates the KNN algorithm's accuracy using cross-validation. It splits the dataset into multiple folds, iteratively trains on all but one fold, tests on the excluded fold, and calculates accuracy for each fold. The process repeats for all folds, collecting accuracy scores to assess the model's performan...
def evaluate_knn(dataset, n_folds, k): ''' Runs KNN and evaluates against cross_validation sets ''' # get a split of data folds = cross_validation_split(dataset, n_folds) scores = [] for i, fold in enumerate(folds): fold_copy = folds.copy() # remove 1 item from each split ...
def get_send_keys(connection, _address): """ The function handle the keys transfer from the server :param connection: The connection :param _address: the user information :return: Nothing important """ client_public_key = decrypt(connection.recv(2048), public_...
The function handles multi-client communication by receiving, decrypting, and responding to client messages. It processes commands like 'users' (showing online users) or 'q' (exit), echoes data back, and securely encrypts responses. On disconnection, it closes the connection, updates thread count, and prints logs.
def multi_threaded_client(connection, _address): """ The function handle all the multi client threads :param connection: the connection :param _address: the user information :return: None """ start_len = '' try: start_len = get_send_keys(connection, _address) user_info = ...
def bind_connection(host, port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # connect to server on local computer sock.connect((host, port)) return sock def set_my_public_key(my_key): global my_public_key my_public_key = my_key def get_key(): password = ''.join([random.choice(s...
The main task of the code is to establish a secure communication channel between a client and server using asymmetric encryption. It binds a socket, exchanges public keys, encrypts and sends messages using both parties' keys, handles key setup, and receives/transmits data. The process involves key exchange, encryption,...
def main(): sock = bind_connection('127.0.0.1', 2004) set_my_public_key(get_key()) send_message(encrypt(my_public_key, server_public_key), sock) try: set_server_private_key(sock.recv(2048)) except Exception as error: print(error, file=sys.stderr) return set_my_private...
def get_merged_tag_metas(config): dst_tag_metas = [] to_skip = set() for first_name, second_names in config.items(): for second_name in second_names: to_skip.add(second_name) for first_name, second_names in config.items(): if len(second_names) > 0: to_skip.discard...
The code migrates data from a source project to a destination project by creating new datasets, converting annotations using a config, and handling both image and video data. It processes images in batches, updates annotations, uploads them, and yields progress. For videos, it converts annotations and appends them to n...
def run(config): dst_tag_metas = get_merged_tag_metas(config) dst_project_meta = get_merged_project_meta(dst_tag_metas) dst_project = create_project(dst_project_meta) g.dst_project_info = dst_project for ds_info in g.api.dataset.get_list(g.project_id): dst_dataset = g.api.dataset.create(ds...
def _process_settings(self): """Process any settings that are not set""" if not self.copyright: self._generate_copyright if not self.description: self.description = "Fill in description" if not self.title: self.title = self.package def _setup_dir(self): """Create the directory for ...
The code generates a project structure by creating directories, processing templates for essential files (e.g., requirements.txt, setup.py), and setting up documentation (Sphinx) and test frameworks, based on predefined project settings.
def generate(self): """Based on the project settings generate the project""" self._process_settings() if not self._setup_dir(): return False # Create package directory os.mkdir(os.path.join(self.path, self.package)) self.process_template("requirements.txt") self.process_template("setu...
def prompt_str(self, prompt, attr, default=None): """Prompt a user for a value :param prompt: The prompt to print :param attr: Where to put the result :param default: What the default should be if the user just presses enter. """ setattr(self, attr, self.ask_str(prompt, default=default)) def pr...
The main task of the code is to collect user input for project details like title, package name, authors, description, and copyright, then generate a configuration or setup using the collected values. It prompts the user interactively and returns the result of the generation process.
def wizard(self): """This will ask the user what the values should be for the project :return: True on success, False otherwise """ self.prompt_str("Project Title", "title") self.prompt_str("Project package name", "package") self.prompt_multi("Authors", "authors") self.prompt_str("Brief Des...
def print_queue_status(): global delivery_queue global delivery_2nd_attempt print ("Delivery Queue: ", delivery_queue) print ("Delivery 2nd: ", delivery_2nd_attempt) def deliver_n_check(name_input): # head to location based on name, check if person there by looking for green box global conn ...
The main task of the code is to process delivery tasks from a queue, attempting to deliver items and updating their status to 'completed' in a database upon successful delivery. If delivery fails initially, items are moved to a second-attempt queue for retry. The function handles both first and second delivery attempts...
def multiple_delivery(): global delivery_queue global delivery_2nd_attempt global conn while len(delivery_queue) > 0: print_queue_status() k = delivery_queue.pop(0) if not deliver_n_check(k): print("NOT delivered, will try again!") delivery_2nd_attempt.ap...
def get_dict_list(book_name): refbk = open_workbook(book_name) refst = refbk.sheet_by_index(0) disc_list = [] for attribute_index in range(1, refst.ncols): disc_list.append(buildDict(attribute_index, refst, 0)) return disc_list def gen_vector(book_name, contList, discList): book = open_workbook(book_name) shee...
The code processes a training dataset from an Excel file, extracts continuous and discrete property features, generates feature vectors, and saves them as separate CSV files for training purposes.
def gen_train(filename='training_set3.xlsx', output=0): contList = get_dict_list('continousproperty.xlsx') discList = get_dict_list('discrictproperty.xlsx') cexamples, dexamples = gen_vector(filename, contList, discList) write_to_csv('c_{}_train'.format(output), cexamples) write_to_csv('d_{}_train'.format(output),...
def get_dict_list(book_name): refbk = open_workbook(book_name) refst = refbk.sheet_by_index(0) disc_list = [] for attribute_index in range(1, refst.ncols): disc_list.append(buildDict(attribute_index, refst, 0)) return disc_list def gen_vector(book_name, contList, discList): book = open_workbook(book_name) shee...
The code generates test data from Excel files by loading continuous and discrete property dictionaries, creating vectorized examples from a test dataset, and saving them as CSV files named with an output identifier.
def gen_test(filename='Testing_set3.xlsx', output=0): contList = get_dict_list('continousproperty.xlsx') discList = get_dict_list('discrictproperty.xlsx') ctexamples, dtexamples = gen_vector(filename, contList, discList) write_to_csv('c_{}_test'.format(output), ctexamples) write_to_csv('d_{}_test'.format(output), ...
def prime_norm_representative(I, O, D, ell): """ Given an order O and a left O-ideal I return another left O-ideal J in the same class, but with prime norm. This corresponds to Step 1 in the notes. So given an ideal I it returns an ideal in the same class but with reduced norm N where N != ell is ...
The function `special_ell_power_equiv` solves the **ell-isogeny problem** for a special order $ O $ in a quaternion algebra. Given a left $ O $-ideal $ I $, it computes a pair $ (J, \delta) $, where $ J = I \cdot \delta $ is a nonfractional ideal in the same ideal class as $ I $, and $ J $ has an **ell-power norm** (i....
def special_ell_power_equiv(I, O, ell, print_progress=False): """Solve ell isogeny problem where O is a special order. Args: I: A left O-ideal. O: A special order in a quaternion algebra. ell: A prime. print_progress: True if you want to print progress. Returns: A p...
def setup_logger_local(mname): level = logging.INFO hdlr = logging.FileHandler(mname) logging.captureWarnings(capture=True) logger = logging.getLogger() FORMAT = logging.Formatter("%(asctime)-1s : %(process)d : %(levelname)-2s : %(message)s") hdlr.setFormatter(FORMAT) ...
The main task of the code is to configure environment variables, initialize logging, fetch database details, download an artifact with checksum tracking, process log files, update checksum records, and clean up temporary files. It handles errors by logging exceptions and raising them. Global variables are used to store...
def main(): global FMTWRP_GATEWAY_ORAUSERID global FMTWRP_GATEWAY_ORAPASSWD global TWO_TASK global feed_file_name global json_file_name global FMTWRP_ENV_LGFRM global consumer_location global FMTWRP_AUTH_USER global FMTWRP_ARTIFACT_PASSWD global fmtwrp_bucket_name global FMTW...
def create_records(self) -> None: """Function responsible to create records to .csv file""" try: # starting the procedure of fill up each row print('########## Add as many register as you need ##########') # question to column 1 self.list_name.append(input...
The main task of the code is to collect and confirm multiple records through a loop, then generate a CSV file with specified columns (name, group, elimination, sport) using the `create_file` method. It uses `create_records` to input data, `confirmation_records` to validate entries, and handles errors during the process...
def create_content(self) -> None: """Function responsible to receive all information to each column in file .csv""" try: # creating the flag variable to control the flow inside the while flag = True while flag: # call the method self.create_records() ...
def sample_location(): u = random.uniform(0, 1) v = random.uniform(0, 1) theta = 2 * math.pi * u phi = np.arccos(2 * v - 1) x = VENUS_RADIUS * np.sin(phi) * np.cos(theta) y = VENUS_RADIUS * np.sin(phi) * np.sin(theta) z = VENUS_RADIUS * np.cos(phi) return [x, y, z] def sim_timebins(resu...
The main task of the code is to generate random resurfacing events with cumulative area ≥1, sort them chronologically, add start/end markers, compute crater distributions using simulation, count classification frequencies, and visualize the results. It models planetary resurfacing processes by creating synthetic event ...
def main(): resurfacing_events: list[ResurfacingEvent] = [] while sum(ev.area for ev in resurfacing_events) < 1: this_event = ResurfacingEvent( year=random.uniform(0, SIM_LENGTH), loc=sample_location(), area=random.choice(RESURFACING_AREAS), ) resurfa...
def is_joint_axis(self, indexes): [a, b, c] = indexes joint_axis1 = self.find_joint_axis(a, b) joint_axis2 = self.find_joint_axis(b, c) if (joint_axis1 and joint_axis2) and joint_axis2 == joint_axis1: return True return False def find_sticking(self, sign, i, sticking_...
This function executes a rotation action on a 3D structure based on given indices and degree, validating the move. It handles joint axes with sticking cubes, reverses invalid moves, and returns success/failure status.
def take_action(self, action): print('take action', action) (i, j, degree) = (action['index1'], action['index2'], action['degree']) coords_backup = self.coords[:] if min(i, j) == i: begin = i - 1 end = i third = j if begin < 0: ...
def setup_args(): parser = ArgumentParser(description='Arguments for talking to vCenter') parser.add_argument('-s', '--host', required=True, action='store', help='vSphere service to connect to.') parser.add_argument('-o', '--port', ...
This code connects to a vSphere server, configures datacenter/resource pool/datastore, imports a VM from an OVA file using OVF Manager with network/property mappings, checks for errors, and deploys the VM via HTTP NFS lease, returning success/failure status.
def main(): args = setup_args() try: si = SmartConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=args.port) atexit.register(Disconnect, si) except Exception as e: print("Un...
def getOriginalImage(imgName): imgPath = f"puzzles/{imgName}.jpg" img = cv2.imread(imgPath) # img = cv2.resize(img, (0, 0), fx=0.2, fy=0.2) img = cv2.resize(img, (0, 0), fx=0.4, fy=0.4) return img def showImg(title, img): cv2.imshow(title, img) cv2.waitKey(0) cv2.destroyAllWindows() def ...
The code processes a Sudoku image by thresholding, detecting grid borders, extracting the grid, splitting it into cells, recognizing digits, and displaying each step to solve or analyze the Sudoku puzzle.
def getBoard(): # Get the original img originalImg = getOriginalImage("multiple") showImg("Original", originalImg) # Set Thresholds up on the img preProcessedImg = preProcessImage(originalImg) showImg("After Thresholding", preProcessedImg) # Get the sudoku grid borders gridWithBorder, ...
def deploy_voting_contract(): priv, pub = generate_keypair(128) encrypted_zero = encrypt(pub, 0) contract = VotingContract.deploy(pub.n_sq, encrypted_zero, {"from": admin}) return priv, pub, contract def cast_vote(voter, vote, contract, pub): # (yx, yy) = contract.Y() encrypted_vote = encrypt(pu...
The main task of the code is to deploy a voting contract, cast votes using a generated keypair, and decrypt the encrypted vote sum. It initializes a contract, simulates voting with predefined values, and retrieves the decrypted result. The code demonstrates a basic voting system with encryption and decryption processes...
def main(): priv, pub, contract = deploy_voting_contract() print( f"Generated keypair and deployed contract on address {contract.address}") vote1 = 9 vote2 = 11 vote3 = 1 print("Casting votes:") cast_vote(voter1, vote1, contract, pub) # cast_vote(voter2, vote2, contract, pu...
def extract_text_and_emotion_labels(loaded_json_data): X = [] # text of tweets y = [] # emotion labels for e in loaded_json_data: X.append(e["text"]) y.append(e["emotion_label"]) return X,y def load_json_file(json_data): jsonfile = open(json_data) jsonload = json.load(jsonfile) ...
This function preprocesses tweets for high-gram models by cleaning text (removing hashtags, URLs, newlines), normalizing punctuation, replacing usernames, generating emotion labels via EmoLex, and creating stemmed word features with placeholders. It returns processed text features, original emotion labels, and EmoLex-d...
def preprocess_tweet_highgram(): X, y = extract_text_and_emotion_labels(load_json_file("wassa2017[tra-devsets].json")) X_preprocessed = replace_usernames(add_whitespace_before_and_after_punctuation_for_tweets(remove_hashtag_symbols(remove_abundant_new_line_symbols(tag_URLs(X))))) y_wassa_emolex = emolex...
def preprocess_tweet_highgram(): X, y = extract_text_and_emotion_labels(load_json_file("wassa2017[tra-devsets].json")) X_preprocessed = replace_usernames(add_whitespace_before_and_after_punctuation_for_tweets(remove_hashtag_symbols(remove_abundant_new_line_symbols(tag_URLs(X))))) y_wassa_emolex = emolex...
The main task of the code is to preprocess and merge Twitter and Instagram datasets for a high-gram emotion analysis model. It retrieves processed features (Xtweet, Xinsta), labels (ytweet, yinsta), and emotion lexicon data (ytweet_emolex, yinsta_emolex) from separate functions, then combines them into a unified datase...
def preprocess_emotion_dataset(): Xtweet, ytweet, ytweet_emolex = preprocess_tweet_highgram() Xinsta, yinsta, yinsta_emolex = preprocess_annotated_instagram_highgram() merged_X, merged_y, merged_emolex = merge_twitter_annotated_instagram_for_highgram_model(Xinsta, yinsta, yinsta_emolex, Xtweet, ytweet, ytwe...
def git(*args: str, working_folder: Path) -> list[str]: """command runnig the git cli.""" return run_subprocess("git", *args, working_folder=working_folder) def git_branch(working_folder: Path) -> list[str]: # git branch --format="%(refname:short),%(upstream),%(upstream:track,nobracket)" return git( ...
The function retrieves local Git branch information from a specified or default working directory, synchronizes with remote repositories by pruning stale branches, parses each branch's details into a structured format, and returns a dictionary mapping branch names to their corresponding parsed information.
def branch_info(working_folder: Path | None) -> dict[BranchName, BranchInfo]: branch_info = {} if working_folder is None: working_folder = Path.cwd() # prune it first to sync remote with local. git("fetch", "-p", working_folder=working_folder) for info in git_branch(working_folder): ...
def get_cells(matrix, markers, i, j): num_rows = len(matrix) row_start = i - 1 if i > 0 else i row_end = i + 1 if i < num_rows - 1 else i col_start = j - 1 if j > 0 else j col_end = j + 1 if j < len(matrix[0]) - 1 else j cells = [] for row in range(row_start, row_end + 1): for col i...
The function performs backtracking to solve a constraint satisfaction problem on a matrix. It recursively explores valid configurations by marking cells, checking combinations, and backtracking if a configuration fails validation. The goal is to find a valid arrangement of markers that satisfies the matrix constraints,...
def brute_force(matrix, markers, num_rows, num_cols, i, j): # looped through the entire matrix. if i == num_rows and j == num_cols: return validate(matrix, markers, num_rows, num_cols) # empty cell or cell banned. if matrix[i][j] == -1 or matrix[i][j] == 0: next_i, next_j = calc_next_in...
def display_menu(): """ Displays the menu of options. """ print("\nPlease select one of the following options.\n") # Complete according to the output sample in the handout print(MEMBER_INFO + ". Show a member's information \n" + NUM_OF_FRIENDS + ". Show a member's number of friends\n" ...
The main task of the code is to handle user interactions in a social network application by displaying a menu, processing user selections, and executing corresponding actions such as retrieving member information, managing friendships, recommending connections, visualizing networks, and saving changes. It operates on m...
def select_action(profile_list: List[Member], network: Dict[int, List[int]], similarity_matrix: List[List[int]]) -> str: """ Asks the user to select an action. """ response = display_menu() print(LINE) size = len(profile_list) if response in [MEMBER_INFO...
def fileReader(comp): get_historical_data(comp) with open('../Service/static/data/' + comp + '_historical_data.json', 'r', encoding='utf-8') as f: data = json.load(f) testJson = data stock_price_open = [] stock_price_close = [] stock_price_high = [] stock_price_low = [] stock_vol...
The code retrieves historical and real-time stock data, calculates technical indicators (EMA, MACD), fetches predictive analysis and historical statistics (high, average, low), and compiles the results into a JSON response containing price/volume data, predictions, and advisory suggestions for a given stock symbol.
def company(): ops = request.args.get('ops') stock_price_close, stock_price_high, stock_price_low, stock_volume, stock_date, ema12, ema26, diff, dea = fileReader(ops) volumn, price, time = realTimeReader(ops) # closePrice is the real time data closePrice = float(price[len(volumn) - 1]) highPric...
def __compare_by_priority(self) -> Optional[Player]: sorted_ranks1 = self.__sort_by_frequency(hand=self.player1.hand) sorted_ranks2 = self.__sort_by_frequency(hand=self.player2.hand) return self.__compare_ranks(list1=sorted_ranks1, list2=sorted_ranks2) def __compare_straight(self) -> Optional[P...
This method determines the appropriate comparison strategy for players with the same poker hand type. It returns the result of either comparing by priority (for TWO_PAIR/FULL_HOUSE), comparing straight hands, or comparing by highest card value for other hand types.
def __compare_same_types(self, *, hand_type: str) -> Optional[Player]: if hand_type == "TWO_PAIR" or hand_type == "FULL_HOUSE": return self.__compare_by_priority() elif hand_type == "STRAIGHT": return self.__compare_straight() else: return self.__compare_by_...
def canEvolve(self, pokemon_names): x,y = self.find_in_names(pokemon_names) if y+1 < len(pokemon_names[x]): return True else: return False def get_candy_evolve(self): return self.candy_evolve def find_in_names(self, pokemon_names): x = 0 for i in p...
This code handles a Pokémon's evolution by checking if it can evolve, verifying sufficient candy count in the inventory, updating its name, type, CP, and stats upon successful evolution, and providing feedback to the user. If evolution isn't possible due to insufficient candies or lack of further evolution potential, i...
def evolve(self, inventory, pokemon_names, pokemon_types, cp_increase, stats_increment): if self.canEvolve(pokemon_names): if inventory[1][self.family].count >= self.get_candy_evolve(): inventory[1][self.family].count -= self.get_candy_evolve() self.candy_evolve = sel...
def clear_buffer(): try: import msvcrt while msvcrt.kbhit(): msvcrt.getch() except ImportError: import termios termios.tcflush(sys.stdin, termios.TCIOFLUSH) def random_pokemon(): evolution_chance = random.randint(0, 100) chosen_family = pokemon_names[random.ra...
The code simulates a Pokémon capture attempt where the player finds a random Pokémon, is prompted to capture it, and has 5 attempts with a 20% chance per attempt. If unsuccessful, the Pokémon runs away. The process includes user input validation, retry options, and handling outcomes like capture success or escape.
def attempt_capture(): clear_buffer() found_pokemon = random_pokemon() # If it is there if check_around_x('\033[1;31m?\033[0m'): print(f"You found a {found_pokemon}!") print("\nDo you want to attempt to capture it? It will run away if you don't.") # Prompt to catch while...
def move_map(direction): ''' In terms of directions, up and down are relatively the same, with only differences being the '-' or '+' Therefore, I will only include explanation of the 'up' and 'left' directions ''' # In order to move the map upwards if direction == 'up': # All the...
This code continuously checks for keyboard inputs to control a game map's movement (WASD), handle actions like capturing (F), accessing inventory (I), and fighting (G), while allowing the player to quit (Q). It processes inputs in a loop, updating the map and triggering corresponding functions with delays to prevent in...
def run(): # Consistently check for... while True: # 'WASD', all the movement keys # And so if the player moves if keyboard.is_pressed('w'): # Sleep for a small time to avoid lag and allow playability time.sleep(0.1) # Move the map up move_...
def load_game(self): """ Loads the game saved state into memory @return bool true if load was successful """ if os.path.isfile("save_file.pickle"): try: file = open("save_file.pickle", "rb") data = pickle.load(file) self...
This method resumes a saved game by loading the game state, resetting player save flags, and continuing gameplay. If setup is pending, it places remaining ships and starts the game. Otherwise, it resumes from the last player's turn, processing shots and saving if needed, then proceeds with the game.
def resume_game(self): """ Attempts to start a game saved in a file """ if self.load_game(): width = os.get_terminal_size().columns print("Game has successfully been loaded...".center(width)) #set up pause self.capture_pause() #reset save sta...
def has_pattern(self, decl_string): """implementation details""" assert utils.is_str(decl_string) last_part = decl_string.split('::')[-1] return ( -1 != decl_string.find(self.__begin) and - 1 != last_part.find(self.__end) ) def split(self, decl_string): ...
The code normalizes a declaration string by recursively processing its arguments, splitting the input into a name and arguments, normalizing each argument, and rejoining them with an optional separator. It returns the modified string if a pattern is detected, otherwise returns the original input.
def normalize(self, decl_string, arg_separator=None): """implementation details""" if not self.has_pattern(decl_string): return decl_string name, args = self.split(decl_string) for i, arg in enumerate(args): args[i] = self.normalize(arg) return self.join(n...
def eval_help() -> None: """ Prints information about the REPL system """ print("This is a Read-Eval-Print-Loop (REPL) system. Enter a command and a query for evaluation.\n" "Valid commands are:\n" f"{constants.COMMANDS}\n\n" f"Seperator token is '{constants.SEPERATOR}', e.g. use '...
The function `evaluate_command_and_query` executes the appropriate evaluation function based on the input `command` (e.g., "query," "describe database"), processes the associated `query` statement, and measures execution time. It initializes settings, prints a title, dispatches tasks to specific evaluation functions, a...
def evaluate_command_and_query(command: str, query: str) -> None: """ Calls the respective evaluation based on the command input :param command: str -- Command, e.g. 'query' :param query: str -- Corresponding query statement, e.g. 'select * from articles LIMIT 10' :return: None """ # Set pa...
def find_prefix_path(base_pat, tree_node): conditional_patterns = {} while tree_node is not None: prefix_path = [] ascend_tree(tree_node, prefix_path) if len(prefix_path) > 1: conditional_patterns[frozenset(prefix_path[1:])] = tree_node.count tree_node = tree_node.nod...
This function recursively mines frequent itemsets from an FP-tree by generating new itemsets from the current prefix and each item in the sorted header table, then building and mining conditional subtrees for each item to identify all frequent combinations meeting the minimum support threshold.
def mine_tree(tree_node, header_table, min_support, prefix, frequent_item_sets): bigL = [v[0] for v in sorted(header_table.items(), key=lambda p: p[1][0])] for base_pat in bigL: new_freq_set = prefix.copy() new_freq_set.add(base_pat) frequent_item_sets.append(new_freq_set) condit...
def create_item_counts(dataset): item_counts = {} for transaction in dataset: for item in transaction: if item not in item_counts: item_counts[item] = 1 else: item_counts[item] += 1 return item_counts def build_tree(dataset, min_support): h...
The code implements the FP-Growth algorithm to find frequent itemsets in a dataset based on a minimum support threshold. It first counts item frequencies, filters frequent items, constructs an FP-Tree, and recursively mines frequent itemsets from the tree structure. The function returns all itemsets meeting or exceedin...
def fp_growth(dataset, min_support): item_counts = create_item_counts(dataset) frequent_items = {item: count for item, count in item_counts.items() if count >= min_support} frequent_item_sets = [] if len(frequent_items) == 0: return frequent_item_sets fp_tree, header_table = build_tree(data...
def get_J1(state): [phi, the, psi] = state['theta'] [ophi, othe, opsi] = state['thetadot'] cphi = np.cos(phi) sphi = np.sin(phi) cthe = np.cos(the) sthe = np.sin(the) A = get_A(state) V = get_V(state) R_33_dot = - sphi * ophi * cthe - cphi * sthe * othe J = R_33_dot * np.dot(V, ...
The code defines a function `get_J` that calculates the sum of three components (`J1`, `J2`, `J3`) derived from a given `state` by calling separate sub-functions. It returns the aggregated result `J = J1 + J2 + J3` as the primary output.
def get_J(state): J1 = get_J1(state) J2 = get_J2(state) J3 = get_J3(state) J = J1 + J2 + J3 # print('J', J) return J
def xydddt(state, F): A = get_A(state) V = get_V(state) R = get_rot_matrix(state['theta']) R_33 = R[2][2] # print(R_3_xy_dot) mat = -F / m * R_33 * np.dot(V, A) return [mat[0][0], mat[1][0]] def alpha(state, i): [x, y, z] = state['x'] return np.array([[(x - cx) ** i / px ** 4, (y - ...
The function computes a scalar value L4hf_mat[0][0] by combining dynamic state variables (xd, yd, xdd, ydd, xddd, yddd), alpha functions, and the Jacobian matrix J through a weighted sum of matrix operations and dot products, likely for a control system or physics simulation involving force and acceleration terms.
def Lf4h(state, F): [xd, yd, zd] = state['xdot'] [xdd, ydd, zdd] = state['xdd'] [xddd, yddd] = xydddt(state, F) alpha_3 = alpha(state, 3) alpha_2 = alpha(state, 2) alpha_1 = alpha(state, 1) alpha_0 = alpha(state, 0) J = get_J(state) L4hf_mat = 4 * F / m * np.dot(alpha_3, J)\ ...
def Lf0h(state): [x, y, z] = state['x'] return 1 - (x - cx) ** 4 / px ** 4 - (y - cy) ** 4 / py ** 4 def Lf1h(state): [xd, yd, zd] = state['xdot'] alpha_3 = alpha(state, 3) hd_mat = - 4 * np.dot(alpha_3, np.array([[xd], [yd]])) return hd_mat[0][0] def Lf2h(...
The code solves a quadratic program (QP) to compute control inputs (ux, uy) for a dynamic system, incorporating state derivatives, Lie derivatives of a barrier function (h), and tunable coefficients (kxy_0–kxy_3). The QP enforces constraints derived from system dynamics and safety requirements, combining a cost functio...
def qp_xy(state, u): F = u[0] u_hat = np.array([[u[1]], [u[2]]]) h = Lf0h(state) dh = Lf1h(state) ddh = Lf2h(state) dddh = Lf3h(state, F) lf4h = Lf4h(state, F) lglf3h_hat = LgLf3h_uhat(state, u) print('hs:', h, dh, ddh, dddh, lf4h, lglf3h_hat) H_qp = lf4h +...
def init_state(): """Initialize state dictionary. """ state = {"x": np.array([0.2, 0.5, 1]), "xdot": np.zeros(3,), "xdd": np.zeros(3,), "theta": np.radians(np.array([0, 0, 0])), # ! hardcoded "thetadot": np.radians(np.array([0, 0, 0])) # ! hardcoded ...
The main task of the code is to simulate a quadrotor's motion control system using PID controllers for position, velocity, and attitude. It initializes the robot's state, computes desired trajectories, applies control inputs (thrust and torque), updates the quadrotor dynamics, and logs position/velocity data for visual...
def main(): t_start = time.time() # Set desired position # Initialize Robot State state = init_state() # Initialize quadrotor history tracker quad_hist = QuadHistory() # Initialize visualization fig, (ax1, ax2, ax3) = plt.subplots(3) # Initialize controller errors integral...
def device_search(self): for p in serial.tools.list_ports.comports(): if p.pid == 4805 and p.vid == 1156: self.comport = p return True self.init_state = False return False def swich_to_scm(self): self.port.write(b'scm\r\n') for i in ran...
This code initializes an I2C communication interface by setting up device parameters, serial port connections, and error handling. It checks for device presence, configures memory address size, and handles SCM mode switching. Error messages are logged if devices are not found or memory address size retrieval fails. The...
def __init__(self): self.devices = [] self.set_dev = None self.scm = False self.mem_addr_size_16bit = None self.port= None self.comport=None self.init_state = False self.error_messages = [] self.dbg = False self.last_operation_status_code=N...
def create_variables(self): self.filename = None self.offset = tk.IntVar() self.offset.set(0) self.encoding = tk.StringVar() self.encoding.set(ENCODINGS[0]) def create_widgets(self): frame = self.frame = ttk.Frame(self.parent) self.openButton = ttk.Button(frame, t...
The code initializes a GUI component by setting up a parent reference, creating variables, widgets, layout, and event bindings. It also checks for command-line arguments to open a file if provided, performing initial setup and potential file loading during object creation.
def __init__(self, parent): self.parent = parent self.create_variables() self.create_widgets() self.create_layout() self.create_bindings() if len(sys.argv) > 1: self._open(sys.argv[1])
def model_marginal_llh_analytic_2x1D_PF_randomized_posterior_aswell(data, sigma_r, Sigma_0 = 1., N = 64, N2 = 64, verbose = True, ret_all_mmllhs = False): z = data['z'] r = np.array(data['r']) # inicializalas T = z.shape[0] # ezen a ponton 0 db adatpontot vettem figyelembe, ezek a prior adatai, ezek frissu...
The function `calc_mmllh_2task` computes the marginal maximum likelihood (mmLLH), posterior distributions, and predictive probabilities for models with two tasks ("2x1D" or "2x2D"). It supports marginalization over tasks using particle filters (PF) with specified particles, handling full or iterative evaluations. It re...
def calc_mmllh_2task(data, sigma_r, model, Sigma_0 = None, evaluation = "full", num_particles = 64, verbose = False, marginalize = True, posterior_prev = None, mmllh_prev = None, mmllhs_prev = None, prev_contexts = None, ret_all_mmllhs = False): ''' calculates the mmLLH, the posterior and the predicitive probabilit...
def cg_pos(data): '''Convers gps data to be in terms of local frame Assuming data is in dict defined in getData.gpsData.dataClean ''' x, y, _ = pm.geodetic2enu(data['latitude'], data['longitude'], data['el'], lat0, long0, h0, ell = wgs84) xC, yC = (data["x_gps_cg"]*np....
The code converts GPS data into state information for ACC/LK systems, computing road and vehicle states (position, velocity, curvature), relative positioning, yaw angles, and future path previews. It generates a state dictionary with parameters like lateral deviation (y), velocity (nu, mu), yaw rate (r), and curvature ...
def step(self, data): '''This takes gps data and converts it into state info''' # Convert GPS position to cg XY coordinate r_cg = cg_pos(data) rc, drc, kappa, road_left, s = self.get_road_state(r_cg) road_state = {} road_state['car_x'] = r_cg[0] road_state['car_y'...
def get_setup(): num_classes = 2 temp1 = 0.9 temp2 = 0.6 bandwidth = 0.001 num_bins = 15 num_samples = 5000 return num_classes, num_samples, num_bins, temp1, temp2, bandwidth def sample_points(num_samples, num_classes, temp1, temp2): logits_temp1 = [] samples = [] labels = [] ...
The code plots the Kernel Density Estimation Expected Calibration Error (KDE-ECE) against ground truth integrals for different convex functions ('l2' or 'kl') and sample sizes. It samples prediction scores, computes ECE estimates using Bregman divergences, and visualizes convergence of KDE-ECE to the true integral as t...
def plot_ce(which_convex_fcn, type='canonical'): num_classes, num_samples, num_bins, temp1, temp2, bandwidth = get_setup() if type == 'classwise': get_bregman_ce_fcn = get_classwise_bregman_ce else: get_bregman_ce_fcn = get_bregman_ce pred_scores_temp1, pred_scores_temp2, _, _, _ = samp...
def get_setup(): num_classes = 2 temp1 = 0.9 temp2 = 0.6 bandwidth = 0.001 num_bins = 15 num_samples = 5000 return num_classes, num_samples, num_bins, temp1, temp2, bandwidth def sample_points(num_samples, num_classes, temp1, temp2): logits_temp1 = [] samples = [] labels = [] ...
The code compares the performance of binning-based calibration error estimation (ECE) against kernel density estimates (KDE) under different convex functions (L2 or KL divergence). It samples predictions and targets, computes Bregman divergences and binning losses across varying sample sizes, and plots their relationsh...
def compare_with_binning(which_convex_fcn, num_repeats=2): num_classes, _, num_bins, temp1, temp2, _ = get_setup() pred_scores_temp1, pred_scores_temp2, _, _, targets = sample_points(50000, num_classes, temp1, temp2) if which_convex_fcn == 'l2': get_bregman_ce_fcn = get_classwise_bregman_stats_via_r...
def get_setup(): num_classes = 2 temp1 = 0.9 temp2 = 0.6 bandwidth = 0.001 num_bins = 15 num_samples = 5000 return num_classes, num_samples, num_bins, temp1, temp2, bandwidth def sample_points(num_samples, num_classes, temp1, temp2): logits_temp1 = [] samples = [] labels = [] ...
This code compares two methods for estimating Bregman divergences (via risk and direct computation) using either L2 or KL divergence, across varying sample sizes. It samples data, computes kernel density estimates (KDEs) for each method, repeats the process multiple times, and plots results against ground-truth integra...
def compare_two_impl(which_convex_fcn, num_repeats): num_classes, _, num_bins, temp1, temp2, bandwidth = get_setup() pred_scores_temp1, pred_scores_temp2, _, _, targets = sample_points(50000, num_classes, temp1, temp2) if which_convex_fcn == 'l2': convex_fcn = l2_norm get_bregman_ce_via_risk...
def sample_points(num_samples, num_classes, temp1, temp2): logits_temp1 = [] samples = [] labels = [] for _ in range(num_samples): # Sample a point from the simplex sample = sample_from_simplex(num_classes, 1) # Temp scale it to simulate our setting logit = temp_scale(tor...
This function evaluates the accuracy of KDE-based ECE estimates against ground truth integrals under L2/KL divergence. It samples predictions and targets, computes ECE for varying point counts, and calculates absolute/relative differences between estimated and true integrals across multiple repetitions.
def collect_results_for_nclasses(which_convex_fcn, num_classes, temp1, temp2, num_samples, num_repeats): pred_scores_temp1, pred_scores_temp2, _, _, _ = sample_points(50000, num_classes, temp1, temp2) if which_convex_fcn == 'l2': get_bregman_ce_fcn = get_classwise_bregman_stats_via_risk_l2 gt_in...
def _get_ratio_iter(f, y, bandwidth, device='cpu'): log_kern = get_kernel(f, bandwidth, device) y_onehot = nn.functional.one_hot(y, num_classes=f.shape[1]) y_onehot = _convert_to_device_and_dtype(y_onehot, device) log_y = torch.log(y_onehot) log_den = torch.logsumexp(log_kern, dim=1) final_ratio...
This function computes the ratio of probabilities between a kernel matrix and class distributions using log-space operations for numerical stability. It handles cases with fewer than 20 classes via efficient log-sum-exp calculations, while delegating larger class counts to an iterative method. The result represents a p...
def _get_ratio(f, y, bandwidth, device='cpu'): if f.shape[1] > 20: # Slower but more numerically stable implementation for larger number of classes return _get_ratio_iter(f, y, bandwidth, device) log_kern = get_kernel(f, bandwidth, device) y_onehot = nn.functional.one_hot(y, num_classes=f....
def get_setup(): num_classes = 2 temp1 = 0.9 temp2 = 0.6 bandwidth = 0.001 num_bins = 15 num_samples = 5000 return num_classes, num_samples, num_bins, temp1, temp2, bandwidth def collect_results_for_nclasses(which_convex_fcn, num_classes, temp1, temp2, num_samples, num_repeats): pred_sc...
( The code generates synthetic data to analyze bias convergence across different convex functions and class numbers (2, 5, 10). It computes bias metrics (e.g., ECE) and relative bias, plots them, and saves the visualizations as TikZ/LaTeX files with customized formatting. The goal is to study how bias behaves in synthe...
def plot_bias_synthetic_data(which_convex_fcn, num_repeats=20): num_classes, num_samples, num_bins, temp1, temp2, _ = get_setup() for num_classes in [2, 5, 10]: diff_kde_ece_gt_integral, relative_bias, points = collect_results_for_nclasses(which_convex_fcn, num_classes, temp1, temp2, num_samples, num_r...
def _check_input(gx): assert not _isnan(gx), "input contains nans" assert len(gx.shape) == 2 assert torch.min(gx) >= 0 assert torch.max(gx) <= 1 def _convert_to_device_and_dtype(x, device): # mps does not support double if device == 'mps': return x.float().to(device) # for cpu and cu...
The code calculates the Bregman calibration error (BCE) using a strictly convex function. It computes the error by applying the convex function to probability scores (`gx`) and their ratio (`ratio`) derived from labels, then evaluates the difference between transformed values and their gradient-weighted discrepancies. ...
def get_bregman_ce(convex_fcn, gx, y, bandwidth, device='cpu'): """ Calculate an estimate of Bregman calibration error. Args: convex_fcn: A strictly convex function F gx: The vector containing the probability scores, shape [num_samples, num_classes] y: The vector containing the labe...
def _check_input(gx): assert not _isnan(gx), "input contains nans" assert len(gx.shape) == 2 assert torch.min(gx) >= 0 assert torch.max(gx) <= 1 def _convert_to_device_and_dtype(x, device): # mps does not support double if device == 'mps': return x.float().to(device) # for cpu and cu...
The function computes the class-wise Bregman divergence-based loss using convex functions and gradients. It processes each class separately by creating class-specific masks, calculating ratios, applying the convex function, and computing gradients. The loss for each class is derived from the Bregman divergence terms, a...
def get_classwise_bregman_ce(convex_fcn, gx, y, bandwidth, device='cpu'): _check_input(gx) gx = _convert_to_device_and_dtype(gx, device) gx.detach() if not gx.requires_grad: gx.requires_grad = True all_CEf = [] for i in range(gx.shape[1]): classwise_y = (y == i).long() g...
def _check_input(gx): assert not _isnan(gx), "input contains nans" assert len(gx.shape) == 2 assert torch.min(gx) >= 0 assert torch.max(gx) <= 1 def _convert_to_device_and_dtype(x, device): # mps does not support double if device == 'mps': return x.float().to(device) # for cpu and cu...
This function calculates the Bregman calibration error (CE) using a strictly convex function $ F $, probability scores $ gx $, labels $ y $, and a kernel bandwidth. It computes the risk-based estimate by evaluating $ F $ on class ratios, Bregman divergences, and combining terms to derive $ CE_f $, which quantifies cali...
def get_bregman_ce_via_risk(convex_fcn, gx, y, bandwidth, device='cpu'): ''' Calculate an estimate of Bregman calibration error using the formula derived via risk. Args: convex_fcn: A strictly convex function F gx: The vector containing the probability scores, shape [num_samples, num_classe...
def _check_input(gx): assert not _isnan(gx), "input contains nans" assert len(gx.shape) == 2 assert torch.min(gx) >= 0 assert torch.max(gx) <= 1 def _convert_to_device_and_dtype(x, device): # mps does not support double if device == 'mps': return x.float().to(device) # for cpu and cu...
This function computes Bregman divergence statistics using risk and KL divergence. It calculates cross-entropy (CEf), entropy (Sf), and sharpness by combining entropy terms with KL divergence between predicted probabilities (gx) and one-hot labels (y). Key steps include ratio computation, negative entropy, KL divergenc...
def get_bregman_stats_via_risk_kl(gx, y, bandwidth, device='cpu'): _check_input(gx) gx = _convert_to_device_and_dtype(gx, device) ratio = _get_ratio(gx, y, bandwidth, device) f_ratio = negative_entropy(ratio) Sf = torch.mean(f_ratio) y_onehot = nn.functional.one_hot(y, num_classes=gx.shape[1]) ...
def _check_input(gx): assert not _isnan(gx), "input contains nans" assert len(gx.shape) == 2 assert torch.min(gx) >= 0 assert torch.max(gx) <= 1 def _convert_to_device_and_dtype(x, device): # mps does not support double if device == 'mps': return x.float().to(device) # for cpu and cu...
The code computes Bregman divergence-related statistics using L2 norms. It calculates three metrics: CEf (a risk measure combining data fit and regularization), Sf (mean L2 norm of ratio estimates), and sharpness (difference between Sf and squared expectation of labels). These metrics assess model calibration and uncer...
def get_bregman_stats_via_risk_l2(gx, y, bandwidth, device='cpu'): _check_input(gx) gx = _convert_to_device_and_dtype(gx, device) ratio = _get_ratio(gx, y, bandwidth, device) f_ratio = l2_norm(ratio) Sf = torch.mean(f_ratio) y_onehot = nn.functional.one_hot(y, num_classes=gx.shape[1]) y_one...
def _check_input(gx): assert not _isnan(gx), "input contains nans" assert len(gx.shape) == 2 assert torch.min(gx) >= 0 assert torch.max(gx) <= 1 def _convert_to_device_and_dtype(x, device): # mps does not support double if device == 'mps': return x.float().to(device) # for cpu and cu...
This function computes class-wise Bregman divergence statistics using entropy and KL-divergence for each class in the input tensor gx. It calculates cross-entropy (CEf), sharpness (Sf), and uncertainty measures, then returns their averaged values across all classes.
def get_classwise_bregman_stats_via_risk_kl(gx, y, bandwidth, device='cpu'): _check_input(gx) gx = _convert_to_device_and_dtype(gx, device) all_CEf = [] all_Sf = [] all_sharpness = [] for i in range(gx.shape[1]): classwise_y = (y == i).long() gx_i = gx[:, i].unsqueeze(-1) ...
def _check_input(gx): assert not _isnan(gx), "input contains nans" assert len(gx.shape) == 2 assert torch.min(gx) >= 0 assert torch.max(gx) <= 1 def _convert_to_device_and_dtype(x, device): # mps does not support double if device == 'mps': return x.float().to(device) # for cpu and cu...
This function computes class-wise Bregman divergence statistics using L2 risk. For each class, it calculates the Bregman divergence (CEf), a smoothness term (Sf), and sharpness metrics. It processes input predictions (gx) and labels (y), computes ratios with a given bandwidth, and aggregates results across classes. The...
def get_classwise_bregman_stats_via_risk_l2(gx, y, bandwidth, device='cpu'): _check_input(gx) gx = _convert_to_device_and_dtype(gx, device) all_CEf = [] all_Sf = [] all_sharpness = [] for i in range(gx.shape[1]): classwise_y = (y == i).long() gx_i = gx[:, i].unsqueeze(-1) ...
def _get_pawn_dests(self, r: int, c: int, player: str) -> Sequence[Tuple[int, int]]: """pawns are actually the most complex pieces on the board! Their moves: 1. are asymmetric, 2. depend on their position, 3. depends on opponents 4. moves do not equal captures NOTE: promotions are handl...
The function generates all possible destinations for a chess piece at position (r,c) based on its type (pawn, rook, knight, etc.), using specific movement rules. It determines the player's color, applies piece-specific movement patterns (e.g., knight jumps, rook slides), and returns a list of valid coordinates. A TODO ...
def get_dests_for_piece(self, r: int, c: int, piece=None) -> Sequence[Tuple[int, int]]: """Given a particular piece, generates all possible destinations for it to move to. piece: optional param to override piece at board location TODO: filter destinations that would put us in check. Retu...
def find_my_pieces(self, turn=None) -> Sequence[Tuple[str, int, int]]: """Returns a list of all the current player's pieces and their locations. turn: override the current turn [(piece, row, column),]""" if turn is None: turn = self.turn if turn == "white": ...
The code generates all possible moves for the current player's turn, including normal moves, pawn promotions, castling, and en passant. It iterates over each piece's destinations, handles promotions for pawns reaching the end rank, and adds special moves like castling and en passant to the list of Move objects, returni...
def moves(self, turn=None) -> Sequence[Move]: """returns a list of all possible moves given the current board state and turn. turn: "white" or "black" or None, to use the current turn Returns a list of Move Objects.""" if turn is None: turn = self.turn pieces = self.f...
def find_valid_action(self, state): action = self.generate_policy(state) action_idx = self.ACTION_SPACE.index(action) while self.Q_table[state][action_idx] == float('-inf'): action = self.generate_policy(state) action_idx = self.ACTION_SPACE.index(action) return a...
The function `generate_episode` simulates an episode in a reinforcement learning environment by executing actions, tracking rewards, steps, and time. It updates Q-table convergence, handles episode termination, records goal/failure counts, and accumulates rewards. If a method (e.g., SARSA/Q-Learning) is provided, it up...
def generate_episode(self, episode, method=None): cost = 0 current_state = self.env.reset() action, action_idx = self.find_valid_action(current_state) episode_info = [] episode_start_time = time.time() for step in range(1, NUM_STEPS + 1): time.sleep((1 / sel...