dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def delete_shopping_list(): [si.delete() for si in ShoppingList.objects.all()] def create_default_shopping_list(): default_list = [ { 'name': 'olive oil', 'quantity': 1, 'unit': 'bottle(s)', 'missing': True, }, { 'name': 'mozzar...
The main task of the code is to reset a shopping list by deleting its current contents, recreating a default shopping list, and then printing the updated list. The function calls `delete_shopping_list()` to remove existing items, `create_default_shopping_list()` to restore predefined items, and `get_shopping_list()` to...
def recreate_default(): delete_shopping_list() create_default_shopping_list() print(get_shopping_list())
def primes(start, up_to): found_primes = set() for x in range(start, up_to): if factors(x) == {1, x}: found_primes.add(x) return found_primes def public_key(m, c): e = m * 2 + 1 while True: if GCD(e, m) == 1 and GCD(e, c) == 1 and mod_inverse(e, m) != 1: br...
The function generates RSA-like public and private keys. It either randomly selects two distinct primes (if m/n are unspecified) or uses primes from a predefined list based on indices m/n. It computes the modulus (c = a*b) and Euler's totient (m = (a-1)*(b-1)), then derives the public key (pub) and private key (priv) u...
def generate_keys(m=None, n=None): if not m or not n: # Generate two primes prime_set = primes(20, 200) a = random.choice(list(prime_set)) prime_set.remove(a) # a and b must be different values b = random.choice(list(prime_set)) else: prime_set = sorted(list(prim...
def initial_prob(data, K, method, supervised=False, labels=None): """ initial cluster assignment probabilities in VCMM algorithm Input: data: NxD np array of data K: number of groups method: string specifying the fast clustering method Output: z: NxK np array of assignm...
The code implements a **Vine Copula Mixture Model (VCMM)** for clustering or classification via the Expectation-Maximization (EM) algorithm. It estimates parameters for a mixture of vine copula-based distributions, including marginal models, copula structures, and mixture proportions. The model supports both unsupervis...
def vcmm(data, K=None, labels=None, tol=0.00001, maxiter=100, initial_method="kmeans", fitting_trunclevel=1, trace=False, marginals = [stats.norm, stats.t], copulas = ["bb1","bb6","bb7","bb8","clayton","frank","gaussian","gumbel","indep","joe","student"]): if (K is None) and (labels is None) : ...
def u_fun(dist, par, data): """ probability transform for a scipy distribution object """ n_par = par.__len__() if n_par > 2 : return dist.cdf(data, par[:-2], loc=par[-2], scale=par[-1]) else : return dist.cdf(data, loc=par[-2], scale=par[-1]) def posterior_prob(data, pi, F, gamm...
The code predicts class labels, probability distributions, and density estimates for input data `x` using a probabilistic model. It computes latent variables `ux`, calculates posterior probabilities (`pred_prob`) with class priors and parameters, and evaluates posterior densities (`pred_dens`). The function returns pre...
def predict(x): ux = [np.column_stack([u_fun(F[i][j], gamma[i][j], x[:,j]) for j in range(d)]) for i in range(K)] pred_prob = posterior_prob(x, pi, F, gamma, ux, V, r, supervised=False) pred_dens = posterior_density(x, pi, F, gamma, ux, V) return pred_prob.argmax(axis=1), pred_prob, pred...
def __parse_moves(self): """ Parse the input file Add moves knight moves to the list and return it """ moves: list[tuple[Knight, DIRECTION]] = [] with open(self.file_path, 'r') as f: for line in f: line = line.strip() if line =...
The main task of the `play` method is to execute a sequence of game moves for testing purposes. It parses input moves, processes them to update the game state, and outputs the resulting state. This facilitates testing by simulating move execution and verifying state changes in a controlled environment.
def play(self): """ To ease testing """ self.moves = self.__parse_moves() self.moves = self.__make_moves() self.moves = self.__output_state()
def changequestion(): global question_list plusminus = random.choice(['+','-']) operators = [div,mul,plusminus] plusminus = random.choice(['+','-']) operators = operators + [plusminus] numbers = [str(random.randint(2,50)),str(random.randint(2,50)),str(random.randint(2,50)),str(random.randint(2,5...
The main task of the code is to generate a structured question database entry by compiling a question, its correct answer, three incorrect options, a solution, and metadata (like topic number and variation) into a dictionary. The function orchestrates fetching the question, generating options, retrieving the solution, ...
def Main_function(): changequestion() question = getQuestion() correct_op,wrong_op = make_options() wrong_op1, wrong_op2, wrong_op3 = wrong_op[0:] solution = getsol() database_dict = database_fn( Question_Type='text', Answer_Type='text', Topic_Number='030302', Variation='v1...
def getQuestion(): generateQuestion() return f"Simplify the following expression<br/>{expression}" def getCorrectOption(): ans_expression = '(' + str(a / b) + ' ' + symbol1 + ' ' + str(c / d) + ')' + ' ' + symbol2 + ' ' + '(' + str( e / f) + ' ' + symbol3 + ' ' + str(g / h) + ')' ans = Fraction(...
The main task of the code is to compile a structured dictionary containing a question, its correct and wrong answer options, solution, and metadata (e.g., topic, variation) by calling helper functions, then return this dictionary for database storage. The function gathers data through `getQuestion()`, `getCorrectOption...
def main_function(): Question = getQuestion() Corr_op = getCorrectOption() wrong_op1, wrong_op2, wrong_op3 = getWrongOptions() Solution = getSolution() database_dict = database_fn( Question_Type='text', Answer_Type='text', Topic_Number='030302', Variation='v1', ...
def changeValues(): global correctAnswer, wrong_Options, soln_print, i correctAnswer, perimeter_ans, answerList, variable, image_name = generate_image() correctIndex, allOptions, wrong_Options = options(correctAnswer, answerList) soln_print = getSolution(correctAnswer, answerList, variable, perimeter_a...
The main task of the code is to generate a structured database entry for an educational question. It compiles a question, correct answer, three wrong options, an image path, and solution text into a dictionary using predefined parameters. The function leverages helper functions to dynamically create question content an...
def main_function(): variable, perimeter, answerList, correctIndex, image_path = changeValues() Question = getQuestion(variable, perimeter) Corr_op = getCorrOption() wrong_op1, wrong_op2, wrong_op3 = getWrongOptions() Solution = soln_print #this database_fn #for understanding the parameter...
def rayleigh_length(self): # remains Ry as fundamental M2 = 2.2 # from experimental values ry = math.pi * (self.w0_fundamental ** 2)*M2/ (self.lambdaL) print('Rayleigh length: ', ry, 'for wo', self.w0_fundamental) return ry def beam_waist_of_z_value(self, z): self.wz = se...
This code initializes a laser beam propagation model, setting parameters like waist (w0), wavelength (lambdaL), defocusing range (z), and denting depth. It calculates the Rayleigh length, beam waist at specific z-values, and focal length using "wzILtauChirp" dependency. The harmonic number array and test_beam_waist() s...
def __init__(self, w0, lambdaL, defocusing_range, denting_depth, color, marker): print('xxxxxxxx run with denting_depth: ' + str(denting_depth) + 'xxxxxxx') self.w0 = w0 print("input angle in pi", np.cos(35/180*np.pi)) print("increase of w0 by angle", 1/(np.cos(35/180*np.pi))) s...
def rayleigh_length(self): # remains Ry as fundamental M2 = 2.2 # from experimental values ry = math.pi * (self.w0_fundamental ** 2)*M2/ (self.lambdaL) print('Rayleigh length: ', ry, 'for wo', self.w0_fundamental) return ry def beam_waist_of_z_value(self, z): self.wz = se...
This code initializes a class to model laser beam propagation, calculating beam waist (wz), focal length dependencies (f), and related optical parameters. It sets up wavelength (lambdaL), harmonic numbers, and computes the Rayleigh length (zr). The 'denting_depth' parameter influences focal length calculations, with me...
def __init__(self, w0, lambdaL, denting_depth, color, marker): print('xxxxxxxx run with denting_depth: ' + str(denting_depth) + 'xxxxxxx') self.w0 = w0 print("input angle in pi", np.cos(35/180*np.pi)) print("increase of w0 by angle", 1/(np.cos(35/180*np.pi))) self.w0_fundamental...
def q_initial_vincenti(self): self.q = (self.beam_waist_of_z_harmonic_scaling_wN(0) ** 2) * math.pi / (self.lambdaL / self.harmonic_number) return self.q def test_beam_waist2(self): plt.title("beamwaist w(z,N)_N="+str(self.harmonic_number)) test = np.linspace(-5,5,1000) wz = np.z...
The function calculates and plots the divergence of a laser beam's harmonic number (N) relative to the fundamental mode (L) using Vincenti's method. It computes the beam waist (w0) and divergence at various z-positions, normalizes them, and visualizes the results with logarithmic scaling for divergence. Key steps inclu...
def resulting_divergence_over_harmonic_number_Vincenti(self): result_w0_new = np.zeros([len(self.z)]) result_div_harmonic_number = np.zeros([len(self.z)]) #self.q = self.q_initial()/(self.harmonic_number **2) self.q = self.q_initial_vincenti() self.test_beam_waist2() #pr...
def q_initial(self): self.q = (self.w0 ** 2) * math.pi / (self.lambdaL / self.harmonic_number) return self.q def focal_lens_wz_tauL_z_scan(self): for x in range(0,len(self.z)): self.beam_waist_of_z_value(self.z[x]) #print(self.q) #print(self.wz, "beamwaist", "...
The code calculates and plots the divergence of a harmonic number's beam waist (w(N)(z)) relative to a reference beam (w(L)(z)) across different z positions. It computes beam waist (result_w0_new) and divergence (result_div_harmonic_number) for each position using focal lens parameters, then visualizes the ratio Θ(N)/Θ...
def resulting_divergence_over_harmonic_number_julia(self): result_w0_new = np.zeros([len(self.z)]) result_div_harmonic_number = np.zeros([len(self.z)]) self.q = self.q_initial() self.focal_lens_wz_tauL_z_scan() for i in range(0, len(self.z)): # difference to the above m...
def read_calib(calib_file_path): with open(calib_file_path, 'r') as calib_file: calib = {} csv_reader = csv.reader(calib_file, delimiter='=') for attr, value in csv_reader: calib.setdefault(attr, value) return calib def create_depth_map(pfm_file_path, calib=None): dispari...
The main task is to read calibration data from 'calib.txt', generate a depth map from disparity data in 'disp0.pfm' using the calibration, display the depth map, and save it as 'depth.png'. The code processes stereo vision data to create a 3D depth representation from disparity and calibration parameters.
def main(): pfm_file_dir = Path(r'images/Middlebury') calib_file_path = pfm_file_dir.joinpath('calib.txt') disp_left = pfm_file_dir.joinpath('disp0.pfm') # calibration information calib = read_calib(calib_file_path) # create depth map depth_map_left = create_depth_map(disp_left, calib) ...
def populate_graph_joint_links(self): """Populate directed links between bodies with joints""" if self.assembly_data["joints"] == None: return for joint_uuid, joint in self.assembly_data["joints"].items(): # TODO: Question - no "joints" in dataset? # TODO: Consider links...
The code's main task is to generate graph links between mechanical bodies based on joints, as-built joints, and contacts present in the assembly data. It conditionally invokes specialized methods—`populate_graph_joint_links`, `populate_graph_as_built_joint_links`, and `populate_graph_contact_links`—to create connection...
def populate_graph_links(self): """Create links in the graph between bodies with joints and contacts""" if "joints" in self.assembly_data: self.populate_graph_joint_links() if "as_built_joints" in self.assembly_data: self.populate_graph_as_built_joint_links() if "...
def populate_graph_nodes(self): """ Recursively traverse the assembly tree and generate a flat set of graph nodes from bodies """ # First get the root and add it's bodies root_component_uuid = self.assembly_data["root"]["component"] # root > component root_comp...
The main task of the code is to retrieve graph data by populating nodes, links, and edges. It initializes empty structures, calls methods to populate nodes and links, processes links further, and returns the final graph components as a tuple of nodes, links, and edges for visualization or analysis.
def get_graph_data(self): """Get the graph data as a list of nodes and links""" self.graph_nodes = [] self.graph_links = [] self.graph_edges = [] self.graph_node_ids = set() self.populate_graph_nodes() # Populate "nodes" list # print(self.graph_nodes) s...
def getGaesTargets(self, rewards:np.ndarray, values:np.ndarray, dones:np.ndarray, fails:np.ndarray, next_values:np.ndarray) -> List[np.ndarray]: ''' input: rewards: np.array(n_steps,) values: np.array(n_steps,) dones: np.array(n_steps,) ...
The code trains a reinforcement learning agent by processing trajectories to compute advantages and targets, normalizing data, and updating the policy and value networks. It calculates generalized advantage estimates (GAEs), applies policy optimization via conjugate gradient and line search, and updates the value funct...
def train(self, trajs): # convert to numpy array states_list = [] actions_list = [] gaes_list = [] targets_list = [] for env_idx in range(self.n_envs): env_traj = trajs[env_idx] states = np.array([traj[0] for traj in env_traj]) actions...
def normalizeAction(self, a): return normalize(a, self.action_bound_max, self.action_bound_min) def getGaesTargets(self, rewards, values, dones, fails, next_values, rhos): delta = 0.0 targets = np.zeros_like(rewards) for t in reversed(range(len(targets))): targets[t] = reward...
The code updates a reinforcement learning policy and value function using sampled trajectories from a replay buffer. It computes generalized advantages (GAEs), targets, and policy gradients, then performs trust region policy optimization (TRPO) with conjugate gradient and line search to ensure stable policy updates. Th...
def update(self, is_last=False): # convert to numpy array states_list = [] actions_list = [] gaes_list = [] targets_list = [] mu_means_list = [] mu_stds_list = [] for env_idx in range(self.n_envs): n_steps = min(len(self.replay_buffer[env_idx]...
def quiesce(self, chessBoard, alpha, beta): stand_pat = self.quickEval(chessBoard) if( stand_pat >= beta ): return beta if( alpha < stand_pat ): alpha = stand_pat for move in getMoveOrdering(chessBoard): if chessBoard.is_capture(move): ...
The function implements the negamax algorithm with alpha-beta pruning for a chess AI, recursively evaluating the best move by exploring possible positions. It uses quiescence search at depth zero to avoid unstable evaluations, applies move ordering, and prunes branches where the current path cannot improve the result, ...
def negaMax(self, chessBoard, depthRemaining, alpha_prev, beta_prev): #Variables alpha = alpha_prev beta = beta_prev if(depthRemaining == 0): #Call Quiescent function return self.quiesce(chessBoard, alpha, beta) #Recursively search for best score and ac...
def initEvaluation(self, chessBoard): """ The evaluation function takes in the current chessBoard and move and returns an evaluation of the resulting position """ evaluation = materialEval(chessBoard) evaluation += sum(pieceSquareEval(chessBoard)) self.eval = ev...
Your return The code implements a minimax algorithm with alpha-beta pruning and transposition tables to determine the best chess move. It prioritizes opening book moves, then checks cached results in the transposition table. If unavailable, it evaluates moves using negaMax, iterates through ordered candidates, and upda...
def getMove(self, chessBoard): """ Returns the minimax action from the current chessBoard using self.depth. """ "*** YOUR CODE HERE ***" #Definitions alpha = -math.inf beta = math.inf bestEval = -math.inf bestMove = chess.Move.null() self....
def CalculateLimitingCompound(ListOfReactants, ListOfMasses, DesiredProduct): LimitingMass = 10 ** 10 LimitingIndex = 0 for i, e in enumerate(ListOfReactants): out = Stoichiometry(e, DesiredProduct, "MassToMass", ListOfMasses[i]) if out < LimitingMass: LimitingMass = out ...
The code calculates the theoretical yield, percent yield, and remaining excess reactants in a chemical reaction. It identifies the limiting reactant, computes the theoretical yield from it, determines the percent yield using actual vs. theoretical values, and calculates leftover excess reactant masses by subtracting co...
def reactionsolver(ListOfReactants, ListOfMasses, Product, ActualYield): LimitingReactant = CalculateLimitingCompound(ListOfReactants, ListOfMasses, Product) ExcessReactants = CalculateExcessReactant(ListOfReactants, ListOfMasses, Product) TheoreticalYield = (LimitingReactant[0]) ListOfExcess = [] P...
def check_if_file_has_blockchain_data(): with open('./blockchain.txt', 'r') as file_data: data = file_data.read() # blockchain_data = json.loads(file_data.read()) if(data): return True else: return False def genesis_block(): genesis = { 'previous_hash': 0, 'in...
This code initializes a blockchain with a genesis block or loads existing data, then provides a menu-driven interface for users to add transactions, view the blockchain, manipulate blocks, verify integrity, or exit. It manages participant balances, validates transactions, and ensures data consistency between the blockc...
def get_user_input(): # Initialize the Blockchain with a genesis block as soon as user interaction starts check_for_data_from_file = check_if_file_has_blockchain_data() if(not check_for_data_from_file): genesis_block() else: update_saved_data_to_blockchain() update_saved_data_of_...
def force_analog(self): value = ADC.read_raw(self.analog_in1) value = int(value)//self.force_sen return value def openw(self): # open the wings PWM.set_duty_cycle(self.servo, SG90_RIGHT) time.sleep(1) PWM.set_duty_cycle(self.servo,SG90_OFF) def rand(self,r): ...
The code's main task is to control user interaction via touch and button inputs, opening wings when touched and cycling through random elements (1-5) using a button. It continuously checks sensor states, manages wing status, and triggers element functions with delays, enabling a choice-based interaction system between ...
def run(self): i = -1 while True: # main script which controls user interaction # signal flow (muggle vs chosen in main script) # check if the touch sensor is touched if self.force_analog() != self.force_max//self.force_sen: # if the touch...
def get_prob_constraints(self): """! Create constraints for each cell that probability sum is 1 [eq 5] """ cell_count = len(self.environment) constraints = [] for a in range(cell_count): eval_str = "lambda x: sum(x[{}*{}:({}+1)*{}]) - 1".format( a, ce...
The function aggregates problem and zero constraints into a combined list, then returns this list along with intruder constraints as separate components in a tuple.
def get_eq_constraints(self): prob_cons = self.get_prob_constraints() zero_cons = self.get_zero_constraints() intruder_cons = self.get_intruder_constraints() return prob_cons + zero_cons, intruder_cons
def get_prob_constraints(self): """! Create constraints for each cell that probability sum is 1 [eq 5] """ cell_count = len(self.environment) constraints = [] for a in range(cell_count): eval_str = "lambda x: sum(x[{}*{}:({}+1)*{}]) - 1".format( a, ce...
The function `get_eq_constraints` aggregates three types of constraints—problem, zero, and intruder—into a tuple. It combines problem and zero constraints into a single list, then returns this merged list alongside the intruder constraints, likely for use in optimization or constraint satisfaction problems.
def get_eq_constraints(self): prob_cons = self.get_prob_constraints() zero_cons = self.get_zero_constraints() intruder_cons = self.get_intruder_constraints() return prob_cons + zero_cons, intruder_cons
def extract_moves_from_board(self, board): moves_dict = dict() postions_on_board = [1, 5, 9, 13, 17, 21, 25, 29, 33] for position in postions_on_board: if board.board_str[position] == 'X': try: existing_moves = moves_dict['X'] e...
The function determines the AI's next move based on imminent wins. It first checks if the AI can win in one move; if so, it plays offensively. If the human can win in one move, it defends. Otherwise, it plays offensively, prioritizing immediate threats over general offense.
def middle_moves(self, board): moves_dict = self.extract_moves_from_board(board) if self.moves_until_ai_wins(moves_dict) == 1: return self.play_offense(moves_dict) if self.moves_until_human_wins(moves_dict) == 1: return self.play_defense(moves_dict) return self.pl...
def get_number_of_moves(self, board): count = 0 if board.board_str[1] in ['X', 'O']: count += 1 if board.board_str[5] in ['X', 'O']: count += 1 if board.board_str[9] in ['X', 'O']: count += 1 if board.board_str[13] in ['X', 'O']: co...
This function determines the AI's next move in a game based on the current board state. If no moves have been made, it initializes as player 'X' and plays a center-opening strategy. If one move exists, it switches to 'O' and employs a second-move tactic. For subsequent moves, it uses a general middle-game strategy. The...
def calculate_move_genius(self, board): if self.get_number_of_moves(board) == 0: self.player = 'X' self.other_player = 'O' return self.first_move_play_center_move_one() if self.get_number_of_moves(board) == 1: self.player = 'O' self.other_playe...
def check_user(vk, uid:Union[str,int,Me])->UserId: """Checks whether a user or community exists""" if isinstance(uid,Me): response = vk.users.get() return UserId(int(response[0]['id'])) else: try: response = vk.users.get(user_ids=uid) return UserId(int(response[0]['id'])) except VKApiE...
The main task of the code is to reclaim and optionally remove VK user albums/photos by authenticating with credentials, iterating through albums/photos, saving files, checking user confirmation (interactive mode), and deleting albums if all associated photos are removed. It handles logging, error handling, and conditio...
def run(args:Args)->None: basicConfig(stream=stdout, level=args.verbose) vk = VkApi(args.login, args.password) vk.auth() vk = vk.get_api() tools = VkTools(vk) reclaimed_photos=[] user_id = check_user(vk,args.targetuser) debug('User:', user_id.val) for album in gen_albums(tools, user_id): debug(alb...
def init_params(self, data): """ Initialize distribution params """ self.weights = np.ones(self.k) / self.k self.mus = np.random.randn(self.k) self.sigmas = np.ones(self.k) def cost(self, data): """ Calculate the negative log-likelihood cost function "...
The code implements the Expectation-Maximization (EM) algorithm to estimate model parameters. It initializes parameters, iteratively performs maximization steps, calculates costs, and stops when the cost difference falls below a threshold (eps) or after n_iter iterations, storing parameters and costs during the process...
def fit(self, data): """ Fit training data (the learning phase). Use init_params and then expectation and maximization function in order to find params for the distribution. Store the params in attributes of the EM object. Stop the function when the difference between the...
def render(self): self.spaces = [[], [], [], [], [], [], [], []] for i in range(8): for j in range(8): win = curses.newwin(3, 6, i*3, j*6) win.addstr(1, 2, self.board.get([i, j]).symbol) self.spaces[i].append(win) if [i, j] == s...
The main task of the code is to handle user input for moving a piece on a board, updating the display and position based on directional key presses (A/B/C/D), with 'q' to quit and Enter to confirm. It tracks the current position, highlights selections, and returns the final position after input processing.
def get_move(self): key = None self.render() self.set_color(self.pos, 2) if self.selection: self.set_color(self.selection, 3) self.find(self.pos).addstr(1, 2, self.board.get(self.pos).symbol) self.find(self.pos).refresh() self.textfield.refresh() ...
def available_moves(color, board): return [[position, move] for position in pieces(color, board) for move in board.valid_moves(position)] def mate_move(color, board, move): new_board = Board() new_board.board = copy.deepcopy(board.board) new_board.move_piece(move[0], move[1]) return new_board.checkm...
The main task of the code is to determine the optimal move for a player in a board game. It first identifies all available moves, checks if any lead to an immediate checkmate, and returns the first such move if found. If no checkmate exists, it selects a random move from the best moves calculated using a depth-based ev...
def get_move(self, board, display): moves = available_moves(self.color, board) mate_moves = [mate_move(self.color, board, move) for move in moves] if len(mate_moves) > 0: return mate_moves[0] else: return random.choice(best_moves(self.color, board, moves, self.dep...
def pos_words(rack: List[Tile], treasures: List[str], power: float=0, max_words: int=50) -> List[Tuple[str, float]]: ''' Creates a list of all words in the rack that can be found in the dictionary, taking frequency of letters into account, along with their evaluation from word_evaluator, sorted by eva...
The function performs a Monte Carlo search to identify the optimal word to play from a given rack, considering future moves up to a specified depth. It evaluates possible words by simulating multiple game scenarios, calculating average scores, and selecting the word with the highest expected score. The search iterative...
def monte_carlo_search(rack, treasures, power=0, num_simulations=100, max_words=5, depth=2): ''' Uses a Monte Carlo search to determine the best word to play out of the top words, taking into account the next few turns ''' # First, we want to generate all possible words that can be played possi...
def applyParallel(dfGrouped, func): retLst = Parallel(n_jobs=multiprocessing.cpu_count())(delayed(func)(name, group) for name, group in dfGrouped) return pd.DataFrame(retLst) def summarize_events_before_game_session(name, events): if not isinstance(name, (list,tuple)) or len(name)==1: # for test dat...
This function transforms user event data into features by grouping events per installation_id and summarizing them before each training session. It processes timestamps, merges with labels if provided, and generates features using parallel processing. The output includes expanded count features, optionally split into f...
def basic_user_features_transform(train_data, train_labels=None): data = train_data[['event_id', 'game_session', 'timestamp', 'installation_id', 'event_count', 'event_code', 'game_time', 'title', 'type', 'world']] data['ts'] = pd.to_datetime(data.timestamp) if train_labels is not None...
def _camel_to_snake(src_string): """Convert camelCase string to snake_case.""" dst_string = [src_string[0].lower()] for c in src_string[1:]: if c in ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"): dst_string.append("_") dst_string.append(c.lower()) else: dst_string.append...
The function parses API response metadata into a standardized dictionary. It converts camelCase keys to snake_case, processes specific fields like spatial/temporal coverage, dates, and browse data, and ensures acquisition_date is set. Numeric IDs are kept as strings, while other values are parsed accordingly.
def _parse_metadata(response, parse_browse_field=False): """Parse the full response returned by the API when requesting metadata.""" metadata = {} for key, value in response.items(): name = _camel_to_snake(key) if key == "browse": if parse_browse_field: metadata[n...
def find_second_shift_by_angle(sorted_shifts, minimum_angle=20): ''' Find the second displacement vector Args: sorted_shifts: displacement vectors that are sorted based on the losses minimum_angle: the minimum angle difference between the first and second displacement vectors Returns: ...
The function `generate_periodicity` identifies the optimal periodicity from displacement vectors by analyzing loss values. It sorts displacement vectors by loss, selects the top two shifts, computes their angles, and derives periods using pairwise shift relationships. The output includes angles, periods, and selected s...
def generate_periodicity(losses, possible_shifts): ''' generate the best periodicity based on the computed loss. Args: losses: losses for possible displacement vectors possible_shifts: possible displacement vectors ''' # sort the losses sorted_index = torch.argsort(losses) ...
def generate_possible_shifts(act_shape, repeat_range_x=(1, 10), repeat_range_y =(10,20), device='cpu'): dxs, dys = torch.meshgrid([ torch.arange(-act_shape[1] // repeat_range_x[0], act_shape[1] // repeat_range_x[0], device=device), torch.arange(0, act_shape[0] // repeat_range_y[0], device=device) ...
This function identifies periodic patterns in an activation map by iterating over displacement ranges, computing losses for possible shifts, and selecting optimal periodicity parameters (angles, periods, shifts) based on minimal loss, aiding in texture or pattern analysis in images.
def feature_search(activation_, mask, repeat_range = (3, 6, 1), edge_searching=True): ''' Args: img: input image activation_: activation map mask: unknown mask repeat_range: key hyperparameters for the periodicity detection method [1]. Its format is (start_r...
def im2act(im, mask, model_name='alexnet', gray_only=False): ''' get activation map from rgb image ''' model_def = get_model_def(model_name) model = model_def.get_model(use_gpu=True) image_transform = T.Compose([ PadMultipleOf(32), T.ToTensor(), T.Normalize([0.485, 0....
This function detects periodic patterns in an image using displacement vectors based on feature maps. It processes the input image and mask, applies edge detection if enabled, searches for periodic features within specified ranges, and scales detected periods and shifts according to image size. The output includes angl...
def search_periodicity_by_feat(img, mask, repeat_range = (2, 32, 5), edge_searching = False, gray_only = False, threshold = 10): ''' Perform periodicity detection method [1] for multiple times based on repeated range. It searches in the form of displacement vectors. Args: img: i...
def train(numSteps): for i in range(numSteps): in1 = random() * 6.0 in2 = random() * 6.0 target = targetFunction(in1,in2) learn(in1,in2,target) def writeF(filename): fout = open(filename, 'w') steps = 50 for i in range(steps): for j in range(steps): ta...
The code `test2()` trains a model with initial parameters (20 units), writes results to 'f20', computes MSE on 10,000 samples, then iterates 10 times: training for 1,000 units each, recalculating MSE, and finally writes final results to 'f10000'. The task involves model training, evaluation, and result storage in disti...
def test2(): train(20) writeF('f20') MSE(10000) for i in range(10): train(1000) MSE(10000) writeF('f10000')
def connection_setup(): """ Sets up connection, making sure port number is within limit""" arguments = sys.argv portnum = int(arguments[1]) if len(arguments) == 2: try: if portnum > 1024 and portnum <= 64000: portnum = int(arguments[1]) #need to check for alphabet? ...
The main task of the code is to configure and initialize a server. It retrieves a port number, creates and binds a socket to that port, sets the socket to listen for connections, and then accepts incoming connections. This establishes a server capable of handling client interactions.
def main(): """Calls functions to get the server set up and listening.""" portnum = connection_setup() s, portnum = create_bind_listen_socket(portnum) accept_connection(s, portnum)
def motion_callback(channel): global last_motion_time current_time = time.time() # Check if enough time has passed since the last motion detection if (current_time - last_motion_time) > 1.5 and GPIO.input(PIR): # Record the time of the latest motion detection last_motion_time = curr...
The code runs an image classification model using a specified TFLite model to classify objects in real-time video from a webcam. It captures frames, classifies images when the spacebar is pressed, determines recyclability based on classification results, updates the UI with labels and colors, and unlocks recycling if c...
def run(model: str, save_images_on: bool) -> None: model_path = f'./models/{model}' # Initialize the image classification model base_options = core.BaseOptions( file_name=model_path, use_coral=False, num_threads=_NUM_THREADS) # Enable Coral by this setting classification_options = processor.Classifi...
def load_and_filter_df(code_id, load_function, column='hcpcs'): code_id = get_valid_code_id(code_id, df_column=column) if code_id: df = load_function() if is_pyspark_df(df): return df.filter(F.col(column) == code_id) else: return df[df[column] == code_id] retu...
The main task of the code is to retrieve the current labor rate per minute for a given code ID, calculate totals using the `calculate_totals` function with specified prefixes, and return the updated DataFrame. It handles both PySpark and pandas DataFrames by checking their type and extracting the initial rate value acc...
def get_current_labor(code_id): df = load_and_filter_df(code_id, pfs.load_labor) if df is not None: if is_pyspark_df(df): rate_per_minute = df.select('rate_per_minute').first()[0] else: rate_per_minute = df['rate_per_minute'].iloc[0] df = calculate_totals(df, ['nf...
def load_and_filter_df(code_id, load_function, column='hcpcs'): code_id = get_valid_code_id(code_id, df_column=column) if code_id: df = load_function() if is_pyspark_df(df): return df.filter(F.col(column) == code_id) else: return df[df[column] == code_id] retu...
The function calculates a 'time_factor' for equipment data by dividing price by the product of useful life and minutes per year, then aggregates totals for 'nf_time' and 'f_time' columns. It handles both PySpark and pandas DataFrames, returning the processed DataFrame or None if input data is invalid.
def get_current_equip(code_id): df = load_and_filter_df(code_id, pfs.load_equip) if df is not None: if is_pyspark_df(df): df = df.withColumn("time_factor", (F.col('price') / F.col('useful_life')) / F.col('minutes_per_year')) else: df['time_factor'] = (df['price'] / df['us...
def load_and_filter_df(code_id, load_function, column='hcpcs'): code_id = get_valid_code_id(code_id, df_column=column) if code_id: df = load_function() if is_pyspark_df(df): return df.filter(F.col(column) == code_id) else: return df[df[column] == code_id] retu...
This function processes supply data by loading and filtering it, then calculates totals for specified columns (nf_quantity, f_quantity) using price and total_price fields. It handles both PySpark and pandas DataFrames, ensuring 'total_price' is correctly derived from 'price', before returning the computed DataFrame or ...
def get_current_supply(code_id): df = load_and_filter_df(code_id, pfs.load_supply) if df is not None: if is_pyspark_df(df): df = df.withColumn("total_price", F.col('price')) else: df['total_price'] = df['price'] df = calculate_totals(df, ['nf_quantity', 'f_quantit...
def get_current_supply(code_id): df = load_and_filter_df(code_id, pfs.load_supply) if df is not None: if is_pyspark_df(df): df = df.withColumn("total_price", F.col('price')) else: df['total_price'] = df['price'] df = calculate_totals(df, ['nf_quantity', 'f_quantit...
The function `get_direct_pe` aggregates the sum of 'tot_f' and 'tot_nf' columns from three data sources (supply, equipment, labor) for a given `code_id`. It handles both PySpark and pandas DataFrames, returning total values if all inputs are valid; otherwise, it returns `(None, None)`.
def get_direct_pe(code_id): df1 = get_current_supply(code_id) df2 = get_current_equip(code_id) df3 = get_current_labor(code_id) if df1 is not None and df2 is not None and df3 is not None: if is_pyspark_df(df1): current_dpe_tot_f = df1.select(F.sum('tot_f')).first()[0] + df2.select(F....
def scan_dir_for_files(path, recursive=False): for entry in os.scandir(path): if recursive and entry.is_dir() and not entry.is_symlink(): for entry in scan_dir_for_files(entry.path, True): yield entry elif entry.is_file(): yield entry.path def rename_image(arg...
The code processes media files by renaming images and videos based on their extensions, using command-line arguments to control directory organization, recursive scanning, and simulation mode. It scans files, checks their extensions against predefined types, and applies corresponding renaming functions without modifyin...
def main(): parser = argparse.ArgumentParser() parser.add_argument( "--dirs", help="Move files into a date-based directory tree", action="store_true", ) parser.add_argument( "--recursive", help="Match files recursively", action="store_true" ) parser.add_argument( ...
def __next_DFS_step(self): if self.__ds and Search.found == None: s = self.__ds.pop() self.__maze.print("(DFS mode) Visiting " + " " + str(s)) self.__maze.tile_color[s.i][s.j][s.k] = 2 if self.__prev_node != None: self.__maze.tile_color[self.__prev...
The `next_step` method selects and executes the appropriate traversal/search algorithm based on the `self.mode` value. It directs to DFS, BFS, UCS, A*, or greedy algorithms by calling corresponding private methods, enabling flexible pathfinding or exploration strategies in a graph or grid structure.
def next_step(self): if self.mode == 1: self.__next_DFS_step() elif self.mode == 2: self.__next_BFS_step() elif self.mode == 3: self.__next_UCS_step() elif self.mode == 4 or self.mode == 5: self.__next_A_star_step() elif self.mode =...
def detect_vertical_horizantal_lines(self,lines_array,voting,angle): """ This function find all lines horizantal/vertical from hough transfroms and give the bounding lines required. :param lines_array: lines array :param voting: Accumulator array :param angle: horizantal / vertic...
The function extracts horizontal and vertical lines from an accumulator array using thresholding, processes them to remove redundant lines and adjust spacing, then identifies question coordinates and pixel markings from a Canny edge image. It saves detected markings to a file and returns coordinates along with a dictio...
def extract_markings(self,voting,edge_image): """ Extract the markings using ard thresholds :param voting: Accumulator array :param edge_image: CAnny edge detector image :return: """ lines_array = np.zeros((voting.shape)) self.detect_vertical_horizantal_l...
def edge_detection(self,kernal_size=3,gauss_sigma=0.5): """ This function performs the canny edge detection :param kernal_size: filter kernal size :param gauss_sigma: sigma of gaussian filter :return: detected edge image and gradient magnitude of image """ pad = m...
This function performs OMR marking extraction from an image by detecting edges, applying Hough transform voting, identifying question coordinates and markings, then classifying answers and saving results to a specified output file.
def omr_extraction(self): """ this function extracts the omr markings and stores extraction in file :return: """ edge_image, gradient_xy = self.edge_detection(gauss_sigma=5) voting = self.hough_transform_voting(edge_image, gradient_xy) question_coordinates, marki...
def read(self) -> Union[None,str]: line = "" while True: line_temp = self._read() if line_temp is None: return None line += line_temp.strip() if self.is_in_comment: if "*/" in line: ...
This function parses a class definition from a stream of lines, extracting its name, fields (properties and functions), and body line number. It searches for the "class" keyword, processes subsequent lines to identify class components using macros, and returns a ParsedClass object or None if the class is not found.
def parse_class(self,macro_iine:str) -> Union[None,ParsedClass]: search_str = "class " line = self.read() while line is not None and search_str not in line: line = self.read() if line is None: return None split_result = line[line.index(search_st...
def read(self) -> Union[None,str]: line = "" while True: line_temp = self._read() if line_temp is None: return None line += line_temp.strip() if self.is_in_comment: if "*/" in line: ...
This function parses a struct definition from a code stream, extracting its name, fields (properties/functions), and body line number. It searches for "struct", captures the name, then processes subsequent lines to collect reflected properties/functions using macros, stopping at "};". The result is a ParsedStruct objec...
def parse_struct(self,macro_iine:str) -> Union[None,ParsedStruct]: search_str = "struct " line = self.read() while line is not None and search_str not in line: line = self.read() if line is None: return None split_result = line[line.index(search...
def write_line(self,line: str): self.file.write(f"{line}\n") def include(self,file: str): self.write_line(f"#include \"{file}\"") def write_id(self): self.write_lines(["#ifdef REFLECT_FILE_ID", "#undef REFLECT_FILE_ID", "#endif", ...
The main task of the code is to generate a C++ header file by writing pragmas, including reflection-related headers, outputting an ID, and iterating through parsed types to write class/struct definitions with empty lines for formatting. It prepares a header for reflection systems by integrating macros and dependencies ...
def generate_header(self): self.write_line("#pragma once") self.include("reflect/Macro.hpp") self.include("reflect/Reflect.hpp") self.include("reflect/Factory.hpp") self.include("reflect/wrap/Wrap.hpp") self.write_line("") self.write_id() self.write_line...
def read(self) -> Union[None,str]: line = "" while True: line_temp = self._read() if line_temp is None: return None line += line_temp.strip() if self.is_in_comment: if "*/" in line: ...
The main task of the code is to parse a file line by line, identifying lines containing specific macros (REFLECT_CLASS_MACRO or REFLECT_STRUCT_MACRO), extracting corresponding class/struct definitions using dedicated parsing methods, and compiling them into a ParsedFile object with the original file path and collected ...
def parse(self) -> Union[None,ParsedFile]: with open(self.file_path,'r') as f: self.file = f result = ParsedFile() result.file_path = self.file_path line = self.read() while line is not None: if REFLECT_CLASS_MACRO in line: ...
def apiname_convert_sentence(apiname): name_words_list = apiname.split('-') suffix = name_words_list[-1] if (suffix[0] == 'v') & suffix[1:].isdecimal(): name_words_list.pop() sentence = " ".join(name_words_list) + "." return sentence def get_sentences(): # sql = "select API from cmb_prod...
The main task of the code is to process an API name by converting it into a target sentence, retrieve a list of API names and their corresponding sentences, and execute a test function that evaluates the target sentence against the list using a parameter of 10. This likely involves comparing or analyzing the target sen...
def main_process(apiname): target_sentence = apiname_convert_sentence(apiname) list = get_sentences() api_namelist = list[0] sentences = list[1] return test(api_namelist, sentences, target_sentence, 10)
def getRepo(repo,username,local='repos'): repo_url = f'https://github.com/{username}/{repo}.git' local_path = f'./{local}/{repo}' # Clone the repository if it doesn't exist locally if not os.path.exists(local_path): git.Repo.clone_from(repo_url, local_path) repo = git.Repo(local_path) re...
The code retrieves Java files, commit history, methods, and documentation from a GitHub repository, then writes this data into a JSONL file. It fetches repository details, extracts relevant code, filters commits by timestamp, identifies new methods, and stores results with metadata like authors and timestamps for analy...
def getData(reponame,username,time_unix=1609434000,output_file="./data.jsonl",local='repos'): #get repo print("getting repo") try: repo=getRepo(reponame,username,local) except Exception as e: exception_message = str(e) print("Exception Message:", exception_message) return...
def _check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(ev...
The code runs a game loop that continuously checks for events, updates the rocket and bullets, renders the screen, and maintains a 60 FPS frame rate, while printing the number of active bullets for debugging.
def run_game(self): while True: self._check_events() self.rocket.update() self._update_bullets() print(len(self.bullets)) self._update_screen() self.clock.tick(60)
def textProcessing(text): text = text.lower() ## Remove the \n's from the text text = text.replace('\n', " ") ## Remove the punctuation text = text.translate(str.maketrans('', '', string.punctuation)) ## Remove numbers text = text.translate(str.maketrans('', '', string.digits)) ## Re...
This function implements a search engine that processes user queries by calculating TF-IDF vectors, computes cosine similarity between queries and documents, retrieves relevant document URLs, and displays results in batches. It allows users to input search terms, navigate through results, and exit the search process.
def startSearchTerminal(): while(1): print("**** Enter the string to search ****") print("** Type -1 to exit the search engine") searchText = input("Enter the string now ...") if (searchText == str(-1)): return queriesDoc = list() queriesDoc.append(search...
def is_string(definition: dict) -> bool: return is_type_included(definition, get_reftype_function(data_type.STRING_TYPE)) def is_number(definition: dict) -> bool: if is_string(definition): # Handle union type, give priority to wider scope types return False return is_type_included(definition...
This function checks if a given definition is not a simple type (string, number, big integer, or long) and then verifies if it includes the boolean type, returning True if both conditions are met.
def is_boolean(definition: dict) -> bool: if is_string(definition) or is_number(definition) or is_big_integer(definition) or is_long(definition): # Handle union type, give priority to wider scope types return False return is_type_included(definition, get_reftype_function(data_type.BOOLEAN_TYPE))
def is_string(definition: dict) -> bool: return is_type_included(definition, get_reftype_function(data_type.STRING_TYPE)) def is_big_integer(definition: dict) -> bool: return False def is_long(definition: dict) -> bool: return is_type_included(definition, get_reftype_function(data_type.INTEGER_TYPE)) def is...
The function determines if a given dictionary definition represents a "simple property" by checking if it matches any of several basic data types, such as string, integer, number, boolean, date/time formats, or binary data. It returns True if any of these conditions are met, indicating the property is simple.
def is_simple_property(definition: dict) -> bool: return ( is_string(definition) or is_big_integer(definition) or is_long(definition) or is_number(definition) or is_boolean(definition) or is_date(definition) or is_time(definition) or is_datetime(defini...
def update_neutral(self): options = self.direction_options() if self.is_at_intersection() or self.last == (self.rect.centerx, self.rect.centery): self.direction = self.chase_path(options) if self.direction == 'u' and 'u' in options: self.rect.centery -= self.speed ...
The code updates an object's state based on its conditions: if in 'normal' state, it checks 'blue' or 'return' flags to call respective update methods (update_neutral, update_blue, update_return), then records the object's current position (rect center) to 'self.last'
def update(self): if self.state['normal']: if not self.state['blue'] and not self.state['return']: self.update_neutral() elif self.state['blue']: self.update_blue() elif self.state['return']: self.update_return() sel...
def generate_chains(nChains, alphabet, method, minLength, maxLength): chains = [] for i in range(nChains): length = randomRange(minLength, maxLength) chains.append(method(length, alphabet)) return chains def output_chains(name, startIndex, file, chains): if isinstance(chains, l...
The main task of the code is to generate synthetic test data for bioinformatics formats, including FASTQ, FASTA, and SAM files. It creates sequences using various generation methods (random, Fibonacci, etc.) with the alphabet ['m', 'i', 's', 'p'], adapts them for alignment, and writes them to files. The code also gener...
def generate_test(): ALPHABET = ['m', 'i', 's', 'p'] GENERATION_METHODS = [generate_random_sequence, generate_same_before, generate_multiple, generate_different, generate_fibonacci] CHAINS_PER_TYPE = 5 # Set seed random.seed(0) fastqNames = None fastqChains = [] if MISSISSIPPI: ...
def genomes_to_file(filename, genomes): bwtList = preprocess_genomes(genomes) outputFile = open(str(filename)+".dat", "wb") pickle.dump(bwtList, outputFile) return bwtList def searchPattern(p, bwtMatcher): if p == "": return left, right = 0, len(bwtMatcher.f) for a in reversed(p...
The main task of the code is to perform exact pattern matching using an FM-index on a genome sequence. It preprocesses a genome file (FASTA format) into a BWT structure, optionally storing it in a .dat file. When provided with reads (FASTQ format), it searches for exact matches of each read in the genome using the prep...
def main(): argparser = argparse.ArgumentParser( description="FM-index exact pattern matching", usage="\n\tfm -p genome\n\tfm genome reads" ) argparser.add_argument( "-p", action="store_true", help="preprocess the genome." ) argparser.add_argument( "genome", ...
def install(session: nox.Session, *groups, dev: bool = True, editable: bool = False, no_self=False, no_default=False): other_args = [] if not dev: other_args.append("--prod") if not editable: other_args.append("--no-editable") if no_self: other_args.append("--no-self") if no_...
The code's main task is to lint and auto-fix code using Ruff for Python syntax checks and formatting, ShellCheck for shell script formatting, and Readable for Python code style enforcement, ensuring code quality and consistency during CI/CD processes.
def format_(session): """Lint the code and apply fixes in-place whenever possible.""" install(session, "lint", no_self=True, no_default=True) session.run("ruff", "check", "--fix", ".") run_shellcheck(session, mode="fmt") run_readable(session, mode="fmt") session.run("ruff", "format", ".")
def install(session: nox.Session, *groups, dev: bool = True, editable: bool = False, no_self=False, no_default=False): other_args = [] if not dev: other_args.append("--prod") if not editable: other_args.append("--no-editable") if no_self: other_args.append("--no-self") if no_...
The main task of the code is to run multiple linters and formatters in readonly mode to check code quality without making changes. It installs required packages, executes Ruff for linting/formatting, Mypy for type-checking, Codespell for spelling, Shellcheck for shell scripts, and Readable for readability checks, ensur...
def lint(session): """Run linters in readonly mode.""" # "test" group is required for mypy to work against test files install(session, "lint", "test") session.run("ruff", "check", "--diff", "--unsafe-fixes", ".") session.run("ruff", "format", "--diff", ".") session.run("mypy", ".") session.r...
def install(session: nox.Session, *args): groups = [] for group in args: groups.extend(["--group", group]) session.run("pdm", "install", "--check", *groups, external=True) def run_shellcheck(session, mode="check"): shellcheck_cmd = [ "docker", "run", "--platform", ...
The main task of the code is to lint and format code in-place using tools like Ruff, ShellCheck, and Readable. It installs a linting package, runs Ruff to check and fix issues, formats code with Ruff, and applies formatting rules via ShellCheck and Readable in "fmt" mode to ensure code consistency and quality.
def format_(session): """Lint the code and apply fixes in-place whenever possible.""" install(session, "lint") session.run("ruff", "check", "--fix", ".") run_shellcheck(session, mode="fmt") run_readable(session, mode="fmt") session.run("ruff", "format", ".")
def install(session: nox.Session, *args): groups = [] for group in args: groups.extend(["--group", group]) session.run("pdm", "install", "--check", *groups, external=True) def run_shellcheck(session, mode="check"): shellcheck_cmd = [ "docker", "run", "--platform", ...
The main task of the code is to execute multiple linters and formatters in readonly mode to check code quality, style, security, and type correctness without modifying the code. It runs tools like Ruff, codespell, shellcheck, bandit, and mypy, using configuration files and command-line arguments to validate code struct...
def lint(session): """Run linters in readonly mode.""" install(session, "lint") session.run("ruff", "check", "--diff", ".") session.run("codespell", ".") run_shellcheck(session, mode="check") run_readable(session, mode="check") session.run("ruff", "format", "--diff", ".") session.run("ba...
def start_worker(self): parallel_sampler.populate_task(self.env, self.policy) if self.plot: plotter.init_plot(self.env, self.policy) def init_opt(self): # First, create "target" policy and Q functions target_policy = pickle.loads(pickle.dumps(self.policy)) target_qf ...
The code trains a reinforcement learning policy using Hindsight Experience Replay (HER). It collects trajectories by interacting with the environment, stores episodes in a buffer, and updates the policy through sampled batches. The training includes goal-oriented exploration, parameter updates, and periodic evaluation,...
def train(self): # This seems like a rather sequential method print("SUCCESS") self.start_worker() self.init_opt() itr = 0 path_length = 0 path_return = 0 terminal = False observation = self.env.reset() sample_policy = pickle.l...
def print(self, *args): if self.rank==0: print(*args) def apply(self, func, inputs): return list(map(func, inputs)) def prune(self, verbose=False): self.apply(self.find_mask, self.layers) self.apply(self.find_mask_fp, self.fp_layers) self.apply(self.apply_mask, self.l...
The code performs iterative pruning to achieve a target pruning rate by adjusting the beta parameter using binary search. It initializes pruning settings, copies model checkpoints, and iteratively adjusts beta to converge on the optimal pruning level that meets the specified rate, returning final FLOPs and parameters a...
def initialize(self, rate, n_iter=10): self.print("="*80) self.print("Finding pruning settings to achieve the target pruning rate") self.print("="*80) self.apply(self.set_arch_hard, self.layers) checkpoints = copy.deepcopy(self.model.state_dict()) self.beta = 0.15 ...
def get_result(self, view): """ Gets the result of the API call. Args: view: The view that is being requested Returns: A dictionary containing the decoded json result. """ try: result = requests.get(self.get_url(view)) return resu...
The main task of the code is to generate a formatted multiline string summarizing current weather conditions from a provided or fetched data structure. It extracts location, temperature, weather description, wind details, and humidity from the input `result` dictionary, combining them into a human-readable report. If n...
def get_conditions(self, result=None, ): """ Returns: A multiline string summary of the current conditions. """ if not result: result = self.get_result('conditions') conditions = "\nCurrent weather for %s \n" % \ (result['current_observation']...
def get_replica_list(logger, key): global HALF_SERVER logger.info("Fetching Replicat List for key: {0}".format(key)) replica_list = [] if HALF_SERVER: if 0<=key<128: replica_list = [0,1] elif 128<=key<256: replica_list = [1,0] else: logger.i...
This function handles PUT/GET operations under Consistency Level One. It checks if the current replica is authorized for the requested key, updates/increments counters, modifies the key-value store, sends responses, and updates replicas. It ensures proper access control and data consistency across replicas for distribu...
def process_consistency_one(logger, replica_info, replica_id, client_conn, request, request_type): # request_type = GET # request_type = PUT global READ_WRITE_COUNT, KEY_VALUE_STORE, TIMESTAMP replica_list = [] if request_type==PUT: logger.info("Processing Consistency One Put Request") ...
def get_replica_list(logger, key): global HALF_SERVER logger.info("Fetching Replicat List for key: {0}".format(key)) replica_list = [] if HALF_SERVER: if 0<=key<128: replica_list = [0,1] elif 128<=key<256: replica_list = [1,0] else: logger.i...
The function processes a consistency quorum request (PUT/GET) by checking if the current replica is part of the key's replica list, incrementing read/write counters, and verifying quorum through heartbeat checks with other replicas. If at least two replicas are available, it updates the replicas; otherwise, it sends an...
def process_consistency_quorum(logger, replica_info, replica_id, client_conn, request, request_type): # request_type = PUT global READ_WRITE_COUNT, KEY_VALUE_STORE replica_availability = 0 replica_list = [] if request_type==PUT: logger.info("Processing Consistency Quorum Put Request") ...
def get_replica_id(replica_name): return int("".join(x for x in replica_name if x.isdigit())) def load_store_key_value_store(logger, is_store): global KEY_VALUE_STORE if not os.path.exists("{0}out/".format(base_dir)): logger.info("Creating Other directory: {0}".format("{0}out/".format(base_dir))) ...
This code runs a key-value store server that handles client requests for data retrieval (get), storage (put), replica synchronization, heartbeat signals, and display operations. It supports consistency levels (one or quorum) for distributed operations, processes incoming messages via TCP sockets, logs activities, and g...
def run_server(logger, args): global TIMESTAMP, READ_WRITE_COUNT replica_name = args.name # replica_name = "replica0" # replica_name = "replica1" ip_addr = socket.gethostbyname(socket.getfqdn()) port_num = args.port # port_num = 9090 replica_info = get_replica_info(logger) replica_...
def compute_bottom(box_a, box_b): # obtain ground corners and area, not containing the height corners1 = Box3D.box2corners3d_camcoord(box_a) # 8 x 3 corners2 = Box3D.box2corners3d_camcoord(box_b) # 8 x 3 # get bottom corners and inverse order so that they are in the # counter-clockwise...
The code computes the 3D Intersection over Union (IoU) or Generalized IoU (GIoU) between two 3D bounding boxes, assuming objects are parallel to the ground. It calculates 2D intersection area, overlap height, and 3D volumes. For GIoU, it adjusts using convex hull areas. Returns IoU as intersection/union or GIoU with co...
def iou(box_a, box_b, metric='giou_3d'): ''' Compute 3D bounding box IoU, only working for object parallel to ground Input: Box3D instances Output: iou_3d: 3D bounding box IoU box corner order is like follows 1 -------- 0 top is bottom because y direction is negati...
def _get_credentials(self) -> Any: """Authenticate with Google and save credentials. Download the credentials.json file with these instructions: https://developers.google.com/drive/api/v3/quickstart/python. Copy credentials.json file and rename it to client_secrets.json file which will be u...
The main task of the code is to load data from Google Drive by either a folder ID or specific file IDs. It uses credentials to authenticate, checks if a folder ID is provided to load documents from that folder, or loads documents from given file IDs if no folder is specified. The function returns a list of Document obj...
def load_data( self, folder_id: str = None, file_ids: List[str] = None ) -> List[Document]: """Load data from the folder id and file ids. Args: folder_id: folder id of the folder in google drive. file_ids: file ids of the files in google drive. Returns: ...
def get_dataframe_KIT(data): """Input: data Output: Dataframe with (key, press_time, release_time)""" keys_in_pipeline = [] result_key = [] press = [] release = [] for row_idx in range(len(data)): keys_in_pipeline = list(data) # print("Keys in pipeline: ", keys_in_pipeline) ...
The main task of the code is to extract specific KIT features from a pandas DataFrame based on the provided `kit_feature_index` (1–4). It processes the input data, validates the index, and returns the corresponding feature set using dedicated functions like `get_KIT_features_F1` to `F4` for different feature extraction...
def kit_from_dataframe(df: pd.DataFrame, kit_feature_index: int): df = get_dataframe_KIT(df.values) user_data = df.values assert 1 <= kit_feature_index <= 4 if kit_feature_index == 1: return get_KIT_features_F1(user_data) elif kit_feature_index == 2: return get_KIT_features_F2(user_d...
def get_dataframe_KIT(data): """Input: data Output: Dataframe with (key, press_time, release_time)""" keys_in_pipeline = [] result_key = [] press = [] release = [] for row_idx in range(len(data)): keys_in_pipeline = list(data) # print("Keys in pipeline: ", keys_in_pipeline) ...
The main task of the code is to extract and organize keystroke dynamics features from multiple CSV files in a directory. It processes each valid CSV file by reading, cleaning, and analyzing data to compute four distinct feature sets (F1-F4) for each user. The results are stored in separate dictionaries, indexed by user...
def get_all_users_features_KIT(directory): users_feat_dict_f1 = {} users_feat_dict_f2 = {} users_feat_dict_f3 = {} users_feat_dict_f4 = {} user_files = os.listdir(directory) for i in tqdm(range(len(user_files))): user_file = user_files[i] if ".csv" in user_file and not user_file....
def make_bbmass_gender_df(): demographics = pd.read_csv("BBMASS_Demographics.csv") return demographics def bbmass_kit_from_dataframe(df: pd.DataFrame, kit_feature_index: int): df = bbmass_get_dataframe_KIT(df.values) user_data = df.values assert 1 <= kit_feature_index <= 4 if kit_feature_index =...
The code processes CSV files from a directory to generate statistical features (mean, median, quartiles, standard deviation) for four task types (F1-F4) from user timing data. It merges these features with user demographics, appending results into separate DataFrames, then concatenates them into a final combined DataFr...
def bbmass_generate_kit_features_df(): bbmass_demographics = make_bbmass_gender_df() # TODO: dir = "Desktop/" f1 = pd.DataFrame() f2 = pd.DataFrame() f3 = pd.DataFrame() f4 = pd.DataFrame() user_id = 1 directory = dir user_files = os.listdir(directory) for i in tqdm(range(len...
def make_bbmass_gender_df(): demographics = pd.read_csv("BBMASS_Demographics.csv") return demographics def bbmass_kht_from_dataframe(df: pd.DataFrame): user_data = df.values user_feat_dict = bbmass_get_KHT_features(user_data) return user_feat_dict def get_mean_timings(data): if math.isnan(sum(da...
The function generates a statistical features DataFrame from CSV files by calculating key metrics (mean, median, quartiles, standard deviation) for each user's data, appending these with gender information from demographics, and returning a cleaned DataFrame excluding entries with zero standard deviation.
def bbmass_generate_kht_features_df(): final_df = pd.DataFrame( columns=[ "ID", "Key(s)", "Mean", "Median", "Standard Deviation", "First Quartile", "Third Quartile", "Gender", ] ) bbmass_demograph...
def make_gender_df(): demographics = pd.read_csv("Filtered_Demographics.csv") return demographics def kit_from_dataframe(df: pd.DataFrame, kit_feature_index: int): df = get_dataframe_KIT(df.values) user_data = df.values assert 1 <= kit_feature_index <= 4 if kit_feature_index == 1: return...
The function generates statistical features from CSV files in a specified directory, calculating mean, median, quartiles, and standard deviation for timing data across four kits. It merges these features with user demographics and returns a combined DataFrame for analysis.
def generate_kit_features_df(use_train=True): demographics = make_gender_df() if use_train: dir = "Twitter/" else: dir = "Test/" f1 = pd.DataFrame() f2 = pd.DataFrame() f3 = pd.DataFrame() f4 = pd.DataFrame() user_id = 1 directory = dir user_files = os.listdir(dir...
def bbmas_get_all_users_features_advanced_word(directory): users_feat_dict = {} user_files = os.listdir(directory) for i in tqdm(range(len(user_files))): user_file = user_files[i] print("File:", directory + user_file) data_frame = pd.read_csv(directory + user_file) user_data...
The function generates a DataFrame containing word-level features (mean, standard deviation, median of key hold and flight times) for each user, using either Desktop or Twitter data based on the 'use_bbmass' parameter. It aggregates statistical metrics for each word across users, appending zeros for missing words, and ...
def generate_word_level_features_df(use_bbmass: bool = True): word_features = [] words = [] curr_dict_index = 1 final_words_set = set() if use_bbmass: desktop_advanced_word_features = bbmas_get_all_users_features_advanced_word( "Desktop/" ) else: # TEMP - chan...
def bbmass_generate_kht_features_df(): final_df = pd.DataFrame( columns=[ "ID", "Key(s)", "Mean", "Median", "Standard Deviation", "First Quartile", "Third Quartile", "Gender", ] ) bbmass_demograph...
This function retrieves unique keys from feature data based on the input FeatureType. It loads or generates DataFrames (KHT/Kit) from pickle files, checks for invalid data, and aggregates unique "Key(s)" values. For WORD_LEVEL, it returns word-level keys. The final output is a list of unique keys from the primary DataF...
def get_unique_keys(feature_type: FeatureType): if feature_type == FeatureType.KHT: # os.chdir("/content/drive/My Drive/Fake_Profile/") if os.path.exists("bbmass_kht_df.pkl"): with open("bbmass_kht_df.pkl", "rb") as f: df = pickle.load(f) else: df = bb...
def showStartScreen(): """ Shows the game's start screen Parameters ---------- titlefont: Font Font of the game's start screen titleText: Surface Text on the game's start screen titleTextRect: Location of text on the game's start screen...
(The main task of the code is to initialize a Pygame-based Snake game by setting up the display, clock, and font modules. It displays a start screen, runs the game loop, and shows a game-over screen. Global variables CLOCK, SCREEN, and FONT are initialized for game timing, visualization, and text rendering, respectivel...
def main(): """ Main function for game initialization Parameters ---------- CLOCK: (class) CLOCK pygame clock to run the game SCREEN: (module) display pygame module for game visualization FONT: (module) font pygame module for message vi...
def revealCell(self, x : int , y : int, firstBox : Canvas.create_rectangle, lastBox : Canvas.create_rectangle) -> None: """shows the cell with coordinates x and y pre: mouse x coords , y mouse coords post: deletes the cell box click by user""" # assigns id of box that user clicked on ...
The method `cellActive` binds mouse events to handle cell interactions in a game grid, enabling left-clicks to reveal cells and right-clicks (OS-dependent) to place or remove flags, with double right-clicks removing flags, ensuring cross-platform compatibility between macOS and Windows.
def cellActive(self) -> None: '''Activates the mouse click binding depending on operating system.''' # left click to reveal cell self.board.bind( "<Button-1>", lambda event: self.revealCell(event.x, event.y, self.firstBox, self.lastBox)) if self.os == "Darwi...
def resetMinesandCells(self) -> None: try: self.field.clear() self.UI.mineField.clear() self.field = self.UI.mineField = [[Cell() for j in range(self.size)] for i in range(self.size)] self.UI.gameEnd = False self.placeMine(self.size) # place mine on b...
The main task of the code is to run a Minesweeper game loop, initializing the UI, handling game state transitions, checking win/loss conditions, updating the board, and managing user interactions until the game ends, at which point it displays the result and resets the game state for potential replay.
def playGame(self) -> None: """ runs the game """ self.UI.introWindow() # created window with intro message self.UI.gameBar() # shows the information bar self.UI.createBoard() # creates the minesweeper board self.UI.printBoard() # print board to console while Tr...
def buttonImageDefault(self): ''' sets smiley button to it's default image''' self.resetButton["image"] = self.images[0] def createBoard(self) -> None: """ creates the entire board """ self.drawLines() self.placeAdjacency() self.createCellBox() def cellActive(self) -> Non...
The main task of the code is to restart the game by resetting all game values to their initial states, destroying the existing board, and recreating a new board. It clears the timer, resets mine counters, releases locked cells, and rebuilds the canvas with updated game components to prepare for a new game session.
def restartGame(self) -> None: '''Restarts game, resets all values to intital state and recreated the board''' self.board.destroy() self.timer.set(0) self.value.set(None) # holds reference to .after() method self.after_id = None self.buttonImageDefault() ...
def lcd_init(): # Initialise display lcd_byte(0x33,LCD_CMD) # 110011 Initialise lcd_byte(0x32,LCD_CMD) # 110010 Initialise lcd_byte(0x06,LCD_CMD) # 000110 Cursor move direction lcd_byte(0x0C,LCD_CMD) # 001100 Display On,Cursor Off, Blink Off lcd_byte(0x28,LCD_CMD) # 101000 Data length, number of lines, font...
The main task of the code is to initialize a LCD display and keypad interface using Raspberry Pi GPIO pins. It configures pins for LCD control/data lines, backlight, and keypad rows/columns, then initializes the display, toggles the backlight, and runs a test function to verify functionality.
def main(): # Main program block GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers GPIO.setup(LCD_E, GPIO.OUT) # E GPIO.setup(LCD_RS, GPIO.OUT) # RS GPIO.setup(LCD_D4, GPIO.OUT) # DB4 GPIO.setup(LCD_D5, GPIO.OUT) # DB5 GPIO.setup(LCD_D6, GPIO.OUT) # DB6 GPIO.setup(LCD_D...
def get_creds(loc=Path.cwd() / ".credentials.ini"): config_f = ConfigParser() config_f.read(loc) return config_f.get("credentials", "username"), config_f.get( "credentials", "password" ) def selenium_scrape(login=False, **kwargs): # returns html for BeautifulSoup # driver = webdriver.Chr...
The code automates scraping data from a webpage by scrolling through a scrollable table, extracting items, searching them against a local JSON database, and handling responses. It uses Selenium for browser automation, scrolls to load all content, processes each item by querying a database, and logs skipped entries.
def main(login): usr, pwd = get_creds() driver = selenium_scrape(login, usr=usr, pwd=pwd) # Get initial height of the page scrollable_div = driver.find_element(By.CSS_SELECTOR, "div.grid-scrolling-table") scroll_height = driver.execute_script( "return arguments[0].scrollHeight;", scrollable...
def tot_summary_stats(self, X, parents, windows, L, D_dict, model_case): ''' :param X: event labels under consideration (list of event labels) :param parents: parents of X (list of event labels) :param windows: windows for parents of X (list of integers, in the same order as parents) :param L: label...
This function computes optimal parameters (thetas) and log likelihood (LL) for a statistical model. It processes input data (X) with given parameters (parents, windows, L, D_dict, alpha), calculates summary statistics, derives optimal thetas via optimization, and evaluates model likelihood using these thetas. The resul...
def opt_model_given_windows(self, X, parents, windows, L, D_dict, alpha, model_case): if len(X) < len(L): num_states_X = len(X) + 1 else: num_states_X = len(X) # summary statistics counts, summ_counts, counts_list, _ = self.tot_summary_stats(X, parents, windows, L, D_dict, model_case) #...
def conv_block(self, inputs, filter_size, input_channels, output_channels): W_conv = weight_variable([filter_size, filter_size, input_channels, output_channels]) b_conv = bn_bias_variable([output_channels]) self.weights.append(W_conv) self.weights.append...
This code constructs a neural network for processing input planes (like a game board) through convolutional and residual blocks, then generates two outputs: a policy head (for action probabilities) and a value head (for estimating the game state's value). It reshapes inputs, applies convolutional layers, uses residual ...
def construct_net(self, planes): # NCHW format # batch, 112 input channels, 8 x 8 x_planes = tf.reshape(planes, [-1, 112, 8, 8]) # Input convolution flow = self.conv_block(x_planes, filter_size=3, input_channels=112, ...
def true_coords_to_arena(self, point): size_ratio = self.size_ratio() arena_point = [ (point[0] - self.MIN_POINT_COORD - self.zoom_focus_point[0]) * size_ratio, (point[1] - self.MIN_POINT_COORD - self.zoom_focus_point[1]) * size_ratio ] return arena_point def clos...
This code draws points on a game arena using Pygame. It renders all points as black circles, identifies the closest point to the mouse cursor, and highlights it in red if it's selected (collides with the mouse). The main tasks are rendering points and visually indicating user interaction with the closest point.
def draw_points_on_arena(self): for point in self.points: pygame.draw.circle(self.arena, (0, 0, 0), self.true_coords_to_arena(point), self.NODE_SIZE) closest_point = self.closest_point_to_(self.point_under_mouse()) is_selected = self.does_point_collide_with_mouse(closest_point) ...
def is_mouse_in_arena(self): mouse_pos = pygame.mouse.get_pos() if not self.arena.get_rect().collidepoint(*mouse_pos): return False else: return bool(pygame.mouse.get_focused()) def point_under_mouse(self): return self.arena_coords_to_true(pygame.mouse.get_pos()) ...
This code handles adding or removing points in a graphical interface based on mouse clicks. It checks if a left mouse click occurs within the arena, then either adds a new point at the cursor location or removes the closest existing point if it collides with the cursor. The function manages dynamic point manipulation f...
def handle_add_delete_node(self, events): for event in events: if event.type == pygame.MOUSEBUTTONDOWN and event.button == pygame.BUTTON_LEFT \ and self.is_mouse_in_arena(): selected_coords = self.point_under_mouse() closest_point = self.closest_po...
def is_mouse_in_arena(self): mouse_pos = pygame.mouse.get_pos() if not self.arena.get_rect().collidepoint(*mouse_pos): return False else: return bool(pygame.mouse.get_focused()) def size_ratio(self): """ Returns a floating point number representing a ratio...
The function handles zooming by adjusting the zoom focus point based on mouse position and wheel input. It centers the zoom if the mouse is outside the arena, calculates displacement from the focus point, updates the zoom level, and repositions the focus point to maintain visibility, ensuring it stays within defined bo...
def handle_zoom(self, events): # zooming to the center if mouse is outside of arena mouse_pos = pygame.mouse.get_pos() if not self.is_mouse_in_arena(): mouse_pos = self.ARENA_WIDTH / 2, self.ARENA_HEIGHT / 2 # reading current zoom parameters size_ratio = self.size_ra...
def handle_exit(self, events): for event in events: if event.type == pygame.QUIT: self.save_changes_to_file("data/json1") sys.exit() def handle_playstop(self, events): if not self.playstop_rect.collidepoint(pygame.mouse.get_pos()): return ...
This method processes user inputs via Pygame events, dispatching actions like exit handling, play/pause toggling, direction control, zoom, swiping, and node management. It gathers all events, then routes them to specialized handlers to manage game state interactions and user interface adjustments.
def process_inputs(self): events = pygame.event.get() self.handle_exit(events) self.handle_playstop(events) self.handle_play_direction(events) self.handle_zoom(events) self.handle_swiping(events) self.handle_add_delete_node(events)
def names_a_directory(path): # type: (str) -> bool """Return True if the given path names a directory vs. a file (even on GCS, existing or yet to be created) by checking if the path ends with a '/'. """ return path.endswith(os.sep) def download_file(self, sub_path, local_path): # type: (str,...
This function downloads files and directories from a storage system, starting with the specified sub_path prefix, to a local directory (local_prefix), preserving their relative structure. It creates necessary directories, handles both files and directories, and returns True if all downloads succeed, logging exceptions ...
def download_tree(self, sub_path, local_prefix): # type: (str, str) -> bool """Download all files and directories that begin with the sub_path prefix (within the storage_prefix) to their same relative paths in local_prefix, making directories if needed. Return True if successful...
def take_pic(self): self.img = self.pibot.get_image() if not self.data is None: self.data.write_image(self.img) def detect_target(self): if self.command['inference'] and self.detector is not None: self.detector_output, self.network_vis = self.detector.yolo_detection(self....
The code regenerates a map by detecting new fruits in the environment. It captures images, identifies unique detected items, and checks if they are not already in the fruit list. If a new fruit is found, its image and pose are stored. When three instances of a new fruit are detected, it is added to the fruit list, and ...
def RegenerateMap(self): # Take picture of surroundings # Find fruits within it # If fruit is found that is not on the list execute the following # Else Continue self.command['inference'] = True self.take_pic() self.detect_target() ...
def mutate_protein(protein, p_mutation, LG_matrix): """Mutate a residue to another residue based on the LG matrix.""" mutant = copy.deepcopy(protein) # Necessary! location = np.random.choice(len(mutant), p=p_mutation) amino_acid = mutant[location] p_transition = LG_matrix.loc[amino_acid] LG_res...
The main task of this code is to mutate a population of amino acid sequences using the LG+I+G substitution model, ensuring stability by iteratively applying mutations and replacing unstable sequences with stable clones from a tree. The process repeats until all sequences achieve stability or a maximum iteration limit i...
def mutate_population(current_generation, n_mutations_per_gen, tree, p_mutation, LG_matrix, stability_table, omega): """Mutate a set of sequences based on the LG+I+G model of amino acid substitution. """ counter = 0 successful_mutation = False while not successful_mutation...
def calc_bifurcation_interval(n_generations, n_clones, n_roots): """Calculate the bifurcation interval (in generations) given that there must be at least three proteins left in each branch after bifurcation.""" # Original iterative algorithm # pool = n_clones - n_roots # n_phases = 1 # n_bifuration...
The code simulates protein evolution over generations using an LG matrix, applying mutations, death rates, and bifurcations. It tracks population stability, records statistics, generates plots, and saves data. The function returns a history of each generation's population and stability metrics, enabling analysis of evo...
def evolve(n_generations, population, stability_table, omega, sites, p_mutation, mutation_rate, death_rate, tree, LG_matrix, plot_omega, plot_epsilon, record, out_paths): """Generation generator - mutate a protein for a defined number of generations according to an LG matrix and gamma dist...
def get_stability_table(clone_size, amino_acids, distributions): """Generate a dataframe describing the stability contributions for each amino acid (columns) in each position (rows) of the generated protein. """ assert len(distributions) if isinstance(distributions, (tuple, list)) \ and is...
The `pesst` function initializes and runs evolutionary simulations to model protein stability evolution. It validates parameters, generates stability distributions (e.g., Tokuriki-based), sets up initial protein structures, and simulates mutations, selection, and population dynamics over generations. The code tracks st...
def pesst(n_generations=2000, stability_start='high', omega=0, mu=0, sigma=2.5, skew=0, distributions='Tokuriki', n_clones=52, n_roots=4, clone_size=100, p_invariant=0.1, initial_protein='', invariant_sites=None, mutation_rate=0.001, death_rate=0.02, gamma_kwargs=None, ...
def get_all_data_len(self,frame): data_len = [] for i in self.pairs: data_len.append(self.get_point_length(frame,i[0],i[1])) return data_len def get_movement_vector(self,data_point_idx,frame): length = self.tpose_len[data_point_idx]/self.data_len[data_point_idx] v =...
The main task of the code is to scale a frame's data by calculating movement vectors for different segments and applying correction operations (fix_data) to specific data ranges. It adjusts the frame's data using multiple movement vectors, with each fix_data call targeting distinct indices to normalize or transform the...
def scale(self,frame): self.data_len = self.get_all_data_len(frame) mov_vec = self.get_movement_vector(3,frame) self.fix_data(frame,mov_vec,0,8) mov_vec = self.get_movement_vector(0,frame) self.fix_data(frame,mov_vec,0,1) mov_vec = self.get_movement_vector(1,f...
def bed_to_itree(beds): intervals = defaultdict(list) for record in beds: seqid, interval = record.as_interval() intervals[seqid].append(interval) itree = {s: IntervalTree(i) for s, i in intervals.items()} for it in itree.values(): it.merge_overlaps() return itree def get_...
The code filters alignments from a PAF file by excluding those with identical query/target genomes (if specified), insufficient alignment length, or overlapping intervals with BED regions. Valid alignments are written to an output file.
def filter_main(args): bed = BED.from_file(args.inbed) bed_tree = bed_to_itree(bed) paf = PAF.from_file(args.inpaf) for p in paf: if args.sep is not None: qgenome = get_genome_name(p.query, args.sep) tgenome = get_genome_name(p.target, args.sep) if qgenome ...
def cli(prog, args): parser = argparse.ArgumentParser( prog=prog, description="" ) subparsers = parser.add_subparsers(dest='subparser_name') filter_subparser = subparsers.add_parser( "filter", help="Filter matches." ) filter_cli(filter_subparser) repeats_...
The main task of the code is to parse command-line arguments, dispatch to subcommand functions (`filter_main` or `repeats_main`), and handle exceptions like broken pipes, keyboard interrupts, and system errors with appropriate messages, ensuring graceful exits or error propagation.
def main(): args = cli(prog=sys.argv[0], args=sys.argv[1:]) try: if args.subparser_name == "filter": filter_main(args) elif args.subparser_name == "repeats": repeats_main(args) else: raise ValueError("I shouldn't reach this point ever") except Bro...
def update_g(F, X): G = np.zeros((X.shape[0], F.shape[1])) for i, sample in enumerate(X): distances = [] for centroid in F.T: distances += [np.linalg.norm(sample - centroid)] minimum = min(distances) index = distances.index(minimum) gi = np.zeros((1, F.shape[1...
The code implements a clustering algorithm (DCKM) that iteratively updates parameters F, G, and w to minimize a loss function until convergence. It initializes centroids randomly, refines cluster assignments and weights, and evaluates clustering performance using Normalized Mutual Information (NMI) and Adjusted Rand In...
def DCKM(X, y): clusters = len(np.unique(y)) # initial random centroids index = np.random.choice(X.shape[0], clusters, replace=False) F = X[index].T w = np.ones((X.shape[0], 1)) G = update_g(F, X) while loss_function(X, F, G, w) > e: F = update_f(X, w, G) G = update_g(F, X) ...