dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def __convert_to_pid__(self, pID): if(isinstance(pID, string_types)): return self.get_portfolio_id(pID) else: return pID def urljoiner(baseurl, path_or_pathlist): if isinstance(path_or_pathlist, string_types): if(baseurl.rsplit('/', 1)[-1] == "rest"): retu...
This function updates or creates a portfolio valuation entry for a specific date by sending a PUT request to the API endpoint /api/v1/portfolios/{id}/valuations/{date}, using the provided portfolio identifier, date, and valuation data. It converts the portfolio name to an ID, constructs the request URL, sends the JSON ...
def save_portfolio_valuations_for_date_put( self, portfolio, date, valuation): """Replaces or creates the portfolio valuation for the given id+date (Auth policies: Users) Endpoint: /api/v1/portfolios/{id}/valuations/{date} Keyword arguments: portfolio: portf...
def __convert_to_pid__(self, pID): if(isinstance(pID, string_types)): return self.get_portfolio_id(pID) else: return pID def urljoiner(baseurl, path_or_pathlist): if isinstance(path_or_pathlist, string_types): if(baseurl.rsplit('/', 1)[-1] == "rest"): retu...
This function retrieves and returns a dictionary mapping dates to the number of positions for a specified portfolio, with dates ordered from latest to earliest. It sends a GET request to the portfolio positions endpoint, processes the JSON response, and constructs the date-position count mapping.
def get_position_date_info(self, portfolio_id): """Lists dates there are Positions for the Portfolio, latest first (Auth policies: Users) Endpoint: /portfolios/{id}/positions Keyword arguments: portfolio_id: portfolio name or id """ portfolio_id ...
def __convert_to_pid__(self, pID): if(isinstance(pID, string_types)): return self.get_portfolio_id(pID) else: return pID def __convert_datetime_to_string__(self, date): if(isinstance(date, string_types)): from dateutil.parser import parse return se...
This function creates a new portfolio position for a specified date by sending a POST request to the corresponding API endpoint. It converts input parameters to required formats, constructs the URL, and handles errors. Debug mode prints the URL and data.
def save_positions_for_date_post(self, portfolio, date, position_data): """Create a new Position in the Portfolio on the given date. (Auth policies: Users) Endpoint: /portfolios/{i...
def __convert_to_pid__(self, pID): if(isinstance(pID, string_types)): return self.get_portfolio_id(pID) else: return pID def __convert_datetime_to_string__(self, date): if(isinstance(date, string_types)): from dateutil.parser import parse return se...
This function updates or adds portfolio positions for a specific date by sending a PATCH request to an API endpoint. It converts input parameters to required formats, constructs the URL, prepares JSON data with 'upsert' operations, and handles errors. The function ensures positions are patched according to provided ope...
def save_positions_for_date_patch(self, portfolio, date, position_data): """Patches the existing collection of Positions according to the supplied operations (Auth policies: Users) Endpoint...
def __convert_to_pid__(self, pID): if(isinstance(pID, string_types)): return self.get_portfolio_id(pID) else: return pID def urljoiner(baseurl, path_or_pathlist): if isinstance(path_or_pathlist, string_types): if(baseurl.rsplit('/', 1)[-1] == "rest"): retu...
This function updates a user's portfolio by sending a PUT request to the /portfolios/{id} endpoint with provided data. It converts the portfolio identifier, constructs the URL, handles authentication headers, and returns response headers after error checking. The operation is debuggable and follows RESTful conventions ...
def update_portfolio(self, portfolio, data): """Updates a portfolio (Auth policies: Users) Endpoint: /portfolios/{id} Keyword arguments: portfolio: portfolio to delete data: json to update portfolio """ verb = "PUT" portfolio_id = sel...
def __convert_to_pid__(self, pID): if(isinstance(pID, string_types)): return self.get_portfolio_id(pID) else: return pID def urljoiner(baseurl, path_or_pathlist): if isinstance(path_or_pathlist, string_types): if(baseurl.rsplit('/', 1)[-1] == "rest"): retu...
This code deletes a portfolio by sending a DELETE request to the API endpoint /portfolios/{id}, using the portfolio's ID derived from the input. It constructs the URL, handles authentication headers, and checks for errors. If debug mode is enabled, it prints the request details. The function returns True upon successfu...
def delete_portfolio(self, portfolio): """Deletes a portfolio (Auth policies: Users) Endpoint: /portfolios/{id} Keyword arguments: portfolio: portfolio to delete """ verb = "DELETE" portfolio_id = self.__convert_to_pid__(portfolio) url =...
def __convert_to_pid__(self, pID): if(isinstance(pID, string_types)): return self.get_portfolio_id(pID) else: return pID def get_latest_portfolio_date(self, portfolio_id): return (self.get_portfolio(portfolio_id))['latestPositionDate'] def urljoiner(baseurl, path_or_pathl...
The main task of the code is to retrieve portfolio positions for a specified date (or the latest available date if none is provided) by making an API request to a predefined endpoint. It converts the portfolio identifier, formats the date, constructs the URL, handles authentication headers, executes the GET request, pr...
def get_positions_for_date(self, portfolio, position_date=None): """Lists Positions on the given date for the Portfolio (Auth policies: Users) Endpoint: /portfolios/{id}/positions/{date} Keyword arguments: portfolio: portfolio name or id position_date: date ...
def getinventorystatus(connection): inventory_id = int(input("Enter InventoryID whose status you want to get: ")) print("\n"); try: cursor = connection.cursor() cursor.execute("SELECT * FROM InventoryItem WHERE InventoryID = %s", (inventory_id,)) print_rows(cursor) except Exce...
The main task of the code is to display a menu-driven interface for inventory management operations, allowing users to retrieve inventory status, purchase items, increment dates, add supplier items, or exit the program. The function loops until the user selects "Exit," using a database connection to execute operations.
def main_menu(connection): while True: print("\n+--------------------------- Main Menu -------------------+") print("| Option | Operation |") print("+----------+----------------------------------------------+") print("| 1 | Get ...
def executing_trigger_creation(connection): create_trigger_after_transaction_update(connection) create_trigger_after_transaction_delete(connection) def get_user_credential(): name = input("ENTER YOUR USERNAME: ") password = getpass("ENTER YOUR PASSWORD: ") return name, password def initialize_proced...
The main task of the code is to set up a database by creating tables, populating data, and establishing triggers, followed by user authentication. If successful, it initializes procedures and launches a main menu for further operations, ensuring proper database connection management throughout the process.
def main(): my_connection = create_connection() create_database(my_connection) # Execute script to create tables create_tables_script = "scripts/create_tables.sql" execute_sql_script(my_connection, create_tables_script) # Execute script to populate data populate_data_script = "scripts/po...
def get_n_scen(prodrisk, data_dir, model_name): model_file = h5py.File(data_dir + "model.h5", 'r') param_path = 'hydro_data/hydro_parameters' params = model_file.get(param_path) prodrisk.n_scenarios = params['value'][3] return def set_price_periods_from_file(prodrisk, data_dir): price_period...
The code initializes and configures a Prodrisk optimization model by loading scenario data from an HDF5 file, setting up the Prodrisk API with parameters like optimization period, working directory, and solver paths, and assembling model components such as inflow series, modules, area objects, and restrictions. It retu...
def build_prodrisk_model(LTM_input_folder, n_weeks=156, start_time="2030-01-07"): ScenF = h5py.File(os.path.join(LTM_input_folder+'ScenarioData.h5'), 'r') names = list(ScenF.keys()) model_name = names[0] ScenF.close() # INITIALIZE PRODRISK API # prodrisk = ProdriskSession(license_path='/prodrisk...
def make_corr_list(training): ''' Identify the correlation between each variable and the value Parameters: training (list of lists): training data Returns: corr_list: a list of correlation between each feature and the label by index ''' corr_list = [] cc_array = np.array(tr...
The main task of the code is to process credit card transaction data by reading, formatting, splitting into training/testing sets, scaling features, and calculating correlations/distances for analysis. It focuses on handling PCA variables, class labels (fraudulent/normal), and applying probabilistic sampling for datase...
def main(): # Read credit card data into cc_data with open('creditcard.csv', 'r') as f: reader = csv.reader(f) cc_data = [] for row in reader: cc_data.append(row) # Print header of credit card data print(cc_data[0]) print("") # 0 is time, 28 PCA varoiables, 29...
def get_args(names: ty.Iterable[str]) -> tuple[str, ...]: # Get the set of arguments passed when running the script arguments = sys.argv # Set up the list to return returns = [None for _ in names] # Iterate through and check if there was a filepath for arg in arguments: fo...
The code trains a neural network on particle physics data (HWW events) using configurable parameters for hidden layers, loss functions, and multi-GPU support. It loads data, builds or loads a model, trains it with specified epochs and batch sizes, saves checkpoints, and generates evaluation plots comparing model perfor...
def main() -> None: print("---------START---------") # Get the arguments for the file saved_model_path, job_number = get_args(("filepath", "jobnumber")) job_number = int(job_number) if job_number is not None else None # Loading data PATH_TO_DATA = "/home/kye/projects/ctb-stelzer/k...
def load_all_event_weights(filepath: str, coefs: ty.Iterable[float], c_prefix: str) -> pd.DataFrame: """Return a pandas DataFrame with the weights of each event for each Wilson Coefficient value. Args: * filepath (str): A path to a pickle file containing the event weights in a pandas DataFrame. ...
The main task of the code is to perform statistical analysis on simulated particle collision data by building a likelihood ratio estimator using neural networks. It loads event data, constructs an estimator for event numbers, calculates likelihood ratios with confidence bounds, integrates the estimator, and generates a...
def main() -> None: #### SETTINGS FOR THE ANALYSIS #### # Loading simulated events ALL_EVENTS_FILEPATH = "/home/kye/projects/ctb-stelzer/kye/HWWTraining/Data/AnalysisTest/full_data.pkl" TEST_FILEPATH = "/home/kye/projects/ctb-stelzer/kye/HWWTraining/Data/AnalysisTest/full_data.pkl" TEST_SLICE =...
def parse_arguments(): """Parse command-line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( "-i", "--input_dir", type=Path, required=True, help="input data directory", ) parser.add_argument( "-o", "--output_dir", type=Path, requi...
The main task of the code is to process training data by analyzing JSON or JSON.gz files, calculate counts using parallel processing, generate permutations, and determine optimal zone boundaries and permutations. Results are saved as text files and logged. The code ensures directory structures, validates inputs, and ha...
def main(): """Main function.""" # Parse command-line arguments args = parse_arguments() assert args.n_jobs >= 1, "`n_jobs` must be a positive integer." args.output_dir.mkdir(exist_ok=True) # Make sure sample directories exist (args.output_dir / "samples").mkdir(exist_ok=True) for subdi...
def assemble_indexes(ta,na,**kwargs): index = [] for i in range(kwargs['sess']): index.append(mkindex(ta,na, **kwargs)) return index def assemble_cases(ta,na,index,**kwargs): if not 'cases' in kwargs: raise Exception('Must define 1 or more cases') cases = {} for c in kwar...
The main task of the code is to assemble data structures from a configuration file. It loads parameters from `config.json`, generates an index and cases using those parameters, and returns either a dictionary containing the index and cases or frames created from them, depending on the `frames` flag.
def assemble(frames=False,config='config.json'): with open(config) as conf: kwargs = json.load(conf) index = assemble_indexes(**kwargs) cases = assemble_cases(**kwargs,index=index) if frames: return mk_frames(index,cases) return {'index':index, **cases}
def loadData(): for i in range(len(categories)): url = "https://storage.googleapis.com/quickdraw_dataset/full/numpy_bitmap/" + categories[i]["category"].replace(" ", "%20") + ".npy" try: d = urllib.request.urlopen(url) except Exception as e: Logger.Log("Failed to ...
The main task of the code is to provide a menu-driven interface for creating or loading a neural network. It prompts the user to either create a new network (specifying a name and number of epochs) or load an existing network (by name). Input validation ensures epochs are numeric and checks if the requested network fil...
def main(): loadData() choice = input("Neural Network\n[1] New Network\n[2] Load Network\n=> ") if (choice == "1"): name = input("Network Name\n=> ") epochs = input("Epochs\n=> ") if (epochs.isdigit()): startNetwork(name, int(epochs)) else: print("Epoc...
def add_round_key(players): for p in players: for i in range(4): for j in range(4): p.texts[i][j] = add_mac(p.texts[i][j], p.keys[i][j]) def sub_byte(players, method=0, eff_dic=None): sbox(players, 0, method, eff_dic) def shift_row(players): offset = [0, 1, 2, 3] for ...
The code implements AES encryption on the input 'players' data using a specified method. It performs multiple rounds of substitution (sub_byte), row shifting (shift_row), column mixing (column_mixture), key expansion (key_expansion), and round key addition (add_round_key), following the standard AES structure with 10 r...
def AES_encode(players, method=0): eff_dic = gen_comb_eff([127, 191, 223, 239, 247, 251, 253, 254]) add_round_key(players) for i in range(9): sub_byte(players, method, eff_dic) shift_row(players) column_mixture(players) key_expansion(players, method, eff_dic) add_roun...
def add_round_key_inv(players): add_round_key(players) def sub_byte_inv(players, method=0, eff_dic=None): sbox_inv(players, 0, method, eff_dic) def shift_row_inv(players): offset = [0, -1, -2, -3] for p in players: for i in range(4): p.set_text_row(i, shift(p.texts[i], offset[i])) de...
This function performs AES decryption on the 'players' data using inverse operations. It applies 10 rounds of decryption steps, including inverse substitution, row shifting, column mixing, and key expansion, with the specified 'method' parameter. The process uses a precomputed efficiency dictionary for optimized operat...
def AES_decode(players, method=0): eff_dic = gen_comb_eff([_ for _ in range(255)]) add_round_key_inv(players) for i in range(9): sub_byte_inv(players, method, eff_dic) shift_row_inv(players) column_mixture_inv(players) key_expansion_inv(players, method, eff_dic) add_r...
def inBounds(): global input global currentIndex return len(input) > currentIndex def letDigParser(): global currentIndex global input global result if inBounds(): if letterParser(): return True elif digitParser(): return True else: return False else: return False
This function recursively parses a string of letters and digits by checking if the current input character is valid (via letDigParser()), then advancing through the input. It returns True if all characters are successfully parsed, otherwise False. The global variables track the current position, input string, and parsi...
def letDigStrParser(): global currentIndex global input global result if inBounds() and letDigParser(): letDigStrParser() return True else: return False
def MAILFROMParser(): global currentIndex global input global result if inBounds() and input[currentIndex] == "M": currentIndex+=1 if inBounds() and input[currentIndex] == "A": currentIndex+=1 if inBounds() and input[currentIndex] == "I": currentIndex+=1 if inBounds() and input[currentIndex] == "...
The main task of the code is to handle a 500 "Syntax error: command unrecognized" response in an SMTP server. It sequentially checks the success of MAILFROM, RCPTTO, and DATAParser parsers. If all fail, it writes the error message and returns True (indicating an error), otherwise resets the loop and returns False. The ...
def error500(): if not MAILFROMParser(): resetLoop() if not RCPTTOParser(): resetLoop() if not DATAParser(): sys.stdout.write("500 Syntax error: command unrecognized\n") resetLoop() return True resetLoop() return False
def RCPTTOParser(): global currentIndex global input global result if inBounds() and input[currentIndex] == "R": currentIndex+=1 if inBounds() and input[currentIndex] == "C": currentIndex+=1 if inBounds() and input[currentIndex] == "P": currentIndex+=1 if inBounds() and input[currentIndex] == "T"...
The code handles SMTP command sequence validation, returning a 503 error when commands like MAILFROM, RCPTTO, or DATA are issued in an invalid order. It checks parser states, resets loops on failures, and outputs "503 Bad sequence of commands" while returning True for error handling or False for critical parsing failur...
def error503(currentCmd): if currentCmd == "mailFromCmd": if not RCPTTOParser(): resetLoop() if not DATAParser(): resetLoop() return False resetLoop() sys.stdout.write("503 Bad sequence of commands\n") return True elif currentCmd == "rcptToCmd": if not MAILFROMParser(): resetLoop() if no...
def inBounds(): global input global currentIndex return len(input) > currentIndex def nullspaceParser(): whitespaceParser() return True def CRLFParser(): global currentIndex global input global result if inBounds() and input[currentIndex] == "\n": currentIndex+=1 return True else: return False
The main task of the code is to parse the "DATA" command sequence from input data by sequentially checking characters "D", "A", "T", "A" at the current index, incrementing the index upon successful matches. It then validates the CRLF (carriage return/line feed) format using CRLFParser and updates the result to "ERROR -...
def dataCmdParser(): global currentIndex global input global result if inBounds() and input[currentIndex] == "D": currentIndex+=1 if inBounds() and input[currentIndex] == "A": currentIndex+=1 if inBounds() and input[currentIndex] == "T": currentIndex+=1 if inBounds() and input[currentIndex] == "A...
def inBounds(): global input global currentIndex return len(input) > currentIndex def letDigParser(): global currentIndex global input global result if inBounds(): if letterParser(): return True elif digitParser(): return True else: return False else: return False
The main task of the code is to recursively parse a string of letters and digits. It checks if the current input position is valid and if a single letter/digit can be parsed. If so, it continues parsing the next character recursively, returning True if all characters are valid alphanumeric, otherwise False.
def letDigStrParser(): global currentIndex global input global result if inBounds() and letDigParser(): letDigStrParser() return True else: return False
def inBounds(): global input global currentIndex return len(input) > currentIndex def letterParser(): global currentIndex global input global result if inBounds(): x = input[currentIndex] if x == "a" or x == "b" or x == "c" or x == "d" or x == "e" or x == "f" or x == "g" or x == "h" or x == "i" or x == "j" o...
This function parses a name by checking if the current position in the input starts with a letter followed by a letter/digit string, returning True if valid, False otherwise. It uses global variables to track parsing state and ensures at least two characters remain before attempting validation.
def nameParser(): global currentIndex global input global result currentIndex+=1 #checks if there are at least 2 characters remaining if inBounds(): currentIndex-=1 if letterParser(): if letDigStrParser(): return True else: return False else: return False else: currentIndex-=1 return ...
def inBounds(): global input global currentIndex return len(input) > currentIndex def letterParser(): global currentIndex global input global result if inBounds(): x = input[currentIndex] if x == "a" or x == "b" or x == "c" or x == "d" or x == "e" or x == "f" or x == "g" or x == "h" or x == "i" or x == "j" o...
This code parses a name by checking if it starts with a letter followed by a letter/digit string, using global state to track position in input. It returns True if valid, False otherwise.
def nameParser(): global currentIndex global input global result currentIndex+=1 #checks if there are at least 2 characters remaining if inBounds(): currentIndex-=1 if letterParser(): if letDigStrParser(): return True else: return False else: return False else: currentIndex-=1 return ...
def inBounds(): global input global currentIndex return len(input) > currentIndex def letterParser(): global currentIndex global input global result if inBounds(): x = input[currentIndex] if x == "a" or x == "b" or x == "c" or x == "d" or x == "e" or x == "f" or x == "g" or x == "h" or x == "i" or x == "j" o...
The main task of the code is to parse an element by first validating a letter, adjusting the current index, and then checking for a valid name. If the name parsing fails, it re-tries the letter parser before returning success. The function returns True if the element structure is valid, otherwise False.
def elementParser(): global currentIndex if inBounds(): if letterParser(): currentIndex-=1 if nameParser(): return True else: letterParser() return True else: return False else: return False
def inBounds(): global input global currentIndex return len(input) > currentIndex def letterParser(): global currentIndex global input global result if inBounds(): x = input[currentIndex] if x == "a" or x == "b" or x == "c" or x == "d" or x == "e" or x == "f" or x == "g" or x == "h" or x == "i" or x == "j" o...
The main task of the code is to parse an element by first validating a letter (via letterParser()), adjusting the global index, then parsing a name (via nameParser()). If the name parsing fails, it rechecks the letter. It returns True if either the name parsing succeeds or the letter recheck passes, provided the index ...
def elementParser(): global currentIndex if inBounds(): if letterParser(): currentIndex-=1 if nameParser(): return True else: letterParser() return True else: return False else: return False
def inBounds(): global input global currentIndex return len(input) > currentIndex def elementParser(): global currentIndex if inBounds(): if letterParser(): currentIndex-=1 if nameParser(): return True else: letterParser() return True else: return False else: return False
This function parses and validates the domain part of an email address by recursively checking for valid elements separated by dots. If parsing fails, it updates the result to an error state and returns False. The global variables track parsing progress and results.
def domainParser(): global currentIndex global input global result if inBounds() and elementParser(): if inBounds() and input[currentIndex] == ".": currentIndex+=1 domainParser() return True else: if result == "Sender ok": result = "ERROR -- element" return False
def inBounds(): global input global currentIndex return len(input) > currentIndex def elementParser(): global currentIndex if inBounds(): if letterParser(): currentIndex-=1 if nameParser(): return True else: letterParser() return True else: return False else: return False
The main task of the code is to parse a domain component of an email address by recursively validating elements separated by dots. It checks if each element is valid using `elementParser()`, advances the index upon encountering a dot, and updates the result to an error if parsing fails. The function returns `True` on s...
def domainParser(): global currentIndex global input global result if inBounds() and elementParser(): if inBounds() and input[currentIndex] == ".": currentIndex+=1 domainParser() return True else: if result == "250 OK": result = "ERROR -- element" return False
def find_fitness(self, boards): board_fitness = {} for b in boards: board_q_p = self.get_chromosome(b.get_queen_positions()) board_fitness[board_q_p] = self.__fitness__(board_q_p) #sort the board descending board_fitness = self.sort_dict_by_values_desc(board...
The code implements a genetic algorithm to solve the N-Queens problem by evolving a population of boards through generations. It calculates fitness, selects boards probabilistically, generates offspring, evaluates them, and retains the fittest individuals. The loop continues until a solved board (max fitness) is found,...
def run(self): #find the fitnesses for each board board_fitness = self.find_fitness(self.boards) #a generation number to see which generation is being run generation = 0 #print(board_fitness) #run until there is a board in the population that is solved #i....
def determine_type_of_feature(df): feature_types = [] n_unique_values_treshold = len(df) / 5 for feature in df.columns[:-2]: unique_values = df[feature].unique() if df[feature].dtype.name == 'object': feature_types.append("categorical") elif len(unique_values) <= n_unique...
The code constructs a decision tree by recursively splitting data based on the best splits determined by an error type, using linear regression for predictions at leaf nodes. It initializes features, clusters, and error metrics, iteratively selects optimal splits (handling both continuous and categorical features), and...
def CreateTree(error_type, df, depth, min_leaf_sample, StoppingRule, random_subspace=None): covariates_df = df.iloc[:, :-2] global col_names, covariates, y, cluster, cluster_dummies, feature_types feature_types = determine_type_of_feature(df) col_names = covariates_df.columns covariates = covaria...
def determine_type_of_feature(df): feature_types = [] n_unique_values_treshold = len(df) / 5 for feature in df.columns[:-2]: unique_values = df[feature].unique() # example_value = unique_values[0] if df[feature].dtype.name == 'object': feature_types.append("cat...
The code constructs a decision tree recursively by splitting data based on features, handling both continuous and categorical variables. It determines the best split using specified error metrics, creates leaf nodes when reaching max depth or minimum samples, and builds a tree structure as a nested dictionary with cond...
def decision_tree_algorithm(error_type, df, max_depth, min_leaf_sample, counter=0, random_subspace=None, V_par_prev=[1] * 6): if counter == 0: global COLUMN_HEADERS, FEATURE_TYPES COLUMN_HEADERS = df.columns FEATURE_TYPES = determine_type_of_feature(df) da...
def row_collisions(self, placement): return np.count_nonzero(self.grid[placement[0]] == 1) def column_collisions(self, placement): return np.count_nonzero(self.grid.T[placement[1]] == 1) def diagonal_collisions(self, placement) -> int: right_diagonal_collisions = np.count_nonzero(self.get_right_...
The code calculates the total number of collisions in a given placement by summing row, column, and diagonal collisions, commonly used in problems like N-Queens to evaluate conflicts between placed objects.
def calculate_collisions(self, placement) -> int: return self.row_collisions(placement) + self.column_collisions(placement) + self.diagonal_collisions(placement)
def row_is_valid(self, placement): return not np.any(np.isin([1], self.grid[placement[0]])) def column_is_valid(self, placement): return not np.any(np.isin([1], self.grid.T[placement[1]])) def diagonal_is_valid(self, placement) -> bool: right_diagonal_valid = not np.any(np.isin([1], self.get_rig...
The main task of the code is to validate if a given placement of queens on a chessboard is conflict-free by checking row, column, and diagonal constraints. It returns `True` if all three checks pass, ensuring no two queens attack each other horizontally, vertically, or diagonally.
def is_valid_placement(self, placement) -> bool: return self.row_is_valid(placement) and self.column_is_valid(placement) and self.diagonal_is_valid(placement)
def get_savings(username): user_data = user_information_table.find_one({'username': username}) if user_data: raw_user_savings = user_data.get('savings', '') int_user_savings = convert_to_integer(raw_user_savings) print(f"Grabbed Raw Savings: {raw_user_savings}") print(f"translat...
The main task of the code is to allow a user to modify their savings account by adding or subtracting funds, with validation checks. It displays current savings, prompts for transaction type/amount, verifies validity, executes transactions if possible, and exits when the user chooses. Input errors and invalid transacti...
def verified_modification_user(username): print(f"Welcome: {username}") loop = True while loop: current_savings = get_savings(username) print(f"\nCurrently you have: {current_savings}\n") print("What would you like to do?") print("Enter one of the following option...
def get_playlists_info( param_session: dict, print_loading: bool = False ) -> dict: """ Get playlists infos of the users Args: param_session (dict): parameters for the request(connection parameters + details of the request) print_loading (bool, optional): print the names of the playlist...
This function transfers Spotify playlists and their tracks to Deezer by creating or updating playlists, searching for corresponding Deezer track IDs, and adding tracks while tracking new additions and existing duplicates. It returns the updated Deezer library DataFrame with added tracks.
def add_playlists( df_spotify_playlists: pd.DataFrame(), param_session: dict, publicplaylist: bool = True, collaborative: bool = False, print_loading: bool = False, print_json: bool = False ): """ From 'df_spotify_playlists' add playlists and their tracks to the user library Args: ...
def set_sizes(self): w, h = self.w, self.h self.plot.xywh(0.1 * w, 10, .8 * w, (h - 10) * 0.75) self.legend.xywh(0.7 * w, 10, 0.29 * w, (h - 10) * 0.65) def _set_legend(self): self.legend.active = False def _set_frame(self): frame = self.frame frame.border.stroke = (50, 5...
The main task of the code is to configure a plot's visual elements by setting sizes, legend, frame, plot content, and title, then invoking the parent class's construct method to finalize initialization.
def construct(self): self.set_sizes() self._set_legend() self._set_frame() self._set_plot() self._title() return super().construct()
def generate_unit_intrinsics() -> str: intrinsics = "" for vtype in VType.iterate(): vtype_unit_uload = f"vle{vtype.sew.value}_v_u{vtype.sew.value}{vtype.lmul.get_code()}" vtype_unit_iload = f"vle{vtype.sew.value}_v_i{vtype.sew.value}{vtype.lmul.get_code()}" vtype_unit_ustore = f"vse{vty...
The main task of the code is to concatenate predefined strings (PREAMBLE and POSTAMBLE) with dynamically generated intrinsic code sections (unit, strided, and fof) into a single string. This combines static boilerplate with specialized low-level instructions for compilation or processing.
def generate_intrinsics() -> str: return (PREAMBLE + generate_unit_intrinsics() + generate_strided_intrinsics() + generate_fof_intrinsics() + POSTAMBLE )
def write_line(self, code: str = ""): self.write("{}\n".format(code)) def push_indent(self) -> None: self._indentation_level += 1 def write_code(self, statement: str = '') -> None: for stmt in statement.split(';'): stmt = stmt.strip() if stmt: self._split_...
This method creates a labeled code block with indentation, captures content within the block using a StringIO buffer, and writes it back with proper formatting. It uses a context manager to handle setup/teardown, including writing the label, managing indentation, and appending/poping buffer content.
def label(self, label: str, end: str = '') -> ContextManager: self.write_line("{}:".format(label)) self._buffer.append(StringIO()) self.push_indent() try: yield finally: if end: self.write_code(end) text = self._buffer.pop()....
def cool(self, with_vent=False, with_drain=False): self.log_history(0) self.plate.set_duty_cycle(0) if with_drain: self.drain.on() else: self.drain.off() if with_vent: self.in_vent.on() self.out_vent.on() self.fan.on() ...
This code prepares tempeh by soaking, draining, heating, steaming, cooling, and drying it. It then incubates the tempeh at a target temperature, monitoring progress, saving history, and adjusting PID settings. The process includes timed steps, temperature checks, and alerts for human input before completing incubation ...
def make_tempeh(self): logger.info("Soaking") time.sleep(self.soak_time) logger.info("Draining") self.cool(with_vent=False, with_drain=True) time.sleep(self.pre_steam_drain_time) logger.info("Heating") self.heat() time.sleep(self.steam_time) logger...
def get_coordinates_from_vcf(input, build, logger): """ Read in vcf file using "pyVCF3", creates CoordinateQuery objects for each variant. This function does find (ref-alt): SNPs (A-T) DelIns (AA-TT) Deletions (TTTCA - AT) :param input: list of pyVCF3 records or vcf file to query :...
The function `query_civic` queries the CIViC API using variant coordinates from a VCF file or pyVCF3 records. It retrieves genomic coordinates, sorts them, and performs bulk API searches. Results are stored in a specified directory as a table, with optional VEP-based filtering. Metadata about the input file, genome, an...
def query_civic(vcf, out_path, logger, input_file, genome, filter_vep): """ Command to query the CIViC API :param vcf: Variant Call Format (VCF) file (Version 4.2) or list of pyVCF3 variant records :type vcf: str or list :param out_path: Name for directory in which result-table will be stored :...
def fill_area(self, i, area): s = set() s.add(i) self._fill_area(area, s, set()) def is_trapped(self, area): for p in area: if p[0] <= 0 or p[0] >= self.points.shape[0] - 2: return False elif p[1] <= 0 or p[1] >= self.points.shape[1] - 2: ...
The code calculates a score based on the exterior areas of zero-valued points in a grid. It identifies free and trapped regions of zeros, then counts adjacent non-zero points connected to free zero regions, excluding those in trapped areas. The score reflects the number of such exterior zero-cell neighbors.
def get_exterior_area(self): zero_indices = np.where(self.points == 0) free_area = set() trapped_area = set() for i in zip(*zero_indices): if i in free_area or i in trapped_area: continue area = set() self.fill_area(i, area) ...
def get_more_articles(start_article, num_articles): wiki_refs = get_wiki_refs_from_page(start_article) ref_articles = get_random_elements_from_list(wiki_refs, num_articles) return ref_articles def extract_sentences_from_article(article, num_sentences): sentences_list = extract_all_sentences(article) ...
This function crawls articles starting from a given URL, extracts sentences in batches, and writes them to a file until a specified number of sentences per cluster is reached. It uses a queue to manage URLs, expands links iteratively, and accumulates sentences while tracking the total count.
def get_all_sentences(url, file_name): count = 0 articles_queue = queue.Queue() articles_queue.put(url) with open(file_name, encoding='utf-8', mode='w+') as filehandler: while count < num_sentences_per_cluster: curr_url = articles_queue.get() print(curr_url) c...
def get_dW(pasting_cutoff, pasting_T, n_sample, dW_orig = dW_STD, seed = None): dt = (T - pasting_cutoff) / T * TR / pasting_T if seed is not None: torch.manual_seed(seed) multi_normal = MultivariateNormal(torch.zeros((n_sample, pasting_T, N_BM)), BM_COV * dt) dW_STD_curr = multi_normal.sample()...
The code performs transfer learning with multiple rounds of training and evaluation, adjusting parameters based on loss differences. It initializes logging, iterates over training rounds, evaluates models using different algorithms (leading order, ground truth), trains models with varying hyperparameters, and dynamical...
def transfer_learning(train_args, N_rounds = 5, n_train = 1, n_sample_lst = [128, 128], lr_lst = [1e-3, 1e-4], epoch_lst = [20000, 20000], retrain = False): if POWER == 2: cost = "quadratic" else: cost = "power" final_ts = datetime.now(tz=pytz.timezone("America/New_York")).strftime("%Y-...
def create_table_from_filtered_dict(filtered_drug_res_dict): table = convert_filtered_dict_to_table(filtered_drug_res_dict) if not table: return None headers = ["Sample_name"] + ["Drug"] + ["Confidence_grading"] + ["Gene"] + ["Variant"] + ["Variant_attributes"] return tabulate(table, h...
This code processes genetic variants (intergenic and others) to categorize them based on drug confidence levels, identify novel variants, and generate structured tables for analysis. It initializes data structures, filters variants against drug-disease associations, separates catalogued vs. novel variants, and creates ...
def __init__(self, my_per_drug_res_dict, drug_name_list, confidence_grading_list, per_sample_drug_dict, sample_name_list): Confidence_grading.__init__(self, my_per_drug_res_dict, drug_name_list, confidence_grading_list) Sample_class.__init__(self, per_sample_drug_dict, sample_name_list) self.sam...
def check_workspace_status(workspace_directory, full=False, verbose=False, show_time=False, fetch=False, gui=False): """ Check the status of all repositories in a workspace Args: workspace_directory (str): path to the workspace full (bool, optional): show the full list. Defaults...
The code defines a `main()` function that parses command-line arguments for managing version control system (VCS) configurations and workspaces. It supports commands like `status`, `config_workspace`, `config_list`, and `config_versions`, each with options to specify directories, configuration files, filtering, verbosi...
def main(): # Parse arguments parser = argparse.ArgumentParser() parser.add_argument("command", help="Action to take", choices=["status", "config_workspace", "config_list", "config_versions"]) parser.add_argument("-w", "--workspace-directory", help="Workspace directory. Use current directory if not spec...
def get_dynamic_depth(self): empty_cells = sum(row.count("") for row in self.board) if empty_cells > (BOARD_SIZE**2) / 2: return 2 # Less depth in the early game elif empty_cells > (BOARD_SIZE**2) / 4: return 3 # Medium depth in the mid-game else: re...
The main task of the code is to determine the AI's optimal move in a turn-based game by checking for immediate winning opportunities, blocking the player's threats (e.g., three-in-a-row or irregular patterns), and using a minimax algorithm with alpha-beta pruning for deeper strategic evaluation. It prioritizes critical...
def move_hard(self): best_score = -float("inf") best_move = None depth = self.get_dynamic_depth() player_winning_next = False ai_extendable_three = False ai_winning_next = False # Check if the player or AI has a critical move for move in self.get_possible...
def initialize_board(self): for i in range(BOARD_SIZE): for j in range(BOARD_SIZE): button = tk.Button( self.master, width=2, height=1, command=lambda i=i, j=j: self.on_cell_clicked(i, j), ...
This code initializes a game interface with AI opponents of varying difficulty levels. It sets up the game board, tracks player and AI scores, creates AI instances (easy, medium, hard) based on user-selected difficulty, and initializes UI elements like the board, scoreboard, and menu. The AI instances use different str...
def __init__(self, master, ai_difficulty, on_restart): self.master = master self.ai_difficulty = ai_difficulty # Set difficulty based on user selection self.board = [["" for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)] self.current_player = HUMAN_PLAYER self.buttons = [[N...
def instructions(): # this function prints the instructions print(""" Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe. This will be a showdown between your human brain and my silicon processor. You will make your move known by entering a number, 0 - 8. The number...
The main task of the code is to execute a game by sequentially calling three functions: instructions() to display rules, printBoard() to initialize or show the game board, and game() to start the game logic or loop. The main() function acts as the entry point, orchestrating these components to run the game.
def main(): # main function to call game instructions() printBoard() game()
def loop_for_apples(self,Apples, screen): apples_in_range = [] for apple in Apples.Apples: if self.eating_food(apple): Apples.nApples -= 1 continue if self.in_range(apple): apples_in_range.append(apple) if len(apples_in_rang...
The code updates an entity's state by processing apple spawning, drawing sensors, calculating movement parameters via a neural network (Brain) using distance and angle data, applying movement, and decrementing health.
def update(self, AppleSpawner, screen): self.loop_for_apples(AppleSpawner, screen) self.draw_sensor(screen) # print(self.angle_diff) params = self.Brain.forward(self.distance, self.angle_diff) self.move(*params, self.pos) # self.draw_rect(screen) self.health -= 1
def contrastive_loss(self, x0, x1, norm=True): # https://github.com/google-research/simclr/blob/master/objective.py bsize = x0.shape[0] target = torch.arange(bsize).cuda() eye_mask = torch.eye(bsize).cuda() * 1e9 if norm: x0 = F.normalize(x0, p=2, dim=1) x...
This code defines a training step for a SimSiam model, computing both base (loss_bl) and contrastive (loss_cl) losses using features from a ResNet backbone. It combines these losses, applies meta-learning optimizations if enabled, and logs training metrics. The model uses masked inputs and two optimizers for parameter ...
def training_step(self, batch, batch_idx): (x0, x1), _, _ = batch masks = torch.ones((512)).to(x0.device) if self.enable_meta: masks = self.auto_mask() x0_bl, x1_bl, x0_cl, x1_cl = self.resnet_simsiam(x0, x1, masks) # our simsiam model returns both (features + proje...
def Validate(self): # ? Assign cookie to driver, auth cookie if os.path.exists("Cookies.pkl"): for cookie in pickle.load(open("Cookies.pkl", "rb")): cookie_new = cookie if cookie.get('expiry') != None: del cookie['expiry'] self.DRIVER.add_cookie(cookie) validateURL = f"https:...
The code scrapes LinkedIn user URLs based on a keyword, scrolls pages to load content, extracts links, and saves them in a JSON file. It iterates through pages until reaching a specified result size, appending new URLs to the file. Finally, it closes the browser and returns processed user data.
def ScrapUserURL(self, keyword="agoda", size=80, close=False): # ? Validate driver is logged in if not self.Validate(): return self.DRIVER.quit() saveURL = 'data/url/' + cfg.BASE_DATE + '.json' page = 0 currentSize = 0 # ? Scrap each page in keyword # for page in range(page_start, page_...
def accuracy(self, dataset): N = dataset.shape[0] predictions = dataset.apply(lambda row: self.predict(row), axis=1) matches = sum(x == y for x, y in zip(predictions, dataset.iloc[:, -1])) percentage = matches/N return percentage def breadth(self): nodes = [] if s...
The function performs iterative pruning on a decision tree by evaluating node removals based on accuracy improvements. It calculates baseline accuracy, tests each non-root node's impact by temporarily assigning its color, and retains the node that maximizes accuracy. If improvement is non-negative, the node is permanen...
def reduced_pruning(self, train_dataset, prune_dataset): improvement = 0 while improvement >= 0: base_acc = self.accuracy(prune_dataset) best_acc, best_node = 0, None for node in self.breadth(): if (node.get_color() is None) and (node is not self.get_r...
def _basic_grow(self, dataset, m=None, depth=float('inf'), min_leaves=1): current_node = self.get_root() N = dataset.shape[0] if (current_node.gini(dataset) == 0) or (depth == 0) or (N <= min_leaves): current_node.average_color(dataset) return current_node.get_color() ...
The code trains a decision tree by splitting the dataset into training and pruning subsets (if post_pruning is specified). It builds the tree using `_basic_grow` with parameters like depth and minimum leaves. If post-pruning is enabled, it applies either minimum error pruning ("mep") or reduced error pruning ("rep") on...
def grow(self, dataset, m=None, depth=float('inf'), min_leaves=1, post_pruning=None): if post_pruning is not None: train_data, prune_data = train_test_split(dataset, test_size=0.3) else: train_data = dataset self._basic_grow(train_data, m, depth, min_leaves) if po...
def obtain_downlink_images_filepaths(mission_folder_path): list_filepaths = [] for file in os.listdir(mission_folder_path): list_filepaths.append(mission_folder_path + '/' + file) return list_filepaths def chop_bytes(bytes_arr, chunk_size): chunk_arr = [] idx = 0 while idx + chunk_size ...
The main task of the code is to download and transmit images from a specified mission folder via a serial connection. It processes each image by compressing, encoding with Reed-Solomon, splitting into batches, and sending them with start packets and delays. Shell scripts handle preprocessing and cleanup, while data is ...
def download_cmd(ser_obj, mission_folder): curr_img_count = 0 filepath_list = obtain_downlink_images_filepaths( mission_folder) print(f"List of images: {filepath_list}") total_img = len(filepath_list) for file in filepath_list: curr_img_count = curr_img_count + 1 print(f"...
def printWithPrefix(*args, incr=0, **kargs): print(lineprefix(incr=incr), end='') print(*args, **kargs) def printContentLine(contLine, incr=0): printWithPrefix('ContentLine:', incr=incr) printWithPrefix('name:'+str(contLine.name), incr=1) printWithPrefix('value:'+str(contLine.value)) printWithPrefix('params:'+str...
The main task of the code is to recursively print the contents of a container object, including nested containers and content lines, with indentation levels managed via the 'incr' parameter. It prints a "Container:" prefix, iterates through items, handles nested containers via recursion, adjusts indentation for nested ...
def printContainer(cont, incr=0): printWithPrefix('Container:', incr=incr) tempIncr=1 for tempObj in cont: if type(tempObj) == ics.grammar.parse.ContentLine: printContentLine(tempObj, incr=tempIncr) elif type(tempObj) == ics.grammar.parse.Container: printContainer(tempObj, incr=tempIncr) if tempIncr > 0:...
def printWithPrefix(*args, incr=0, **kargs): print(lineprefix(incr=incr), end='') print(*args, **kargs) def printContainer(cont, incr=0): printWithPrefix('Container:', incr=incr) tempIncr=1 for tempObj in cont: if type(tempObj) == ics.grammar.parse.ContentLine: printContentLine(tempObj, incr=tempIncr) elif ...
The main task of the code is to print the 'extra' attribute of the input object `var` with customizable indentation, using helper functions `printWithPrefix` and `printContainer` to format output. The `incr` parameter controls indentation levels, and `lineprefix(-1)` adjusts formatting after printing.
def printExtra(var, incr=0): printWithPrefix('extra:', incr=incr) printContainer(var.extra, incr=1) lineprefix(-1)
def printWithPrefix(*args, incr=0, **kargs): print(lineprefix(incr=incr), end='') print(*args, **kargs) def printDuration(var, incr=0): printWithPrefix('duration:' + str(var.duration), incr=incr) printWithPrefix('min:' + str(var.duration.min), incr=1) printWithPrefix('max:' + str(var.duration.max)) printWithPrefi...
This function prints detailed information of an event object, including attributes like alarms, attendees, categories, and timestamps, using a prefixed format. It calls helper functions to print duration, geographic data, extra fields, and adjusts indentation levels for structured output.
def printEvent(var, incr=0): var=eachEvent varName='eachEvent' printWithPrefix(varName+':', incr=incr) printWithPrefix('alarms:'+str(var.alarms), incr=1) printWithPrefix('attendees:'+str(var.attendees)) printWithPrefix('categories:'+str(var.categories)) printWithPrefix('created:'+str(var.created)) printWithPref...
def ask(a, b, c): eprint(f" Ask {a} {b} {c}", end='') print(a, b, c) r = int(input()) eprint(f" -> {r}") if r == -1: exit() return r def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def compare(a, b, l1, l2): if a == l1: return -1 elif b == l1: return 1 elif a == l2:...
The code identifies two critical values (l1, l2) through iterative comparisons with a custom `ask` function, then sorts numbers 1 to N using these values as a comparator. Finally, it passes the sorted list to a `guess` function. The core task is to determine optimal thresholds (l1, l2) for ordering elements and applyin...
def solve(N): l1 = 1 l2 = 2 for i in range(3, N + 1): a = ask(l1, l2, i) if a == l1: l1 = i elif a == l2: l2 = i eprint(f"Limits: {l1} {l2}") L = list(range(1, N + 1)) Q = sorted(L, key=functools.cmp_to_key(lambda a, b: compare(a, b, l1, l2))) guess(Q)
def clean_text(text,arg): clean_txt1 = remove_number(text) stop_words1 = extra_stopwords(clean_txt1) tokens = word_tokenize(clean_txt1) if arg: remove_ = [str(i).lower() for i in remove_words(clean_txt1) if i] stop_words2 = stop_words1 + remove_ else: ...
The main task of the code is to determine if a given string is in title case format. It checks conditions like whether the string or its cleaned words are title-cased, if proper nouns are present, or if the string lacks words but contains proper nouns. It returns 1 if any condition matches, otherwise 0.
def title_case(s1): _,words = clean_text(s1,True) b1 = remove_number(s1) if (b1.istitle())|((' '.join(words)).istitle())|(proper_noun(b1)[0]==1)|((len(words)==0)&len(proper_noun(b1)[1])>0.9): value = 1 else: value = 0 return value
def open_gripper(gazebo_model_name=None): set_gripper(0.0) # Destroy dynamic joint if gazebo_model_name is not None: req = AttachRequest() req.model_name_1 = gazebo_model_name req.link_name_1 = "link" req.model_name_2 = "robot" req.link_name_2 = "wrist_3_link" ...
The code identifies a Lego piece matching the specified color from a list, retrieves its details, straightens it using Gazebo coordinates, and returns a dictionary containing the Lego's name, pose, color, and Gazebo model name.
def pick(to_pick, legos): lego = {} for model_name, model_pose, model_color in legos: if model_color == to_pick: lego_name = model_name lego_pose = model_pose lego_color = to_pick break open_gripper() # Get actual model_name at model xyz co...
def delete_model(name): delete_model_client = rospy.ServiceProxy('/gazebo/delete_model', DeleteModel) return delete_model_client(model_name=name) def spawn_model(model, pos, name=None, ref_frame='world', color=None): if name is None: name = model model_xml = open(getModelPath(model), 'r').read() if color is ...
The function `setUpArea` clears existing bricks, creates a spawn area, and spawns Lego bricks based on the `livello` parameter (1-4). Level 1 spawns a specific brick with varied colors; Level 2 spawns all bricks; Level 3 spawns first four bricks and rotated variants; Level 4 builds predefined structures or uses `select...
def setUpArea(livello=None, selectBrick=None): #delete all bricks on the table for brickType in brickList: #ripulisce count = 1 while delete_model(f'{brickType}_{count}').success: count += 1 #screating spawn area spawn_model(spawn_name, Pose(Point(*spawn_pos),None) ) try: if(livello == 1): #spawn r...
def nussinov(rna): """ Takes a star notation rna sequence as input and puts out a list of lists where each sublist corresponds to the possible stuctures calculated by to nussinov algorithm for the given sequence """ split_seq = rna.split() UL_liste = cv.UL_list(split_seq) nm = init_matrix(UL_liste) M = ...
The code processes an RNA sequence to predict possible secondary structures using the Nussinov algorithm. It generates unpaired loop lists, identifies domain folds, and enumerates all feasible structural paths. The function returns these paths along with the Nussinov output for further analysis.
def nussinov_modules(rna): """ Takes rna sequence and applies our nussinov algorithm to it. Args: module_fol rna (str): domain level sequence with spaces Returns: possible_paths (list): List of all possible paths were each sublist corresponds to one path. """ nussi_output = nussinov(rna) print("nuss...
def d_length(domain): if domain[0] == "b" or domain[0] == "B": return 5 elif domain == "l": return 5 return 3 def add_folding_path_constraint(path,UL_seq,model): """ Takes the path calculated from nussinov for the sequences and adds those pair constraints to the model args: ...
The code designs an RNA sequence from a given annotated sequence and folding path by applying constraints, optimizing with GC content and energy considerations, and outputting the optimized sequence along with structural scores. It uses domain-based modeling, path constraints, and Monte Carlo optimization to achieve a ...
def rna_design(seq,path): """ Takes the calculated sequence(With space annotation) and the calulated nussinovpath as input and designs a RNA sequence args: seq: sequence generated by path_to_seq (space annotation) path: extended folding path """ print("Given sequence: ",seq)...
def loss(x): return f(x)**2 def armijo(x, maxiter=100, c1=.5, c2=1.9): alpha = 0.4 for _ in range(maxiter): while not(f(x - alpha * gradient(x)) <= f(x) - c1 * (gradient(x)**2) * alpha).all(): alpha *= 0.7 while not (f(x - gradient(x) * alpha * c2) > f(x) - c1 * gradient(x) ** ...
The code performs gradient descent with Armijo backtracking line search to minimize a loss function. It initializes parameters as zeros, iteratively updates them using a step size (alpha) determined by the Armijo rule, and stops when the loss falls below a tolerance threshold (tol). The goal is to find optimal paramete...
def minimize(): x = np.zeros(len(A)) while loss(x) > tol: alpha = armijo(x) x += alpha * -gradient(x) # print('Loss: ', loss(x)) return x
def sgd(alpha, indices=batchsgd()): for i in range(len(indices)): x = np.array(( user_x_categories[indices[i][0]], movies_x_categories[:, indices[i][1]], dictionary_matix[indices[i]] )) grad = gradient(x) user_x_categories[indices[i][0]] -= alpha...
This code trains a model using stochastic gradient descent (SGD) with exponential decay on the learning rate (alpha). It iteratively updates parameters via batch SGD, computes loss on randomly selected entries from a dictionary matrix, and prints accumulated loss at intervals. The goal is to minimize loss by adjusting ...
def train_(maxiter=9000): training = [] alpha = .01 constant = .001 for i in range(maxiter): alpha *= (math.exp(-constant)) sgd(alpha, batchsgd()) total_loss = 0 random_value = random.randrange(len(dictionary_matix)) if i % random_value == 0: for k, v ...
def gradient(x): eps = 1e-5 grad = [np.zeros((n_cats,)) for _ in range(3)] x0 = np.copy(x[0]) x1 = np.copy(x[1]) for i in range(len(x[0])): x0_eps = np.copy(x0) x0_eps[i] = x0[i] + eps new_x = [x0_eps, x1, x[2]] grad[0][i] = (loss(new_x) - loss(x)) / eps for i i...
The code performs Stochastic Gradient Descent (SGD) to update user and movie embedding vectors in a recommendation system. It iterates over given indices, computes gradients and loss for each sample, adjusts embeddings using a learning rate (alpha), and periodically calculates the total loss across all known ratings. T...
def sgd(indices): # random.seed(2020) range_loss = [] for i in range(len(indices)): x = np.array([user_x_categories[known_users[indices[i]]], movies_x_categories[:, movies_users[indices[i]]], known_scores[indices[i]]]) grad = gradient(x) ra...
def plot_luminance(datasets, labels, colors, axs, luminance_sample): print("Creating luminance histogram...") lums = [] for i in range(len(datasets)): bins = np.arange(0, 256, 1) fractional_lum, bins = get_luminance(datasets[i], bins, luminance_sample) lums.append(fractional_lum) ...
The main task of the code is to generate a composite figure with multiple statistical plots (luminance, spatial power spectra, derivatives, motion, speed-direction, and flow derivatives) from input datasets. It uses provided labels and colors for each dataset, arranges them in a 2x4 grid (excluding one subplot), sets f...
def plot_stats(datasets, labels, colors, plot_file_name, luminance_sample=0): # Setting up figure fig, axs = plt.subplots(2, 4) fig.delaxes(axs[0][3]) plot_luminance(datasets, labels, colors, axs, luminance_sample) plot_spatial_power_spectra(datasets, labels, colors, axs) plot_spatial_deriv...
def plot_luminance(total_frame_paths, labels, colors, luminance_sample): print("Creating luminance histogram...") fig, ax = plt.subplots() lums = [] for i in range(len(total_frame_paths)): bins = np.arange(0, 256, 1) fractional_lum, bins = get_luminance(total_frame_paths[i], bins, lumin...
The function `plot_stats` generates multiple visualizations of statistical properties from input data, including luminance, spatial power spectra, spatial derivatives, motion, speed, direction, and flow derivatives. It processes frame paths and flow matrices, optionally limiting data size via `file_limit`, and uses lab...
def plot_stats(total_frame_paths, total_flow_matrices, labels, colors, file_limit=0, luminance_sample=0): # if file_limit, extract paths if file_limit: for i in range(len(total_frame_paths)): total_frame_paths[i] = total_frame_paths[i][:file_limit] total_flow_matrices[i] = total_...
def get_uniform_samples(self): """Get uniform parameter samples. Get uniform parameter samples in case no user-defined samples are provided. The user-defined upper and lower bounds of the parameter vector are used. Parameters ---------- None Returns ...
The main task of the code is to execute the MLGLUE algorithm to select posterior samples, compute likelihoods, and generate simulated observations. It handles parameter sampling, tuning, variance/mean analysis, threshold calculation, and sampling via single-core or parallel processing. The method returns selected sampl...
def perform_MLGLUE(self): """Perform the full MLGLUE algorithm. Perform the full MLGLUE algorithm using single-core or parallelized computation. Settings for performing all computations are obtained from instance attributes. Parameters ---------- None ...
def sampleTestData(TPM_channel, testChannels, testLabels, subjectIndex, output_classes, output_dpatch,logfile): proxy_img = nib.load(testChannels[0]) shape = proxy_img.shape affine = proxy_img.affine xend = output_dpatch * int(round(float(shape[0])/output_dpatch + 0.5)) # shape[0] + output_dpatch#-o...
This function performs full-head brain segmentation using a 3D neural network model on MRI data. It extracts image patches, processes them in minibatches with TPM data, predicts segmentations, and reconstructs the full volume. It optionally computes DICE scores against ground truth labels and saves results as NIfTI fil...
def fullHeadSegmentation(wd,subj, penalty_MATRIX, TPM_channel, dice_compare, dsc, model, model_name, testChannels, testLabels, subjectIndex, output_classes, segmentation_dpatch, size_minibatches,logfile, epoch, saveSegmentation = False): if ('Baseline' in model_name) or ('MultiPriors' in model_name) or ('DeepM...
def rule_by_target(target: str, creat: bool = True) -> dict: global rule_table if target not in rule_table: if creat is False: return None add_rule(target) return rule_table[target] def get_prerequisites(target: str) -> list: rule = rule_by_target(target, False) if rule i...
The function `dump_rule` generates a formatted string representing a build rule for a given target. It concatenates the target, its prerequisites, and associated recipes into a structured output, then prints it. If no rule exists for the target, it exits early. The output includes the target name, followed by its depen...
def dump_rule(target: str) -> None: dump_str = target + ': ' rule = rule_by_target(target, False) if rule is None: return for prerequisite in get_prerequisites(target): dump_str += prerequisite + ' ' dump_str += '\n' for recipe in get_recipes(target): dump_str += '\t%s\n'...
def add_prerequisites(target: str, *prerequisites: str) -> None: rule = rule_by_target(target, True) for prerequisite in prerequisites: rule['prerequisites'].append(prerequisite) def add_recipes(target: str, *recipes: str) -> None: rule = rule_by_target(target, True) for recipe in recipes: ...
The code tests a rule management system by adding prerequisites, recipes, and rules for targets, then dumping their states at different stages. It verifies rule additions, modifications, and clearing by printing rule configurations after each operation, including final dumps and a reset of all rules.
def test_rule(): add_prerequisites('target1', 'pre1', 'pre2') add_recipes('target1', 'do sth1', 'do sth2') print('1=====================') dump_rules('target1', 'target2', 'target3') add_prerequisites('target2', 'pre1', 'pre2') print('2=====================') dump_rules('target1', 'target2'...
def _load_conll_data(self, datasets_path: str) -> dict: """Load the CONLL-formatted data from the given folder. Only loads train and dev, as loading test would give it an unfair advantage vs other models. Args: datasets_path (str): The folder containing the three ...
The code builds a frequency dictionary from CONLL-formatted training/dev datasets, chunks it into structured data, and saves it as a "trained model" for heuristic tagging of test sentences. It does not perform traditional model training but constructs a dictionary-based tagging resource.
def train(self, datasets_path: os.path, trained_model_path: os.path): """ "Train" the dictionary model on the given conll datasets. Note it isn't actually training... just building a dictionary from the training/dev datasets and using it as a means to heuristically tag the test sents. ...
def cmd(command): if inp == command: return True else: return False def printCommands(): print(' commands:') printCom('full', 'does a full scan') printCom('scan', 'does a quick scan in common virus locations') printCom('view', 'view scan results') printCom('test', 'makes s...
The main task of the code is to handle user commands for initiating different types of scans. It checks for commands like 'help', 'full', 'scan', and 'test', executing corresponding scan operations (e.g., running scans from specific starting points) and ending the scan process. The function routes input commands to app...
def doCommand(): if cmd('help'): printCommands() if cmd('full'): runScan(fullStart) endScan() if cmd('scan'): runScan(downloadStart) runScan(tempStart) runScan(sys32Start) endScan() if cmd('test'): runScan(testStart) ...
def parse_args(): parser = ArgumentParser(description="Example recommender based on the MovieLens 20M dataset") subparsers = parser.add_subparsers(dest="subcommand") parser_fit = subparsers.add_parser("fit", help="Fit the model") parser_fit.add_argument( "--num_iter", type=int, default=50, help=...
The main task of the code is to execute different functions based on the provided subcommand argument. It parses input arguments, checks the subcommand value, and calls either 'fit', 'update', or 'recommend' functions accordingly, allowing the program to handle distinct operations depending on user input.
def main(): args = parse_args() if args.subcommand == "fit": fit(args) if args.subcommand == "update": update(args) if args.subcommand == "recommend": recommend(args)
def _init_data(self, user_items: sps.spmatrix) -> None: """Initialize parameters and hyperparameters before batch training""" # coerce user_items to csr matrix with float32 type if not isinstance(user_items, sps.csr_matrix): print("converting user_items to CSR matrix") us...
The main task of the code is to train a collaborative filtering model on user-item rating data by iteratively updating user and item embeddings. It performs alternating least squares optimization over a specified number of iterations, optionally printing loss values per iteration. If enabled, it converts the sparse mat...
def fit( self, user_items: sps.spmatrix, show_loss: bool = False, postprocess: bool = True ) -> None: """Fit the model to the given rating data from scratch Parameters ---------- user_items: scipy.sparse.spmatrix Rating matrix for user-item pairs show_los...
def _convert_data_for_online_training(self) -> None: """convert matrices to lil for online training""" if self._training_mode == "online": return del self._user_items_csc gc.collect() self._user_items_lil = self._user_items.tolil() del self._user_items ...
The function updates a model for a single user-item pair by iteratively adjusting user and item vectors, and the SV matrix. It initializes new items' vectors if needed, expands data structures, and optionally prints loss. The process involves updating user/item representations and their interactions, ensuring the model...
def update_model(self, u: int, i: int, show_loss: bool = False) -> None: """Update the model for single, possibly new user-item pair Parameters ---------- u: int User index i: int Item index show_loss: bool Whether to compute and print...
def insert_parabola(self, parabola_vector): """ """ # Base case if self.root_parabola == None: self.root_parabola = VoronoiParabola(parabola_vector) return # Degenerate event - heights are the same if self.root_parabola.isLeaf and (self.root_parab...
The main task of the code is to generate Voronoi edges by processing events from a queue, updating the sweep line position, inserting or removing parabolas, finalizing edge connections, and returning the resulting edge list. It handles event-driven construction of Voronoi diagrams, adjusts edge endpoints, and ensures p...
def get_edges(self): """ Retrieves the voronoi edges without animation """ while not self.event_queue.empty(): event = self.event_queue.get() self.sweep_line_pos = event.point[1] if event in self.deleted_events: self.deleted_events.remo...
def insert_parabola(self, parabola_vector): """ """ # Base case if self.root_parabola == None: self.root_parabola = VoronoiParabola(parabola_vector) return # Degenerate event - heights are the same if self.root_parabola.isLeaf and (self.root_parab...
The main task of the code is to update the beach line structure during an animation by processing events from a queue. It adjusts the sweep line position, inserts or removes parabolas based on event flags, and finalizes edges. When the event queue is empty, it completes the root edge, connects remaining edges, and mark...
def update(self): """ Will be called to update the beach line, supports animation """ if not self.done: if not self.event_queue.empty(): event = self.event_queue.get() self.sweep_line_pos = event.point[1] if event in self.delete...
def point_location(self, point): """ Iterative point location for the triangulation """ for (a, b, c) in self.triangles: if self.in_triangle_test(point[0], point[1], (a, b, c)): return (a, b, c) return None def on_triangle_edge_test(self, point, tri_in...
This function adds a point to a triangulation structure, determining its position relative to existing triangles. If the point lies on a triangle's edge, it splits the triangle into four sub-triangles and legalizes edges; otherwise, it splits the triangle into three and legalizes each new edge. The process ensures the ...
def add_point(self, point): """ Adds the point to the triangulation, and legalizes the edges """ tri = self.point_location(point) # if this assert hits, it means that super triangle was not large enough assert (tri != None) (a, b, c) = tri nullable_edge =...
def _ref( name: str, package: Optional[str] = None, version: Optional[int] = None, ) -> str: parts: List[str] = [] if package: parts.append(repr(package)) parts.append(repr(name)) if version: parts.append(f"{version=}") inner = ",".join(parts) return "{{ ref(" + inn...
This function retrieves a specified database model by constructing a SQL query to select all data from the model, then executes the query using dbt with optional profile and target settings, returning the result as a Table.
def get_model( name: str, package: Optional[str] = None, version: Optional[int] = None, profile: Optional[str] = None, target: Optional[str] = None, ) -> "Table": model = _ref(name, package, version=version) q = f"select * from {model}" # noqa: S608 return _dbt_show( inline=q, ...
def get_empty_squares(self, array): empty_squares = [] for row in range(array.shape[0]): for col in range(array.shape[1]): if array[row][col] == 0: empty_squares.append((row, col)) return empty_squares def rollout_policy(self, possible_moves): ...
The main task of the code is to simulate a game rollout by iteratively selecting moves using a rollout policy until the game ends (either a player wins or no moves remain). It alternates the player's turn, updates the game state, and returns the final game result.
def rollout(self): current_rollout_state = self.board while current_rollout_state.has_won() == 0 and len(self.get_empty_squares(current_rollout_state.array)) != 0: possible_moves = self.get_empty_squares(current_rollout_state.array) action = self.rollout_policy(possible_moves) ...
def one_hot_encoding(self, y): """ Encodes labels into binary vectors Args: y (np.ndarray): labels Returns: np.ndarray: binary encoded labels """ one_hot_y = np.zeros((len(y), len(np.unique(y)))) for i in range(len(y)): one_hot_y[i, ...
This code trains a one-vs-all logistic regression model by iterating over each class, using batch gradient descent with cross-entropy loss to update weights and bias terms. It initializes parameters randomly, processes data in batches, computes gradients, and tracks loss for each class. The final model parameters (weig...
def fit(self, x, y): """ Fits the one-vs-all logistic regression model to the training data Args: x (np.ndarray): input features y (np.ndarray): target labels Returns: np.ndarray: model parameters (weights and bias) """ class_types = np.uniqu...
def _get_img_data( img_name: str, placement_settings: PlacementSettings ) -> Tuple[str, str, ImageSettings]: """Anchor names for images are formatted so: {type}__{optional: person/role} We use the type to figure out how to load the image and what settings to use to position and resize the image. The...
The main task of this code is to insert images and dynamic text into specified positions on a PDF document. It processes metadata to determine where to place each image, applies filtering via regex and page numbers, and constructs a new PDF with the additions using a Document object. The function handles both image ins...
def add_images_to_pdf( initial_pdf: bytes, metadata: List[Dict[str, List[Tuple[float, float]]]], img_loader: Callable[[str], Image], dynamic_text: Dict[str, str], placement_settings: PlacementSettings = None, only_matches: Optional[str] = None, page_numbers: Optional[List[int]] = None, ) -> ...
def generate_e(n): """ Functie ce calculeaza variabila e pt RSA :param n: intreg n :return: un numar random, mai mic ca n, care sa fie prim cu n """ while True: x = random.randint(1, n - 1) if cmmdc(x, n) == 1: return x def modinv(a, m): """ Functie ce returne...
The main task of the code is to generate RSA public and private key pairs using fixed prime numbers (p=31, q=37). It calculates the modulus (n), Euler's totient (phi_n), selects a public exponent (e) via generate_e(), computes the private exponent (d) using modular inversion, stores intermediate values with write_data(...
def generate_keys(): """ Functie ce returneaza cheia publica si cheia privata pt RSA :return: returneaza cele 2 perechi de chei - publica si privata """ p = 31 q = 37 n = p * q phi_n = (p - 1) * (q - 1) e = generate_e(phi_n) d = modinv(e, phi_n) write_data(p, q, n, phi_n, e, ...
def find_neighbors(self, context): '''Finds neighbors of current tile in order to find shortest path to end point''' zerg_map_location = self.overlord.zerg_to_map[id(self)] symbol_map_list = self.overlord.map_object.map_symbols[zerg_map_location] for x in list(symbol_map_list.keys())...
This code navigates a Zerg unit by mapping its environment, identifying target locations ("*"), calculating distances, and determining movement directions. It updates the map with terrain/symbol data, finds the shortest path to targets, and returns directional commands based on context. The function manages position tr...
def action(self, context): '''returns the directional command to move to''' new_x = context.x new_y = context.y new_south = context.y - 1 new_east = context.x + 1 new_west = context.x - 1 new_north = context.y + 1 id_of_zerg = id(self) ...
def dX_dt(fx, params): return params[2] def dY_dt(fy, params): return params[3] def dN_dt(fn, params): #direct equation plugging trigs = computeIntegrals(params[2], params[3], params[4]) constPack = 2 * n.pi * params[3] * ROCK_MASS return ((params[4] * (trigs[0])) - (params[2] * trigs[3])) / (constP...
The main task of the code is to compute and return the time derivatives of five variables (X, Y, N, P, W) in a dynamic system. It aggregates results from five separate functions `dX_dt`, `dY_dt`, etc., each calculating the rate of change for a specific variable using provided parameters `fparams` and `params`, consolid...
def wholeSystem(fparams, params): return [dX_dt(fparams, params), dY_dt(fparams, params), dN_dt(fparams, params), dP_dt(fparams, params), dW_dt(fparams, params)]
def poll_dash_central(): proposal_hash = os.getenv('PROPOSAL_HASH') url = "https://www.dashcentral.org/api/v1/proposal?hash={}".format(proposal_hash) data = requests.get(url) proposal_data = json.loads(data.text)['proposal'] min_quorum = int(get_mn_count())/10 proposal_data['current_ratio'] = ...
The code checks for updates in vote and comment counts from a data source, compares them with cached data, and triggers a webhook notification if the changes exceed a threshold. It updates stored data and logs results, ensuring only significant changes prompt alerts.
def check_for_updates(): new_data = poll_dash_central() # Check to make sure that we have cached data before continuing if check_file('dc_data'): old_data = read_json("dc_data") else: write_json(new_data, "dc_data") old_data = read_json("dc_data") # Calculate the difference...
def set_new_repo(path): if not os.path.exists(path): os.makedirs(path) print("new folder: %s" %path) else: print("update folder: %s" %path) def image_enhancement(frame): err_kernel = np.ones((3, 3), np.uint8) dil_kernel = np.ones((3, 3), np.uint8) img_erosion = cv2.erode(fra...
The code performs background subtraction on a video to extract foreground silhouettes, applying thresholding, median blur, and morphological enhancement. Valid silhouettes (with sufficient white pixels) are saved, segmented into views, and processed into subdirectories based on subject (sub_id), condition (cond_id), an...
def background_subtract(avi_name, sub_id, cond_id, pid): in_path = os.path.join(INPUT_PATH, avi_name) full_path = os.path.join(OUTPUT_PATH, avi_name) set_new_repo(full_path) p_full_path = os.path.join(POST_PATH, sub_id, cond_id).replace("\\", "/") set_new_repo(p_full_path) backSub = cv2.create...
def copy_bits(dest_data, dest_bit_pos, src_data, src_bit_pos, num_bits): bits_to_copy = min(num_bits, 8 - (dest_bit_pos & 7)) copy_bits_in_a_byte(dest_data, dest_bit_pos, src_data, src_bit_pos, bits_to_copy) num_bits -= bits_to_copy while (num_bits != 0): dest_bit_pos += ...
This function decompresses data using a bitstream and sliding window. It processes bits to either copy literal bytes or reference prior data via offset/length. It builds decompressed data while managing a window to limit memory usage, adjusting the window position when exceeding size limits.
def decompress(data, unpack_len): if (unpack_len > 0x10000): return b'' dec_data = b'' bit_pos = 0 wnd_pos = 0 wnd_size = 0 i = 0 while (i < unpack_len): b = get_bit(data, bit_pos) bit_pos += 1 if (b == 0): s = bytearray(b'\0') copy...
def initialize_weights(self, dims): if self.seed is not None: np.random.seed(self.seed) self.weights = {} all_dims = [dims[0]] + list(self.hidden_dims) + [dims[1]] # self.weights is a dictionnary with keys W1, b1, W2, b2, ..., Wm, Bm where m - 1 is the n...
The code trains a neural network model over multiple epochs using mini-batch gradient descent. It initializes weights, processes data in batches, performs forward and backward passes to compute gradients, updates parameters, and logs training/validation loss/accuracy after each epoch. The function returns a dictionary ...
def train_loop(self, n_epochs): X_train, y_train = self.train y_onehot = y_train dims = [X_train.shape[1], y_onehot.shape[1]] self.initialize_weights(dims) n_batches = int(np.ceil(X_train.shape[0] / self.batch_size)) for epoch in range(n_epochs): for batch i...
def parse_nout(self, x): """ This function returns an iterable array that contains the outbound neighbors of x :param x: The vertex :return: The list of outbound neighbors Precondition: x is a valid vertex of the graph. """ if not self.is_vertex(x): ra...
This function removes a vertex from a graph by first verifying its existence, then updating all adjacent vertices' in/out lists and removing corresponding edge costs. It iterates through outgoing and incoming neighbors, adjusts their connections, and finally deletes the vertex's entries from the graph's data structures...
def remove_vertex(self, x): """ Removes a vertex from the graph :param x: The vertex to be removed Precondition: The vertex x must exist in the graph """ if x not in self.din.keys(): raise ValueError(f"{x} is not in the graph") for y in self.parse_nou...
def parse_vertices(self): """ This function returns a list of the vertices ( in ascending order) :return: The list """ l = list(self.din.keys()) l.sort() return l def parse_nout(self, x): """ This function returns an iterable array that contains t...
The main task of the code is to print a graph's structure by iterating through vertices and edges. It prints isolated vertices first, then outputs directed edges (x, y) with their costs only once when x < y, avoiding duplicates. The function uses internal methods to parse vertices/edges and accesses a cost dictionary t...
def print_graph(self): """ This function prints the graph on the screen :param graph: The graph to be printed :return: """ for x in self.parse_vertices(): if len(self.parse_nout(x)) + len(self.parse_nin(x)) == 0: print(x) for y in s...
def parse_nout(self, x): """ This function returns an iterable array that contains the outbound neighbors of x :param x: The vertex :return: The list of outbound neighbors Precondition: x is a valid vertex of the graph. """ if not self.is_vertex(x): ra...
The main task of the code is to remove a specified vertex from a graph. It first verifies the vertex exists, then updates all incoming and outgoing edges connected to the vertex by removing it from adjacency lists and deleting corresponding edge entries from the cost dictionary. Finally, it completely removes the verte...
def remove_vertex(self, x): """ Removes a vertex from the graph :param x: The vertex to be removed Precondition: The vertex x must exist in the graph """ if x not in self.din.keys(): raise ValueError(f"{x} is not in the graph") for y in self.parse_nou...
def parse_vertices(self): """ This function returns a list of the vertices ( in ascending order) :return: The list """ l = list(self.din.keys()) l.sort() return l def parse_nout(self, x): """ This function returns an iterable array that contains t...
This function prints the vertices and edges of a graph, displaying isolated nodes and their outgoing edges with associated costs from the dcost dictionary. It iterates through vertices, checks for nodes with no connections, and prints edges with their costs if present.
def print_graph(self): """ This function prints the graph on the screen :param graph: The graph to be printed :return: """ for x in self.parse_vertices(): if len(self.parse_nout(x)) + len(self.parse_nin(x)) == 0: print(x) for y in s...
def initialise(self): for i in range(0, self.n): self.din[i] = [] self.dout[i] = [] def is_edge(self, x, y): """ Checks if there is an edge from x to y :param x: First vertex :param y: Second vertex :return: True or False accordingly """ ...
The function generates a random graph with `n` vertices and `m` edges by repeatedly selecting random vertex pairs and assigning random costs, adding edges only if they don't already exist, until `m` edges are successfully created.
def create_random_graph(self, n, m): """ This function creates a new random graph :param n: The number of vertices of the new graph :param m: The number of edges of the new graph :return:The created graph Preconditions: m <= n """ if m > n or m < 0 or n < ...
def initialise(self): for i in range(0, self.n): self.din[i] = [] self.dout[i] = [] def is_edge(self, x, y): """ Checks if there is an edge from x to y :param x: First vertex :param y: Second vertex :return: True or False accordingly """ ...
The function generates a random graph with `n` vertices and `m` edges by repeatedly selecting random vertex pairs and assigning random costs, adding edges only if they don't already exist, until `m` edges are created. It validates input constraints and initializes the graph structure before populating it with edges.
def create_random_graph(self, n, m): """ This function creates a new random graph :param n: The number of vertices of the new graph :param m: The number of edges of the new graph :return:The created graph Preconditions: m <= n """ if m > n or m < 0 or n < ...
def macro_accuracy(yhat, y): num = intersect_size(yhat, y, 0) / (union_size(yhat, y, 0) + 1e-10) return np.mean(num) def macro_precision(yhat, y): num = intersect_size(yhat, y, 0) / (yhat.sum(axis=0) + 1e-10) return np.mean(num) def macro_recall(yhat, y): num = intersect_size(yhat, y, 0) / (y.sum(ax...
This function computes and returns four macro-averaged evaluation metrics—accuracy, precision, recall, and F1 score—by applying corresponding calculation functions to predicted labels (yhat) and true labels (y), aggregating results across classes equally.
def all_macro(yhat, y): return macro_accuracy(yhat, y), macro_precision(yhat, y), macro_recall(yhat, y), macro_f1(yhat, y)
def micro_accuracy(yhatmic, ymic): return intersect_size(yhatmic, ymic, 0) / union_size(yhatmic, ymic, 0) def micro_precision(yhatmic, ymic): return intersect_size(yhatmic, ymic, 0) / yhatmic.sum(axis=0) def micro_recall(yhatmic, ymic): return intersect_size(yhatmic, ymic, 0) / ymic.sum(axis=0) def micro_f1...
The function `all_micro` computes and returns four micro-averaged evaluation metrics—accuracy, precision, recall, and F1 score—using the predicted labels `yhatmic` and true labels `ymic`. It aggregates these metrics to assess model performance on a per-class basis, providing a comprehensive overview of classification a...
def all_micro(yhatmic, ymic): return micro_accuracy(yhatmic, ymic), micro_precision(yhatmic, ymic), micro_recall(yhatmic, ymic), micro_f1(yhatmic, ymic)