dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def tokenize_text2search(text): le = WordNetLemmatizer() tokens = nltk.word_tokenize(text) for i in range(len(tokens)): tokens[i] = tokens[i].replace('.', '') filtered_words = [le.lemmatize(w) for w in tokens if not w.lower() in stop_words and w.isalpha()] for i in range(len(filtered_words)): ...
The code calculates a text similarity score by comparing the input text's word set with words from search results. It tokenizes the input, searches for URLs, extracts and cleans their content, computes similarity matrices, identifies matching words, and returns the score as the ratio of overlapping words to total uniqu...
def text_similarity_score(data): search_word = tokenize_text2search(data) curl_list = [] url = [] for search_url in search(search_word, tld="co.in", stop=20, pause=2): if search_url[-3:] == 'pdf': continue clean_curl = curl_and_clean(search_url) curl_list.append(clean_curl) url.append(search_url) matri...
def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--mode', default='adjusted_score') parser.add_argument('--scores', nargs='+', type=float, default=[1199, 1546, 2197, 1857]) parser.add_argument('--target_rate', type=float, default=1600) parser.add_argument('--participation_cou...
The code's main task is to process different modes for score calculations. It calculates a rate from given scores, adjusts this rate based on score count, determines the next required score to meet a target rate, or computes an adjustment value from participation count. The function prints and returns results based on ...
def run(): args = get_args() if args.mode == 'score': scores = args.scores rate = calc_rate(scores) print(rate) return rate if args.mode == 'adjusted_score': scores = args.scores rate = calc_rate(scores) rate -= adjusted_value(len(scores)) pri...
def changeTime(self): laserpower = self.laserpowerEdit.value() itime = self.integrationtimeEdit.value() frames = self.framesEdit.value() totaltime = itime * frames / 1000 / 60 totaltime = round(totaltime * 100) / 100 self.totaltimeEdit.setText(str(totaltime)) pho...
The main task of the code is to create a graphical user interface (GUI) for configuring simulation parameters related to imaging experiments. It organizes settings into sections like camera parameters, PAINT model parameters, imager properties, noise models, and structure definitions. The GUI allows users to adjust val...
def initUI(self): self.currentround = CURRENTROUND self.grid = QtGui.QGridLayout() self.grid.setSpacing(5) # CAMERA PARAMETERS camera_groupbox = QtGui.QGroupBox('Camera parameters') cgrid = QtGui.QGridLayout(camera_groupbox) camerasize = QtGui.QLabel('Image siz...
def create_alternative_df(x, xk, xk1,xk2, F_exp): x = x.split() matrix=[] for Fi in F_exp: line=[] for j in range(len(x)): elem=calc_alt_dfij(j,x,xk,xk1,Fi)+calc_alt_dfij(j,x,xk2,xk,Fi)-calc_alt_dfij(j,x,xk2,xk1,Fi) line.append(elem) matrix.append(line) re...
This function implements a parallelized Potra method for solving nonlinear systems. It uses multiprocessing to compute updated variables (xk, Ak) iteratively until the solution converges within a specified tolerance (eps). The method employs finite differences to approximate derivatives, parallelizes key calculations, ...
def parallel_pro_potra_method(symb,F,F_exp, x0, eps): xk=numpy.array(x0) x = numpy.array([0] * len(xk)) xk1=numpy.array([e+10**-4 for e in xk]) xk2=numpy.array([e+2*10**-4 for e in xk]) Ak = numpy.linalg.inv(numpy.array(create_alternative_df(symb, xk, xk1,xk2, F_exp), dtype='float')) I2 = numpy....
def _evaluate_fitness(self, object, test_sample) -> float: """ Evaluates the fitness of an object for a given test sample by calculating the sum of distances between the training samples indexed by the object and the test sample. Parameters: ----------- object : numpy array ...
The main task of the code is to train a kNN-P classifier by iteratively optimizing objects within cells using fitness evaluation, evolving objects with the best-performing ones, and updating the environment through communication steps to enhance classification accuracy.
def fit(self, training_data: np.ndarray, class_labels) -> None: """ The main function for training the kNN-P classifier. It iteratively optimizes the objects in the cells and updates the best objects in the environment. Parameters: ----------- training_data : numpy array ...
def restore_weights(self): try: checkpoint = torch.load(self._saving_filepath) self._model.load_state_dict(checkpoint['model_state_dict']) self._model.optimizer.load_state_dict(checkpoint['optimizer_state_dict']) print(f"Model correctly Restored") self...
The code trains a model using user-item interactions with node dropout on the graph. It iterates over epochs, processes data in batches, computes loss via training steps, monitors for invalid loss values, and evaluates performance after each epoch. Node dropout randomly removes connections during training to prevent ov...
def train(self): if self._restore: return self.restore_weights() for it in self.iterate(self._epochs): loss = 0 steps = 0 self._model.train() if self._node_dropout > 0: sampled_adj = self.sparse_dropout(self.adj, ...
def restore_weights(self): try: checkpoint = torch.load(self._saving_filepath) self._model.load_state_dict(checkpoint['model_state_dict']) self._model.optimizer.load_state_dict(checkpoint['optimizer_state_dict']) print(f"Model correctly Restored") self...
The code trains a model by iterating over epochs, generating adjacency matrices based on the specified sampling strategy ('nd', 'ed', or 'rw'), processing transactions in batches, accumulating loss, and evaluating performance after each iteration. It handles edge cases like NaN/inf loss and restores weights if specifie...
def train(self): if self._restore: return self.restore_weights() for it in self.iterate(self._epochs): loss = 0 steps = 0 if self._sampling in ['nd', 'ed']: adj_1 = self.create_adj_mat(is_subgraph=True, aug_type=self._sampling) ...
def get_info(file_name: str) -> tuple: """Convert .txt file contents into a tuple of dictionaries. Given Books.txt, convert each line in the file into a dictionary, where each spaced out piece of text in the first line is the key and the proceeding lines are the values for the key it lines up with. Each di...
The main task of the code is to execute the Books.py program by reading data from "Books.txt," processing it through a menu-driven loop, updating the text file with modified data, and terminating the program with a thank-you message. It handles initialization, user interaction, file updates, and cleanup.
def books() -> None: """Runs Books.py from start to finish. To be used in the main() function.""" print("Initiating books.py...") books_file = get_info("Books.txt") final_books = menu(books_file) # main loop of the program print("\nUpdating text file...") quit_books(final_books, "Books.txt") ...
def collision_factory(self): # check for any collisions with any other entities and return the life_form_id of an entity # collided with collision_detected, collided_life_form_id = self.collision_detector() # get the count of total life forms currently active # if there has been...
The code moves an entity in a set direction, handling edge collisions by randomizing direction. It checks for collisions; if the entity dies, it returns "Died". If no collision, it moves the entity, updates surrounding positions, and decrements a timer. When the timer reaches zero, it randomizes direction regardless of...
def movement(self): """ Will move the entity in its currently set direction (with 8 possible directions), if it hits the edge of the board it will then assign a new random direction to go in, this function also handles the time to move count which when hits 0 will select a new random dir...
def character_movement(boards, board, board_list, name): """ Randomly moves the character on the board. Args: boards (dictionary), board (string), board_list (list of lists) and name (string). Returns: boards (dictionary) """ bad_character = boards[board]["characters"][name] numbers = rando...
This function updates game boards based on the player's current location, handling character movement, board updates when Loki is defeated, and gate-opening logic tied to collected stones. It returns messages, message types, and character names specific to the current board's events.
def plot_development(player, boards, board_list): ''' Function in charge of changing boards' elements to the current plot of the game. Args: player (dictionary), boards (dictinary) and board_list (list of lists). Returns: message, message_type and name (all strings). ''' message, message_type, ...
def display_title(board_name, console_width): ''' Displays board's name over the printed board. Args: board_name (string) and console_width (int). Returns: Nothing. ''' caption = pyfiglet.figlet_format("*** " + board_name + " ***", font="digital") caption = "*** " + board_name + " ***" ...
The main task of the code is to display a complete game board and coordinate the presentation of related elements like the title, description, player stats, equipment, legend, and messages. It uses the console width for proper formatting, integrating board data, player information, quests, and optional inventory/legend...
def display_board(board_list, board_name, player, quests, show_inventory, show_legend,legend, message): ''' Displays complete game board on the screen. Coordinates displaying other elements of screen. Args: board_list (list of lists), board_name (string), player, quests, legend (dictionaries), show_inve...
def initialise(self): self.outputs = self.initialOutputs.copy() self.game = self.gameObject() self.ended = False self.nextInput = (None, None) def back(self): self.initialise() App.get_running_app().root.current = "mainmenu" def restart(self): self.initialise() ...
This code initializes a UI component with back and restart controls. It sets up a layout containing two emoji buttons (◀ and 🔄) positioned horizontally at the bottom. The buttons trigger `self.back()` and `self.restart()` methods when pressed, enabling navigation and game reset functionality. The code also initializes...
def __init__(self, **kwargs): BoxLayout.__init__(self, **kwargs) self.players = None self.initialOutputs = self.outputs.copy() self.initialise() controls = FloatLayout(size_hint=(1, 0.2)) back = EmojiButton( text="◀", size_hint=(None, 0.8), ...
def create_attribution_masks(img, model, layers, class_index, max_mask_num, interp='bilinear'): ''' Derives feature maps from one, or a couple of layers, and post-processes them to convert them to attribution masks. inputs: img: a 4-D tensor image. model: the classification model ...
The function `SISE` generates saliency maps for a given image using a pre-trained model by creating attribution masks from specified layers, visualizing these masks, and fusing them via addition/multiplication or Otsu thresholding. It processes input images, applies gradient-based feature selection, and combines layer-...
def SISE(img, model, class_index, layers, grad_thr, interp='bilinear', fusion_type='otsu', T=100.): ''' For now, this function supports VGG16, ResNet50, and ResNet101. img: a 4-D image, or a 3-D array. model: the classification model layers: list of layers to be visualized either individu...
def preprocess(lang): normalizer = NORMALIZERS.get(lang) for key in range(32): path = INPUT_PATH.format(key=key, lang=lang, ver=WOC_VERSION) fh = gzip.open(path) logging.info("Processing %s", path) for line in fh: chunks = line.strip().split(';') commit_s...
The main task of the code is to process language-specific data to generate datasets for machine learning models, focusing on library adoption prediction. It collects statistics on project/developer namespace usage, filters out low-usage entities and bots, splits data into training/validation/test sets, and writes bench...
def main(lang, low_usage_threshold=100, test_val_share=0.1, benchmark_size=100000, bot_threshold=0.001, ns_whitelist_path='ns_whitelist', data_path='data', benchmark_path='benchmark_data', min_project_imports=2, max_project_imports=100): assert lang in utils.ECOSYSTEMS, "Invalid ...
def parse_bbox(bounding_box): ''' Parse bounding box arguments ''' if isinstance(bounding_box, str) and not os.path.isfile(bounding_box): try: bbox = [float(val) for val in bounding_box.split()] except ValueError: raise Exception( 'Cannot understan...
The main task of the code is to query GPS repositories for zenith tropospheric delay data based on input parameters like dates, bounding box, and station files. It processes date ranges, downloads tropospheric delays, merges station metadata, and extracts delay data for specified dates, saving results to an output dire...
def main(inps=None): """ Main workflow for querying supported GPS repositories for zenith delay information. """ try: dateList = inps.date_list returnTime = inps.time except: dateList = inps.dateList returnTime = inps.returnTime station_file = inps.st...
def check_health_combat(): if user.Player["hp"] > 0.7 * user.Player["hp_max"]: deco.clear_l(1) print(colors.green, "You feel fine.", colors.reset) deco.clear_l() elif user.Player["hp"] > 0.4 * user.Player["hp_max"]: deco.clear_l(1) print(colors.gold, "You don't feel that...
The code simulates a turn-based combat system where the player encounters an enemy at a given location. It manages combat loops, action choices (attack, check health, flee), processes damage calculations, tracks HP loss, logs events, and determines combat outcomes (win/loss) based on player and enemy HP thresholds.
def combat(current_location): enemy = enemies.encounter(current_location) fighting = True log = [] temp_log = [] total_hp_lost = 0 hp_lost = 0 deco.clear_l(1, "") while fighting: deco.clear_l() print(f'You spotted a {enemy["name"]} Level {enemy["lvl"]}') deco.cl...
def createSameSizeMatrix(matrix): rows = len(matrix) columns = len(matrix[0]) resultMatrix = [[] for row in range(rows)] for row in range(len(resultMatrix)): for column in range(columns): resultMatrix[row].append(0) return resultMatrix def getRows(matrix): rows = len(matrix) ...
The function computes the matrix of minors for a given input matrix. For a 2x2 matrix, it swaps diagonal elements to form minors. For a 3x3 matrix, it calculates each minor by taking the determinant of the corresponding 2x2 submatrix. The result is a new matrix where each element is the minor of the original matrix's e...
def minorsOfMatrix(matrix): resultMatrix = createSameSizeMatrix(matrix) #We create a new matrix so that we don't use the reference value of matrix size = getRows(matrix) if size == 2: resultMatrix[0][0] = matrix[1][1] resultMatrix[0][1] = matrix[0][1] resultMatrix[1][0] = matrix[1...
def getRows(matrix): rows = len(matrix) return rows def minorsOfMatrix(matrix): resultMatrix = createSameSizeMatrix(matrix) #We create a new matrix so that we don't use the reference value of matrix size = getRows(matrix) if size == 2: resultMatrix[0][0] = matrix[1][1] resultMatrix[...
The main task of the code is to compute the cofactor matrix of a given input matrix. It first calculates the minors of the matrix, then applies sign changes to specific elements based on the matrix's row count: for 2x2 matrices, it negates off-diagonal elements; for larger matrices, it adjusts selected positions using ...
def cofactorsOfMatrix(matrix): rows = getRows(matrix) resultMatrix = minorsOfMatrix(matrix) if rows == 2: resultMatrix[0][1] = -matrix[0][1] resultMatrix[1][0] = -matrix[1][0] else: resultMatrix = getAdjacent(resultMatrix) resultMatrix[0][1] *= -1 resultMatrix[1][...
def getDeterminant(matrix): rows = getRows(matrix) firstPart = 0 secondPart = 0 if(rows == 2): firstPart = matrix[0][0] * matrix[1][1] secondPart = matrix[0][1] * matrix[1][0] elif(rows == 3): extendedMatrix = extendMatrix(matrix) newSize = getColumns(extendedMa...
The code computes the inverse of a matrix by calculating its determinant, generating the cofactor matrix, and scaling it by the reciprocal of the determinant.
def inverseMatrix(matrix): determinant = getDeterminant(matrix) cofactors = cofactorsOfMatrix(matrix) inverse = multiplicationByScalar(1/determinant,cofactors) return inverse
def delete_vm(cloud_vm_id: str) -> dict: """Delete vm in openstack and local db :param cloud_vm_id: id vm from openstack :type cloud_vm_id: str :return: dict with code and message about succesfully result :rtype: dict """ from app import db, VMInstanse instanse = ( db.session.q...
The main task of the code is to create a standard or preemptible VM in OpenStack based on the `is_preemptible` flag, managing existing instances by deleting preemptible VMs when switching to standard and vice versa, while returning status codes and messages via a dictionary. It checks for existing VMs, handles deletion...
def create_vm(is_preemptible: bool = False) -> dict: """Create standart or preemptible vm in openstack :param is_preemptible: bool value, that describe vm preemptible or standart, defaults to False :type is_preemptible: bool, optional :return: dict with code and message about succesfully result ...
def forward_pass(self, inputs): ''' Computes a forward pass on the inputs and stores the node activations at each node ''' self.activations["acts0"] = inputs acts = inputs for i in range(self.no_hidden + 1): acts = np.matmul(acts, self.params["weights...
This code trains a neural network model using specified optimization algorithms (batch gradient descent, mini-batch SGD, momentum, or Adam) on given data, computes validation accuracy, and returns the accuracy along with average training loss. It processes data in batches for mini-batch methods, applies gradient update...
def train(self, data, labels, valid_data, valid_labels, optimizer, batch_size = 64): ''' Trains the model on the data for one epoch ''' if optimizer == "gd_batch": ''' Use batch gradient descent. Slow to train. ''' for i in range(data.shape...
def forward_pass(self, inputs): ''' Computes a forward pass on the inputs and stores the node activations at each node ''' self.activations["acts0"] = inputs acts = inputs for i in range(self.no_hidden + 1): acts = np.matmul(acts, self.params["weights...
The code computes numerical gradients for a neural network by perturbing weights and comparing loss changes, then compares these with analytically computed gradients. It iterates through each weight, applies a small perturbation, recalculates loss, and stores the gradient difference. Results are written to files for an...
def numerical_gradients(self, data, labels): perturbation = 0.0001 old_loss = 0.0 self.num_gradients = {} for i in range(data.shape[0]): inputs = data[i] outputs = self.forward_pass(inputs) probs = self.softmax() old_loss = old_loss + self....
def getLineupIds(boxscore): homeTeamBox = boxscore['home'] awayTeamBox = boxscore['away'] homePlayers = homeTeamBox['battingOrder'] try: homePlayers.append(homeTeamBox['pitchers'][0]) awayPlayers = awayTeamBox['battingOrder'] awayPlayers.append(awayTeamBox['pitchers'][0]) exc...
The main task of the code is to collect and store baseball game data (scores, lineups, player statistics) for 1800 days starting from March 2, 2010, by fetching schedules, retrieving game details, processing player data, and writing valid results to CSV files in a 'Data' directory. It handles HTTP errors, validates tea...
def main(): dataDir = os.path.join(os.getcwd(), 'Data') if not os.path.exists(dataDir): os.mkdir(dataDir) dataCollectionRunTimeStart = time.time() dayDelta = timedelta(days=1) day = date(year=2010, month=3, day=2) numDays = 1800 totalGames = 0 totalSuccessfulGames = 0 for _...
def isDifferentColor(RGB): mean_comp = (RGB[0]+RGB[1]+RGB[2])/2 mean_ref = (neutralColor[0]+neutralColor[1]+neutralColor[2])/2 diff = mean_comp - mean_ref return abs(diff) > 30 def traitementLigne(line): global rgb_im #RGB = rgb_im.getpixel((line,0)) RGB = copieImg[line][0] ...
The main task of the code is to segment an image by iterating through rows and columns to identify and process lines/columns where the color matches the first pixel of that row/column. It uses a copied image (`copieImg`) to avoid modifying the original, checks color consistency with `isDifferentColor()`, and applies `t...
def segmentation(): global rgb_im RGB = (0,0,0) for line in range(heightImg): #RGB = rgb_im.getpixel((line,0)) RGB = copieImg[line][0] if (not(isDifferentColor(RGB))): traitementLigne(line) for column in range(widthImg): #RGB = rgb_im.get...
def dtw_align(p1,p2,path=0,strat="cost"): if not path: if True: #pdb.set_trace() distance,path = fastdtw(p1.vel,p2.vel,dist=euclidean) #distance,path = dtw(p1.vel,p2.vel,dist=euclidean) #distance,path = fastdtw(p1.acc,p2.acc,dist=euclidean) else: ...
This class initializes an object to process either file-based or aligned sequence data, extracting features like velocity, acceleration, timestamps, and costs. It loads data from files, scales dimensions, computes derivatives, and handles hierarchical relationships. For file-based data, it parses timestamps and metadat...
def __init__(self,index,from_file = True, seq_file = 0, seq1 = 0, seq2 = 0, path = 0): self.index = index self.seq1 = seq1 self.seq2 = seq2 self.file_path = seq_file self.from_file = from_file if from_file: ## For now I don't need to store the seq self.file_na...
def run_exp(params,save_dfs = False): thresh_array = np.empty([params.n_birds,params.n_rounds]) for b in range(params.n_birds): start_noise = (np.random.random() - 0.5) * params.thresh_noise end_noise = (np.random.random() - 0.5) * params.thresh_noise thresh_min = max([0,params.thresh -...
The code simulates multiple iterations of an experiment to analyze how varying thresholds and potencies affect bird responses to songs. It computes interaction effects, divergence metrics, and correlations between models. For each iteration, it either runs a pre-defined experiment or generates synthetic data with noise...
def run_sim(params,debug=False): #all_threshs = np.zeros([params.iterations,params.n_birds,params.n_rounds,params.n_songs]).astype(bool) #all_pots = np.zeros_like(all_threshs) effect_array = np.empty([params.iterations,2]) interaction_array = np.empty([params.iterations,2]) divergence_array = np.em...
def get_local_objects(self) -> dict: str_source = self.sourceFolder.as_posix() source_files = {} for source_file in self.sourceFolder.rglob("*"): if source_file.is_dir(): continue str_source_file = source_file.as_posix() str_source_file = str_...
The code synchronizes local files with a cloud bucket by retrieving local and bucket objects, comparing them, and updating the bucket to match the local files. It prints both object lists for debugging before triggering the synchronization process.
def sync_folder(self): local_objects = self.get_local_objects() bucket_objects = self.get_bucket_objects() print(local_objects) print(bucket_objects) self.update_bucket_objects(local_objects, bucket_objects)
def readAllLines(file_path): with open(file_path, 'r') as f: return f.readlines() def attributesCorrect(students_attributes): correct_attributes = [] for attributes in students_attributes: if len(attributes) is not 5: continue if not isValidAttributes(attributes...
The function reads student data from an input file, sorts them by age, selects the k youngest students, writes their names to an output file, and returns the count of students processed (k) or -1 if k is invalid.
def printYoungestStudents(in_file_path: str, out_file_path: str, k: int) -> int: if not isinstance(k, int) or k < 1: return -1 lines = readAllLines(in_file_path) student_attributes = attributesCorrect(getAttributes(lines)) get_age = lambda student: int(student[2]) student_attri...
def isSemesterValid(semester): try: semester_num = int(semester) except Exception: return False return semester_num >= 1 def readAllLines(file_path): with open(file_path, 'r') as f: return f.readlines() def attributesCorrect(students_attributes): correct_attributes = [] ...
The function `correctAgeAvg` calculates the average age of students in a specified semester from a given file. It first validates the semester; if invalid, it returns -1. It reads the input file, processes student attributes, filters students belonging to the given semester, and computes their average age. If no studen...
def correctAgeAvg(in_file_path: str, semester: int) -> float: if not isSemesterValid(semester): return -1 lines = readAllLines(in_file_path) student_attributes = attributesCorrect(getAttributes(lines)) students_semester = list(filter(lambda student: int(student[4])==semester, student_attri...
def sigmoid(z): """ Sigmoid function""" return 1.0 / (1.0 + np.exp(-z)) def quadratic_cost_derivative(output, y, z, network): """for the cost function (1/2)*(a-y)^2 the derivative is a-y""" # Regularization Confidence Penalty if network.regularization == 'Confidence Penalty': network.con...
This function performs backpropagation for a single training example in a neural network. It first computes forward activations and z-values, then calculates gradients (nabla_b_single, nabla_w_single) using the chosen cost function (quadratic or cross-entropy). It applies the four backpropagation steps: computing outpu...
def back_prop_single(self, x, y): """ :returns the back propagation gradient of a SINGLE example""" # FEEDING FORWARD the network: nabla_b_single = [np.zeros(b.shape) for b in self.biases] # initializing the changes in b and w for single input nabla_w_single = ...
def solve_ns_explosion(rho, mu, L, dx, dt, Niter, icenter, jcenter, magx, magy, radius, tstart, tend, explosion_type): N = int(L/dx) u = np.zeros((N, N, Niter)) v = np.zeros((N, N, Niter)) f1 = np.zeros((N, N, Niter)) f2 = np.zeros((N, N, Niter)) # Initialize f1 and f2 for explosion f1, f...
The main task of the code is to parse input parameters for fluid dynamics simulations, select a solver based on the specified force type (constant, Gaussian, delta, or boundary), solve the Navier-Stokes equations, and save velocity field animations as GIFs. It handles fluid properties, grid settings, and iteration coun...
def main(): parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter) parser.add_argument("rho",type=float,help="density of fluid") parser.add_argument("mu",type=float,help="viscosity of fluid") parser.add_argument("dx",type=float, help="the grid size") parser.ad...
def initialize_files(num): filehelper.initialize_winners(num) def sample_population(size): population = [] initial_score=0 for gene in range(size): population.append((gene_generate(), initial_score)) return population def duels(population): duels = [population[i:i+2] for i in range(0, le...
The code implements a genetic algorithm (GA) to evolve a population of solutions over multiple generations. It initializes parameters (e.g., population size, mutation/crossover rates), iterates through generations, and for each, conducts duels to select winners. Within GA rounds, it evaluates population scores, applies...
def main(): #Hyper Parameters decided for our GA Algorithm generations = 10 GA_rounds = 800 winners_size = 5 pop_size = 1024 mutation_p = 0.02 crossover_p = 0.4 initialize_files(winners_size) for generation in range(generations): pop = sample_population(pop_size) ...
def getResponseJson(url): try: response = requests.get(url) if response.status_code != 200: print( 'HTTP Response: {0} when trying {1}' .format(response.status_code, url) ) exit() except ConnectionError: print("Could...
The code handles Codechef contest and problem data by determining if it's a practice problem or a specific contest. It fetches problem details via API, writes front matter, and generates solutions based on user input. For non-practice contests, it lists available problems and writes solutions for selected ones.
def main(): global contestCode, contestName if input('Is it a practice problem? (y/n) : ') == 'y': contestCode = 'PRACTICE' contestName = 'Practice' problemCode = input('Enter problem code : ') responseJson = getResponseJson( 'https://www.codechef.com/api/contests/PRA...
def create_rules(self): """ Method that creates rule objects from the Rule class """ # All possible signals all_signals = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '#'] # A1 for first iteration rule1 = Rules('S-init', all_signals, 'S-Read', self.agent.wake_up_sequ...
The main task of the code is to execute a Finite State Machine (FSM) by initializing rules, processing signals from a keypad, and transitioning states until a final state is reached. It creates rules, adds them to the FSM, and iteratively matches signals against rules to update the state. The loop continues until the F...
def main_loop(self): """Main sequence to run the FSM""" # Create all rule objects self.create_rules() print('Rules created') for rule in self.rules: self.add_rule(rule) led_board_obj = LEDBoard() keypad_obj = Keypad() self.current_state = ...
def init_gps(powerkey): print('turning on....') GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(power_key, GPIO.OUT) time.sleep(0.1) GPIO.output(power_key,GPIO.HIGH) time.sleep(2) GPIO.output(power_key, GPIO.LOW) time.sleep(20) ser.flushInput() def get_gps_position(): ...
The code defines a function `start()` that attempts to initialize a GPS module, retrieve its position, and power it down. If an error occurs, it ensures the serial connection is closed and the GPS is powered down safely.
def start(): try: init_gps(power_key) get_gps_position() power_down(power_key) except: if ser != None: ser.close() power_down(power_key)
def __random_district_label(self, graph): """ UTIL method for getting a random district from a graph of nodes """ return random.sample(graph, 1)[0] def __get_district_subgraph(self, g, district_label): """ Given a nx.graph and a district_label Return a...
This function performs redistricting recombination by merging two districts, generating a minimum spanning tree (MST) of the combined subgraph, and iteratively testing edge cuts to split the merged area into valid districts. It aims to create a new districting plan by randomly selecting districts, combining them, and f...
def recombination_of_districts(self, i): """ Given a graph Perform the recombination algorithm described in https://mggg.org/va-report.pdf ("Comparison of Districting Plans for the Virginia House of Delfates"; Metric Geometry and Gerrymandering Group; Section 2.3.2) ...
def initialize_grid(grid_height, grid_width): grid = np.zeros((grid_height, grid_width), dtype=int) return grid def populate_grid(grid, genomic_elements_lengths): height, width = grid.shape for element_type, lengths in genomic_elements_lengths.items(): for length in lengths: availabl...
This function runs a single genomic simulation by initializing a grid with specified element types, scaling it down, and logging interactions over rounds. It sets a random seed, generates the grid, processes element lengths, scales the grid, and executes the simulation, returning the simulation number, seed, and intera...
def single_simulation_run(simulation_number): seed = np.random.randint(0, 2**31 - 1) np.random.seed(seed) logging.info(f"Running simulation {simulation_number} with seed: {seed}") grid = initialize_grid(2, genome_size) element_types = { 1: exon_lengths, 2: retrotransposons_lengths, ...
def make_new_function(func_name, token_iter): param_list = get_param_list(func_name, token_iter) return_type = get_return_type(func_name, token_iter) return Function(func_name, param_list, return_type) def get_def_block(func_symbol, tokenized_arr): seen_definition = False in_block = [] function...
The code processes a stream of tokens to build a map of function declarations and definitions. It checks for redeclarations, validates function parameters (ensuring 'void' is exclusive and at least one parameter exists), verifies return types against function signatures, and ensures the existence of a properly defined ...
def make_function_map(token_iter, tokenized_arr): func_map = {} prev_tok_symbol = "" while True: try: token = token_iter.next() except StopIteration: break if token.label == Token_Label.Func_Id: if token.symbol not in func_map: # g...
def get_range_from_file(file_location): """Return range of digits from the given file location Parameters: file_location (str): file path location of file Returns: tuple (int, int): a tuple containing the min and max range numbers """ with open(file_location, "r") as input_file: ...
The main task of the code is to retrieve a numerical range from a file, generate passwords within that range, and compute grouped passwords. It prints the total number of passwords (Part 1) and the grouped passwords (Part 2), highlighting their counts and structure.
def main(): range_min, range_max = get_range_from_file(FILE_LOCATION) passwords = get_passwords_from_range(range_min, range_max) group_pass = get_double_grouped_passwords_from_range(range_min, range_max) print("TOTAL PASSWORDS (PART 1) : %d" % len(passwords)) print(group_pass) print("TOTAL P...
def restart(self): self.game_state = [[0 for j in range(self.game_height)] for i in range(self.game_width)] self.game_won = False self.current_row = None self.picked_column = None self.current_player = 1 self.rectangles = [] self.circles = [] self.create...
This function handles user or AI moves in a Connect4 game. It determines the selected column based on user input (x-coordinate), executes the move, checks for a win, and triggers a restart or winner screen. If AI is enabled, it predicts the next move using Connect4AI, executes it, and checks for a win. The function ens...
def handle_user_move(self, x): if self.game_won: self.restart() return for i in range(self.window.width): x_min = self.circle_diameter * i + self.circle_spacing * i + self.circle_spacing * 0.5 x_max = self.circle_diameter * i + self.circle_spacing * i + se...
def set_seed(seed): """ Set random seeds """ torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if use multi-GPU torch.backe...
The main task of the code is to train a CoHeat recommendation model using a specified dataset. It loads configuration settings, initializes the model and optimizer, trains the model over multiple epochs with loss tracking, and evaluates performance on validation/test sets. The best results are tracked and printed, focu...
def main(seed, data): set_seed(seed) conf = yaml.safe_load(open("config.yaml"))[data] conf['dataset'] = data dataset = Datasets(conf) conf['num_users'] = dataset.num_users conf['num_bundles'] = dataset.num_bundles conf['num_items'] = dataset.num_items device = torch.device('cuda' if torc...
def get_map(coords): # This function checks to see if the bot has been to this location # if it hasn't been it calls check and adds the current intersection to the map # Also generates a list of whether each path has been traveled in the order # North, West, South, East if coords in Map: ...
The function identifies unexplored paths from the current coordinates, prioritizes the first available unexplored direction, or selects the nearest unexplored path if none exist. It updates the robot's direction, marks the path as explored, and ensures map exploration progress by adjusting motor direction and logging t...
def choose_unexplored_direction(coords): #get potential paths temp = [] temp = get_map(coords) available_paths = temp[0] explored_paths = temp[1] # treat unavailable paths as explored for a in range(4): if available_paths[a] == False: explored_paths[a] = True ...
def get_map(coords): # This function checks to see if the bot has been to this location # if it hasn't been it calls check and adds the current intersection to the map # Also generates a list of whether each path has been traveled in the order # North, West, South, East explored_paths = [False, Fals...
This function identifies unexplored paths in a grid, prioritizes unexplored directions over explored ones, calculates the necessary rotation to align with the chosen direction, updates movement direction tracking, and marks the selected path as explored in the map. It ensures navigation through uncharted areas while ma...
def choose_unexplored_direction(coords): #get potential paths temp = [] temp = get_map(coords) print("here") available_paths = temp[0] explored_paths = temp[1] print(available_paths) print(explored_paths) # treat unavailable paths as explored for a in range(4): if avail...
def get_map(coords): # This function checks to see if the bot has been to this location # if it hasn't been it calls check and adds the current intersection to the map # Also generates a list of whether each path has been traveled in the order # North, West, South, East if coords in Map: ...
The main task of the code is to determine the next unexplored direction for navigation. It checks available and explored paths, treats unavailable paths as explored, identifies unexplored paths, and selects the first unexplored direction. If no unexplored paths exist, it chooses the closest unexplored node or a random ...
def choose_unexplored_direction(coords): #get potential paths temp = [] temp = get_map(coords) available_paths = temp[0] explored_paths = temp[1] # treat unavailable paths as explored for a in range(4): if available_paths[a] == False: explored_paths[a] = True ...
def drive(motors, sensors): #returns 0 at end #returns 1 at intersection #bot is centered on end criteria when block ends exit_condition = -1 edge = 'c' #Set edge for sensor updates l, r or c while(exit_condition == -1): #print("here") state = sensors.read() if state ==...
The code implements a robotic driving loop that navigates through an environment by selecting unexplored directions, updating coordinates, and managing state transitions. It handles different operational states: exploring (0), waiting (1), driving to a destination (2), stopping (3), and resetting (4). The loop continuo...
def driving_loop(): global driving_stopflag global next_location global driving_state driving_stopflag = False coords = (0, 0) while not driving_stopflag: drive(motors, sensors) if driving_state == 0: choose_unexplored_direction(coords) coords...
def mergesortX(Array): if len(Array) == 1: return Array mid_point = len(Array) // 2 left_part = Array[:mid_point] right_part = Array[mid_point:] left_sorted = mergesortX(left_part) right_sorted = mergesortX(right_part) i = j = 0 C = [] while i < len(left_sorted) and j < len...
The main task of the code is to find the closest pair of points in a set using a divide-and-conquer approach. It first sorts the points by x-coordinates (Px) and y-coordinates (Py), then applies the Closest_Pair function to determine the nearest pair and their Euclidean distance. The result is printed as the closest po...
def main(P): Px = mergesortX(P) Py = mergesortY(P) p, k = Closest_Pair(Px,Py) print("The pair of closest points are :",p) print("The distance between the points are :",k,"units")
def send_chat(self, chat_line, to_spectators = True): print(self.game_id, "Sending " + ("global" if to_spectators else "player") + " message:", chat_line) self.client.bots.post_message(self.game_id, chat_line) if to_spectators: self.client.bots.post_message(self.game_id, chat_line, spectator=True) def pick_str...
The code processes game state events by handling "gameFull", "gameState", and "chatLine" events. When "gameFull" is detected, it sends a farewell message, resets the game state, initiates strategy selection (if needed), and updates the state. "gameState" events trigger state change handling, while "chatLine" events are...
def run(self): for event in self.client.bots.stream_game_state(self.game_id): if event["type"] == "gameFull": self.send_chat("Thanks for playing!") self.current_game_state = None if self.strategy is None: self.strat_selector_thread = threading.Thread(target = self.strat_select_thread) self.st...
def check_keydown_events(event, spaceship, ss_settings, screen, sparks): """responds to key presses.""" if event.key == pygame.K_RIGHT: #case for when right key is pressed down spaceship.moving_right = True elif event.key == pygame.K_LEFT: #case for when left key is pressed down spaceship.m...
The main task of the code is to handle user input events in a game, processing keyboard presses/releases and mouse clicks to control the spaceship, manage game settings, and trigger actions like starting the game via a play button. It updates the game state based on these interactions, including quitting the game, firi...
def check_events(spaceship, ss_settings, screen, sparks, stats, play_button, aesteroids, sb): """respond to keypress and mouse events.""" for event in pygame.event.get(): #recieves the event occurred if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: #when a...
def check_fleet_edges(ss_settings, aesteroids): """respond appropriatley if any aesteroids have reached an edge""" for aesteroid in aesteroids.sprites(): if aesteroid.check_edges(): #if its true change_fleet_direction(ss_settings=ss_settings, aesteroids=aesteroids) break def spac...
This function updates asteroid positions by checking fleet edges and moving them. It detects collisions between asteroids and the spaceship, triggering a response if hit. It also checks if asteroids reach the screen bottom, updating game state accordingly.
def update_aesteroids(ss_settings ,aesteroids, spaceship, stats, sb, screen, sparks): """checks if the fleet is at either edge and then updates the position of all aesteroids in the fleet""" check_fleet_edges(ss_settings=ss_settings, aesteroids=aesteroids) aesteroids.update() #looks for aesteroid-s...
def extract_data(spark, log, config): """Load data from FlightRadar24 :param spark: Spark session object. :return: Spark DataFrame. """ # create API fr_api = FlightRadar24API() if "extract.frApi.login" in config and "extract.frApi.password" in config: log.info("logging into FlighRada...
(The main task of the code is to execute an ETL (Extract, Transform, Load) pipeline using Apache Spark. It initializes a Spark session with a specified configuration, logs the start of the ETL process, extracts data, transforms it, loads the results into a target system, logs completion, and terminates the Spark applic...
def main(): """Main ETL script definition. """ # start Spark application and get Spark session, logger and config spark, log, config = start_spark( app_name='FR24-App', files=['etl_config.json']) # log that main ETL job is starting log.warn('etl_job is up-and-running') # ex...
def hline(screen,size=10,y=0): hcenter(screen, "="*size, y=y) return y+1 def printColumns(screen, printvalues, size, y=0): """ Args: screen: screen, ref to screen obj headers: list of string headers to print to screen size: int, how large should the headers take up y: int...
The function `printHeaders` renders headers and associated content on a screen, drawing horizontal lines, printing column headers, and displaying current prices. It updates and returns the next safe y-coordinate for subsequent screen elements, ensuring proper vertical spacing and layout management.
def printHeaders(screen, headers, size, y=0): """ Args: screen: screen, ref to screen obj headers: list of string headers to print to screen size: int, how large should the headers take up y: int, first y coordinnate to start writing to Return: y: int, next safe y-coo...
def xor_(state1, state2): temp = [] for i in range(len(state1)): temp.append(state1[i] ^ state2[i]) return temp def f0(T0: list, rk: list): # (after key add) T = [(rk[i] ^ T0[i]) for i in range(4)] # hex (jika ingin lihat saja): # T_hex = [hex(i)[2:] for i in T] # sub-S0 untuk T...
The function performs a cryptographic transformation on a 4-element key through 12 rounds. In each round, it updates x1 and x3 using XOR operations with results from functions f0 and f1, which depend on current state variables and constant_value elements. After each round, the variables x0–x3 are rotated. The process s...
def gFn4_12(key, constant_value): x0 = key[0] x1 = key[1] x2 = key[2] x3 = key[3] for i in range(12): x1 = xor_(x1, (f0(x0, constant_value[2*i]))) x3 = xor_(x3, (f1(x2, constant_value[2*i+1]))) temp = x0 x0 = x1 x1 = x2 x2 = x3 x3 = temp ...
def xor_(state1, state2): temp = [] for i in range(len(state1)): temp.append(state1[i] ^ state2[i]) return temp def f0(T0: list, rk: list): # (after key add) T = [(rk[i] ^ T0[i]) for i in range(4)] # hex (jika ingin lihat saja): # T_hex = [hex(i)[2:] for i in T] # sub-S0 untuk T...
This function performs a cryptographic transformation over 18 rounds, applying XOR operations with substitution functions f0 and f1 on input variables, followed by a rotation of state variables. It uses round keys from rk and working keys from wk to iteratively transform the input state (x0-x3), returning the modified ...
def gFn4_18(inp, wk, rk): x0 = inp[0] x1 = xor_(inp[1], wk[0]) x2 = inp[2] x3 = xor_(inp[3], wk[1]) for i in range(18): x1 = xor_(x1, (f0(x0, rk[2*i]))) x3 = xor_(x3, (f1(x2, rk[2*i+1]))) temp = x0 x0 = x1 x1 = x2 x2 = x3 x3 = temp retur...
def xor_(state1, state2): temp = [] for i in range(len(state1)): temp.append(state1[i] ^ state2[i]) return temp def f0(T0: list, rk: list): # (after key add) T = [(rk[i] ^ T0[i]) for i in range(4)] # hex (jika ingin lihat saja): # T_hex = [hex(i)[2:] for i in T] # sub-S0 untuk T...
This function performs an inverse cryptographic transformation on input values using 18 rounds of XOR operations with round keys. It initializes variables from the input and a key array, then iteratively applies XORs with functions f0 and f1, swapping values in a specific order to produce transformed output. The proces...
def gFn4_inv_18(inp, wk, rk): x0 = inp[0] x1 = xor_(inp[1], wk[2]) x2 = inp[2] x3 = xor_(inp[3], wk[3]) for i in range(18): x1 = xor_(x1, (f0(x0, rk[2*(18-i)-2]))) x3 = xor_(x3, (f1(x2, rk[2*(18-i)-1]))) temp = x3 x3 = x2 x2 = x1 x1 = x0 x0 ...
def getOperandStructure(ins): # Gets the operand structure of the instruction tag = "" for o, opr in enumerate(ins.operandList): if opr.type in ("register", "tempreg", "stackPtr", "placeholder"): tag += "r" else: tag += "i" if tag == "r"*len(tag): return ins.opcode.name else: r...
This function translates complex or unsupported instructions in a program into lower-level equivalents using predefined patterns, handling multi-word operations, pointers, and temporary registers. It iteratively replaces instructions, adjusts labels/registers, and ensures compatibility with the target ISA, while managi...
def replaceComplex(program): # Replaces unsupported instructions with lower-level translations where possible # Uses tempregs where necessary global labelCount global MAXTEMPREG global DEPTH global POINTERS global WORDS global BITS global TEMPREGPTR global MWLABEL global MWFULL global MWFULL_fla...
def regSubstitution(program): # Replaces unsupported operand structures with register-only versions # Example: ADD $1, $2, 15 -> IMM $3, 15; ADD $1, $2, $3 global MAXREG global MAXTEMPREG global TEMPREGPTR global MWLABEL global WORDS global FINALSUB exempt = ("IMM", "header", "pragma", "IN", "MULT...
The code translates multi-word (MW) instructions in a program into equivalent sequences of single-word instructions, handling operand registers, control flow, and temporary register allocation. It modifies opcodes like `MW_ADD`, `MW_MOV`, etc., by expanding them into detailed operations for each word, managing temporar...
def fullMultiword(program): global WORDS global MAXREG global TEMPREGPTR global MWADDR global MWLABEL global FINALSUB global PROGBITS global MWFULL global MWFULL_flag MWFULL_flag = False flg = False program = regSubstitution(program) for x, ins in enumerate(program): if ins.opcode.name[0] ...
def sendMessage(self, msg, players): """Sends messege to players :param msg: Message to be sent :type msg: String :param players: A list of players :type players: [Player] """ #All communication begins with "MSG" or "FIN" and ends with "|", #So the player...
The code's main task is to initialize and manage a tournament by sending start messages to participants (either "1v1 game" or "round-robin tournament" based on player count), pairing players, initiating matches, running the game loop, and concluding the tournament. It coordinates game setup and execution based on prede...
def start(self): """Starts the tournament """ if (self.maxPlayers == 2 and self.minPlayers == 2): #send to all "1v1 game is starting." msg = "1v1 game is starting" self.sendMessage(msg, self.clients.values()) else: #send to all "Round robin...
def diff1(x): return (cal_psi_t1(x + del_x) - cal_psi_t1(x))/del_x def cal_psi_t1(x): psi_t = A1 + x*neuron1(x) return psi_t def cal_psi_t2(x): psi_t = A2 + x*neuron2(x) return psi_t
The code defines a function `LHS1(x)` that computes a value by subtracting the square of `cal_psi_t1(x)` and `cal_psi_t2(x)` from the result of `diff1(x)`, then returns the computed value as `lhs`
def LHS1(x): lhs = diff1(x) - cal_psi_t1(x)*cal_psi_t1(x) - cal_psi_t2(x) return lhs
def diff2(x): return (cal_psi_t2(x + del_x) - cal_psi_t2(x))/del_x def cal_psi_t1(x): psi_t = A1 + x*neuron1(x) return psi_t def cal_psi_t2(x): psi_t = A2 + x*neuron2(x) return psi_t
The code defines a function `LHS2` that computes a value `lhs` by subtracting the product of two functions `cal_psi_t1(x)` and `cal_psi_t2(x)` from the result of `diff2(x)`. It then returns this computed value. The primary task is to calculate and return the difference between `diff2(x)` and the product of the two psi ...
def LHS2(x): lhs = diff2(x) - cal_psi_t1(x)*cal_psi_t2(x) return lhs
def LHS1(x): lhs = diff1(x) - cal_psi_t1(x)*cal_psi_t1(x) - cal_psi_t2(x) return lhs def LHS2(x): lhs = diff2(x) - cal_psi_t1(x)*cal_psi_t2(x) return lhs def RHS1(x): rhs = np.cos(x)-(1 + x*x + np.power(np.sin(x), 2)) return rhs def RHS2(x): rhs = 2*x - (1 + x*x)*np.sin(x) return rhs
The function computes the sum of absolute values of squared differences between two neural network outputs (LHS1, LHS2) and their corresponding RHS functions over 10 random samples, returning this sum as a loss measure.
def RMSLoss(): summ = [] for j in range(10): x = np.random.uniform() del_NN1 = LHS1(x) del_NN2 = LHS2(x) summ.append((del_NN1 - RHS1(x))**2 + (del_NN2 - RHS2(x))**2) return tf.reduce_sum(tf.abs(summ))
def _handle_index_and_time(self, index, time_in_seconds): if index is None and time_in_seconds is None: index = 0 if index is None: index = self.get_index_after_time(time_in_seconds) return index, time_in_seconds def get_image(self, index = None, time_in_seconds = None): ...
The main task of the code is to resample an image at a specified index or time by scaling it according to the voxel size in x, y, and z dimensions, using linear or nearest-neighbor interpolation, and returning the resampled image.
def get_resampled_image(self, index = None, time_in_seconds = None, resampled_image : cle.Image = None, linear_interpolation : bool = True): index, time_in_seconds = self._handle_index_and_time(index, time_in_seconds) input_image = cle.push(self.get_image(index)) voxel_size = self.get_voxel_siz...
def expectedImprovement(model, X, maxObserved, jitter=0.01): """ Compute expected improvement. EI attempts to balance exploration and exploitation by accounting for the amount of improvement over the best observed value. Parameters ----------------------------------------------------------...
The function `computeNextGradient` selects the next gradient to evaluate using a specified acquisition function (e.g., Expected Improvement, UCB, random). It determines an index via the chosen method and returns the corresponding gradient from `self.gridX`. The acquisition function guides the trade-off between explorat...
def computeNextGradient(self, acqFunc="ei"): """ Function to calculate the next gradient to run using an acquisition function. Parameters ---------------------------------------------------------- acqFunc: str Acquisition functions in lower case. ...
def create_connection(self): try: super_connection = mysql_conn.connect( host=os.getenv('ADMIN_MYSQL_HOST'), user=os.getenv('ADMIN_MYSQL_USER'), password=os.getenv('ADMIN_MYSQL_PASSWORD'), port=os.getenv('ADMIN_MYSQL_PORT', '') ...
This function resets a specified database by dropping it and recreating it, ensuring the user has necessary permissions. It establishes a connection, verifies user rights, executes the DROP DATABASE command, then recreates the database. If any step fails (e.g., invalid connection, permissions, or creation errors), it r...
def reset_database(self, db_name=None, user=None, password=None): try: connection = self.create_connection() user_rights = self.check_user_db_rights( db_name=db_name, user=user, password=password) if not connection or not user_rights: return F...
def create_connection(self): try: super_connection = psycopg2.connect( host=os.getenv('ADMIN_PSQL_HOST'), user=os.getenv('ADMIN_PSQL_USER'), password=os.getenv('ADMIN_PSQL_PASSWORD'), port=os.getenv('ADMIN_PSQL_PORT', '') ) ...
The main task of the code is to reset a database by dropping it and recreating it, ensuring the user has the necessary permissions. It establishes a connection, verifies user rights, executes the DROP DATABASE command, and recreates the database. If any step fails, it returns False; otherwise, it returns True after clo...
def reset_database(self, db_name=None, user=None, password=None): try: connection = self.create_connection() user_rights = self.check_user_db_rights( db_name=db_name, user=user, password=password) if not connection or not user_rights: return F...
def get_tagged_entities(entities): """ Args: entities (Dict[str,List[Entity]]): Returns: Dict[str,List[Entity]] """ return {src: drop_other_entities(entities) for src, entities in entities.items()} def calc_results(gold_entities, guess_entities, surface_form=False): ...
The main task of the code is to generate evaluation metrics (precision, recall, F1) for token and entity-level predictions, comparing gold-standard annotations with system outputs. It calculates overall and per-tag statistics, outputs accuracy, and formats results in a near-W-NUT style, including counts of phrases, cor...
def fmt_results(tokens, all_entities, surface_form=False): """ Args: tokens (Dict[str,List[Tokens]): a dictionary of gold and guess tokens all_entities (Dict[str,List[Entity]): a dictionary of gold and guess entities surface_form (bool): whether or not to calculate f1-scores on the entit...
def doc_to_toks(lines): """ Args: lines (Iterator[str]): the lines in a document Returns: Dictionary[str,List[Tokens]]: a lists of all tokens in the document, stored in a dict with keys for gold and guess """ return {src: flatten(nested) for src, nested in doc_to...
The main task of the code is to evaluate entity recognition performance by calculating F1-scores for both entity mentions and their surface forms. It processes input text into tokens and entities, then reports two sets of F1-scores: one using entity mentions and another using surface forms, highlighting precision, reca...
def main(): # get tokens and entities lines = [line for line in fileinput.input()] tokens = doc_to_toks(lines) entities = doc_to_entities(lines) # report results print("### ENTITY F1-SCORES ###") for line in fmt_results(tokens, entities, surface_form=False): print(line) print() ...
def read_CLI_input( sequence_1: Path, sequence_2: Path, configuration: Path, output: Optional[Path] ): """Helper function for reading input""" seq1: SeqIO.SeqRecord = next(SeqIO.parse(sequence_1,'fasta')) seq2: SeqIO.SeqRecord = next(SeqIO.parse(sequence_2,'fasta')) conf = read_configuration_fil...
This function computes the optimal cost of globally aligning two DNA sequences using dynamic programming with linear space complexity. It converts sequences to integer representations, constructs a matrix for alignment scoring, and outputs the minimum alignment cost at the matrix's end. The method balances quadratic ti...
def global_linear_linspace( sequence_1: Path, sequence_2: Path, configuration: Path, output: Optional[Path] = typer.Option(None, "--outfile", "-o") ): """ This program finds the cost of a global alignment quadratic time and linear space. """ seq1, seq2, conf, f = read_CLI_input(sequenc...
def read_CLI_input( sequence_1: Path, sequence_2: Path, configuration: Path, output: Optional[Path] ): """Helper function for reading input""" seq1: SeqIO.SeqRecord = next(SeqIO.parse(sequence_1,'fasta')) seq2: SeqIO.SeqRecord = next(SeqIO.parse(sequence_2,'fasta')) conf = read_configuration_fil...
This function computes the optimal cost of a global alignment between two DNA sequences using dynamic programming in quadratic time and space. It optionally outputs the aligned sequences if specified. The input sequences are converted to integer representations, a cost matrix is generated, and backtracking reconstructs...
def global_linear( sequence_1: Path, sequence_2: Path, configuration: Path, print_alignment: bool = typer.Option(False, "--print-alignment"), output: Optional[Path] = typer.Option(None, "--outfile", "-o") ): """ This program finds the cost of a global alignment and, optionally, the alig...
def read_CLI_input( sequence_1: Path, sequence_2: Path, configuration: Path, output: Optional[Path] ): """Helper function for reading input""" seq1: SeqIO.SeqRecord = next(SeqIO.parse(sequence_1,'fasta')) seq2: SeqIO.SeqRecord = next(SeqIO.parse(sequence_2,'fasta')) conf = read_configuration_fil...
This function computes the optimal cost of a global alignment between two DNA sequences using affine gap costs, employing dynamic programming with quadratic time and space complexity. If enabled, it also reconstructs and outputs the aligned sequences in FASTA format. The process involves converting sequences to integer...
def global_affine( sequence_1: Path, sequence_2: Path, configuration: Path, print_alignment: bool = typer.Option(False, "--print-alignment"), output: Optional[Path] = typer.Option(None, "--outfile", "-o") ): """ This program finds the cost of a global alignment and, optionally, the alig...
def gini(self, rows): counts = self.class_counts(rows) impurity = 1 for label in counts: probab_of_label = counts[label] / float(len(rows)) impurity -= probab_of_label**2 return impurity def partition(self, rows, qsn): true_rows, false_rows = [], [] ...
The function `best_split` identifies the optimal feature and value to split a dataset, maximizing information gain. It calculates the Gini impurity of the current dataset, iterates through each feature, and evaluates potential splits by partitioning data into subsets. For each valid split, it computes the information g...
def best_split(self,rows): best_gain = 0 best_question = None current_uncertainty = self.gini(rows) n_features = len(rows[0]) - 1 for col in range(n_features): values = set([row[col] for row in rows]) for val in values: question = Questio...
def best_split(self,rows): best_gain = 0 best_question = None current_uncertainty = self.gini(rows) n_features = len(rows[0]) - 1 for col in range(n_features): values = set([row[col] for row in rows]) for val in values: question = Questio...
This function recursively builds a decision tree by selecting the best split, partitioning data into true/false subsets, and creating nodes or leaf nodes based on stopping conditions like zero information gain or maximum depth.
def build_tree(self, data, level): gain, question = self.best_split(data) if (gain == 0 or level>self.max_depth): return Leaf(data) true_rows, false_rows = self.partition(data, question) true_branch = self.build_tree(true_rows, level+1) false_branch = self.build_tree(...
def onSettingsChanged(self): kodiLog('Enter fd628Addon.onSettingsChanged') self._settings.readValues() if (self._rlock.acquire()): self.__createStates() self._fd628.enableDisplay(self._settings.isDisplayOn()) if (self._settings.isDisplayOn()): self._fd628.setBrightness(self._settings.getBrightness())...
The code runs a loop that monitors for abort requests, checks the existence of specific files, initializes settings on first iteration, updates indicators periodically, and performs cleanup after exiting the loop.
def run(self): firstLoop = True while not self._monitor.abortRequested(): if self._monitor.waitForAbort(0.5): break if (not os.path.isfile(self._vfdon) or not os.path.isfile(self._vfdoff)): firstLoop = True continue if (firstLoop): self.onSettingsChanged() firstLoop = False self.__up...
def connect_to_cloudservers(region=None): """Creates a client for working with cloud servers.""" region = safe_region(region) mgt_url = _get_service_endpoint("compute", region) cloudservers = _cs_client.Client(identity.username, identity.api_key, project_id=identity.tenant_name, auth_url=ide...
The main task of the code is to establish authenticated connections to multiple cloud APIs by assigning global variables to each service's connection. It initializes connections for cloud servers, storage, databases, load balancers, DNS, and block storage using dedicated functions, enabling subsequent interactions with...
def connect_to_services(): """Establishes authenticated connections to the various cloud APIs.""" global cloudservers, cloudfiles, cloud_loadbalancers, cloud_databases global cloud_blockstorage, cloud_dns cloudservers = connect_to_cloudservers() cloudfiles = connect_to_cloudfiles() cloud_loadbal...
def load_image_group(self, group): return [self.load_image(image_index) for image_index in group] def load_annotations_group(self, group): return [self.load_annotations(image_index) for image_index in group] def filter_annotations(self, image_group, annotations_group, group): # test all annotati...
The main task of the code is to prepare input-output pairs for a neural network by loading images and annotations, filtering invalid annotations, preprocessing data, and computing network inputs and targets from the processed image and annotation groups.
def compute_input_output(self, group): # load images and annotations image_group = self.load_image_group(group) annotations_group = self.load_annotations_group(group) # check validity of annotations image_group, annotations_group = self.filter_annotations(image_group, anno...
def random_board(n): return [random.randint(0, n - 1) for _ in range(n)] def print_board(board): """ Display the board in a readable format. """ n = len(board) for row in range(n): line = "" for col in range(n): if board[col] == row: line += " Q " ...
The code conducts a single-instance experiment comparing Steepest-Ascent Hill Climbing and Genetic Algorithms (GA) for solving the N-Queens problem. It initializes a random board, runs both algorithms, records their time and search cost, prints final board states, and checks if GA achieves a solution (heuristic=0). The...
def run_single_instance_experiment(n, pop_size, generations): initial_board = random_board(n) print("Initial Board:") print_board(initial_board) # Steepest-Ascent Hill Climbing start_time = time.time() final_board_hc, search_cost_hc = steepest_ascent_hill_climbing(initial_board) hc_time = t...
def random_board(n): return [random.randint(0, n - 1) for _ in range(n)] def steepest_ascent_hill_climbing(board): current_board = board search_cost = 0 while True: current_heuristic = compute_heuristic(current_board) neighbors = get_neighbors(current_board) search_cost += len(ne...
The code runs multiple experiments comparing Hill Climbing and Genetic Algorithm (GA) on N-Queens problems. It measures success rates, average search costs, and average time for each algorithm across `num_instances` trials. Results are returned as statistics, highlighting performance differences between the two methods...
def run_experiments(n, num_instances, pop_size, generations): hill_climbing_success = 0 ga_success = 0 hc_search_costs = 0 ga_search_costs = 0 hc_time = 0 ga_time = 0 for _ in range(num_instances): initial_board = random_board(n) # Hill Climbing start_time = time.ti...
def print_board(): # Print the column labels print(" ", end=" ") for col in cols: print(col, end=" ") print() for i in range(BOARD_SIZE): print(rows[i], end=" ") for j in range(BOARD_SIZE): print(board[i][j], end=" ") print() def is_full(): # Loop ...
The code implements a 4-in-a-line game where a human player (O) and computer (X) take turns on an 8x8 board. It handles user input, alternates turns, updates the board, checks for wins/draws, and declares the result. The game starts with a welcome message, allows the user to choose first move, and ends with a win/draw ...
def play(): # Print a welcome message print("Welcome to the 4-in-a-line game!") print("You are O and I am X.") print("The board is 8x8 and the first player to get 4 in a line wins.") print("You can enter your move in the format of row and column, such as A1.") print("Here is the initial board:")...
def actualizarInventarios(inventarios): global output for cuenta, info in usuarios_ml.items(): print("Actualizando Mercado Libre %s..." % cuenta) output = output + ("Mercado Libre %s\n" % cuenta) headers_authorized = headers_authorizedML(info["at_line"]) all_ids = obtenerProducto...
The main task of the code is to safely update inventories using data from leerAdminbox(), send an email with output, and handle exceptions by notifying via email if the update fails, while printing any secondary errors during the email notification process.
def safeMain(): try: actualizarInventarios(leerAdminbox()) sendemail(output) except Exception as e: try: sendemail("Hubo un error actualizando los inventarios\n%s" % e) except Exception as e2: print(e2)
def drive(self, way): if way == 1: if self.speed < self.max_speed / 3: self.speed = min(self.speed + self.acceleration, self.max_speed) elif self.speed < self.max_speed / 2: self.speed = min(self.speed + self.acceleration / 5, self.max_speed) e...
The code processes movement commands by checking each element of the 'move' list. If elements 0-3 are not 'False', it triggers driving or rotating actions. If none are active, it calls 'reduce()'. The commented section suggests a potential return value based on move[4], but it's not executed.
def onServer(self, move): moved = False if move[0] != 'False': moved = True self.drive(1) if move[1] != 'False': moved = True self.drive(0) if move[2] != 'False': self.rotate(1) if move[3] != 'False': sel...
def new_object(name): try: objs = bpy.data.objects objs.remove(objs[name], do_unlink=True) except: pass try: mesh = bpy.data.meshes[name+"_mesh"] mesh.user_clear() bpy.data.meshes.remove(mesh) except: pass new_mesh = bpy.data.meshes.new("{}_mes...
This function builds a 3D model from lattice data by creating a base mesh with vertices, edges, and error markers, then generating xSyndrome and zSyndrome objects with distinct materials. It joins these components into a single object, hides non-empty models, and manages selection states for Blender operations.
def build_model(step, lattice_data, lattice, i): model_name = "{}_{}".format(step,lattice) model = new_object(model_name) mesh = model.data bm = bmesh.new() add_materials(mesh) mat_dict = {mat.name: i for i, mat in enumerate(mesh.materials)} bm.from_mesh(mesh) build_vertices...
def cleanCellOutput(values): data = [] for i in range(0,len(values)-1): if('AT#' in str(values[i])): del values[i] break for i in range(0,len(values)-1): if('Network' in str(values[i])): del values[i] break for i in values: a = i.sp...
The function `getCells` sends a command via a serial port, reads responses, processes LTE data, and writes it to a database (with optional GPS integration) based on configuration flags. It handles error conditions, cleans data, and uses separate SQL writing functions depending on whether GPS data is included.
def getCells(cmd,ser,timeout,cursor,conn): if(ser.is_open): #print(LogHed_LTE,"is_open") ser.timeout = timeout ser.reset_input_buffer() ser.reset_output_buffer() sleep(0.5) output = cmd + '\r' ser.write(output.encode()) sleep(.25) #print(LogHed...
def setupMySql(cursor,conn): logger.debug('setupMySql') try: #logger.debug(cursor,conn) createTable = """CREATE TABLE IF NOT EXISTS cells( earfcn int, rxLev int, mcc int, mnc int, ...
The main task of the code is to continuously retrieve LTE cell data via a serial connection (ser2), store it in a MySQL database using provided cursor and connection objects, and handle potential errors. It initializes database settings, validates formats, and loops indefinitely to fetch cell information every second, ...
def main(cursor,conn,ser2): try: logger.debug("LTE_MAIN!") setupMySql(cursor,conn) checkFormat(ser2) #getGPSvalues(cursor,conn) #checkGPSLock(cursor,conn) #exit() while True: #logger.debug("whileTrue") getCells("AT#CSURVC",ser2,5,curs...
def GetValue(Value, Size, ItemNumber): if(Value == 0): Bin, ListOfItems = DefinedScenario(Size, ItemNumber) else: Bin, ListOfItems = Scenario(Value) shuffle(ListOfItems) for i in range(len(ListOfItems)): ListOfItems[i].ItemNumber = i + 11 return Bin, ListOfItems def Describ...
This function processes items into bins by attempting to place each item in a bin, creating new bins when necessary. It initializes bins, iterates through items, checks placement validity, and logs progress. The core task is bin packing: efficiently assigning items to bins while managing bin creation and item placement...
def DoScenario(Value, Size=10, ItemNumber=30): Bin, ListOfItems = GetValue(Value, Size, ItemNumber) DescribeListOfItems(ListOfItems) ListOfBins = [] ListOfBins.append(deepcopy(Bin)) BinCounter = 0 CurrentBin = ListOfBins[BinCounter] CurrentBin.BinNumber = BinCounter + 1 i = 0 whil...
def paginator(self, limit, action_result): if not self._create_client(action_result): return action_result.get_status() dic_map = { 'list_rules': ['list_rules', 'Rules'], 'list_ip_sets': ['list_ip_sets', 'IPSets'], 'list_acls': ['list_web_acls', 'WebACLs...
The function `_handle_add_ip` adds an IP address to an AWS WAF IP set. It validates parameters, creates a new IP set if necessary, checks the IP format, and updates the set. It returns success/failure status and logs results. If inputs are insufficient or invalid, it raises errors. The process includes Boto3 API calls ...
def _handle_add_ip(self, param): self.save_progress("In action handler for: {0}".format(self.get_action_identifier())) # Add an action result object to self (BaseConnector) to represent the action for this param action_result = self.add_action_result(ActionResult(dict(param))) ip_set_...
def paginator(self, limit, action_result): if not self._create_client(action_result): return action_result.get_status() dic_map = { 'list_rules': ['list_rules', 'Rules'], 'list_ip_sets': ['list_ip_sets', 'IPSets'], 'list_acls': ['list_web_acls', 'WebACLs...
This function deletes an IP address from an AWS WAF IP set by validating parameters, verifying the IP set's existence, checking the IP format, and executing the deletion. It returns success or failure status based on validation and operation outcomes, updating the summary accordingly.
def _handle_delete_ip(self, param): self.save_progress("In action handler for: {0}".format(self.get_action_identifier())) # Add an action result object to self (BaseConnector) to represent the action for this param action_result = self.add_action_result(ActionResult(dict(param))) ip_s...
def log(self, message): print(message) pass def get_metrics(self, metrics, datafields = None): for metric in metrics: self.df_list.append(self.get_metric_df(metric, datafields)) def join_exported_metrics(self): self.out_df = self.df_list[0] for i in range(1, len(self...
The code's main task is to fetch and transform metrics data, join all exported metrics, and save the resulting DataFrame to a specified file. It logs progress at each step, ensuring data is processed and exported systematically.
def qc_standard(self, filename): self.log("Fetching and transforming data") self.get_metrics(self.request_params.keys()) self.log("Joning all metrics together") self.join_exported_metrics() self.export_df(self.out_df.copy(), filename=filename)
def get_required_pd_files_list(start, end): start = pd.to_datetime(start) end = pd.to_datetime(end) all_links_df = pd.DataFrame(columns = ['url','source']) if start < get_earliest_current_pd_date(): years_and_dates = pd.DataFrame({'dates':pd.date_range(start,end, freq = '1d')}) years_and...
The code fetches and processes NEMWEB predispatch price data for a specified date range, combining archive and current files. It filters data by date, concatenates results, removes duplicates, sorts by datetime and region, and returns a cleaned DataFrame with forecasted 30-minute prices.
def get_predispatch_price_NEMWEB(start = datetime.date.today(), end = datetime.date.today() + datetime.timedelta(days=1)): pd_data = None start = pd.to_datetime(start) end = pd.to_datetime(end) #TODO FIND ACTUAL START LIMIT assert start >= pd.to_datetime('1...
def print_message(m): num_stars = 10 if verbose: print("*" * num_stars + m + "*" * num_stars) def initialize(): """ :return (dictionary data - any format that you wish, which can be reused in get_features below) """ data = {} return data def train(filename, data): """...
The code's main task is to train and test a logistic regression model for a MEMM tagger. It checks if the first command-line argument is "-t", then initializes data, trains the model using the specified training file, and tests it with the provided test file. If arguments are incorrect, it displays usage instructions. ...
def main(): if sys.argv[1] == "-t": print_message("Initialize Data") data = initialize() print_message("Train Model") log_reg = train(sys.argv[2], data) print_message("Test Model") test(sys.argv[3], log_reg, data) print() else: print("Usage: python...
def openWindow(self): w = FloatingWindow((200, 242), title = "Backdrop", closable = False) w.glyphList = List((10, 10, -10, 160), [{"Visibility": False, "Status": None, "Name": "None", "Position": 0, "layer": None}], columnDescriptions = [{"title": "Visibility", "cell": CheckBoxListCell(), "width": 30}, {"title": "...
The main task of the code is to handle background layer updates in a UI context. It checks tool status, updates the current glyph if it differs from the input layer, updates the UI accordingly, and handles exceptions by resetting the glyph. Finally, it triggers a drawing operation for "friends" based on the layer.
def background(self, layer): if not self.toolStatus: self.openWindow() try: if self.currentGlyph is not layer: self.currentGlyph = layer self.updateWindowUI() except: self.currentGlyph = None self.updateWindowUI() self.drawFriends(layer)
def read_src_file(self, sheet_name: str, header: List or None = None, index_col: List or None = None): if index_col is None: index_col = [] if header is None: header = [] _df = pd.read_excel( io=self.src_file, sheet_name=sheet_name, he...
The code processes multiple sheets by reading dataframes, adjusting indices, splitting large dataframes into smaller subsets, and writing each subset to files.
def run(self): for sheet_row in self.sheet_details: _df_mega = self.read_src_file( sheet_name=sheet_row["sheet_name"], header=sheet_row["header"], index_col=sheet_row["index_col"] ) _df_mega = self.process_index(index_name=shee...
def _init_global(self, loader): # adjust scales real = loader.dataset.image.clone().to(self.args.device) self._adjust_scales(real) # set reals real = imresize(real, self.args.scale_one) loader.dataset.reals = self._set_reals(real) # set noises loader.dat...
The code performs model evaluation by initializing data loaders, setting up evaluation components, iterating through specified steps to sample and process data, and closing TensorBoard if enabled.
def eval(self): # get loader loader = get_loader(self.args) # init self._init_global(loader) loader = self._init_eval(loader) # evaluate logging.info('Evaluating...') for self.step in range(self.args.num_steps): self._sample_iteration(loader)...
def _train_iteration(self, loader): # set inputs data = next(iter(loader)) noises = data['noises'] reals = data['reals'] amps = data['amps'] # critic iteration fakes = self._critic_wgan_iteration(reals, amps) # only update generator every |critic...
This function trains a model at a specific scale by iterating through training steps, updating learning rates via schedulers, and periodically evaluating performance. It alternates between training and evaluation modes, and finally generates samples after completing all steps.
def _train_single_scale(self, loader): # run step iterations logging.info('\nScale #{}'.format(self.scale + 1)) for self.step in range(self.args.num_steps + 1): # train self._train_iteration(loader) # scheduler self.g_scheduler.step(epoch=self.ste...
def _init_global(self, loader): # adjust scales real = loader.dataset.image.clone().to(self.args.device) self._adjust_scales(real) # set reals real = imresize(real, self.args.scale_one) loader.dataset.reals = self._set_reals(real) # set noises loader.dat...
The main task of the code is to train a multi-scale model by iterating through different scales, initializing global/local parameters, training each scale, saving models at each stage, and finalizing with statistics and TensorBoard closure. It loads data, manages model states, and handles training processes across scal...
def train(self): # get loader loader = get_loader(self.args) # initialize global self._init_global(loader) # iterate scales for self.scale in range(self.args.stop_scale + 1): # initialize local self._init_local(loader) self._t...
def recieve_album_request(): usage_msg = """ Hi there! This program is designed to download full albums from youtube! Enter the name of the artist and the album. When finished - press enter! """ print(usage_msg) albums = [] album_title = input("Album Title:(Ente...
The main task of the code is to download songs based on user-specified album and artist requests, save them to the user's Music directory, and add metadata (title, album, artist, track number) to each MP3 file. It retrieves album-song mappings, iterates through them, downloads songs with error handling, and applies met...
def main(): albums = recieve_album_request() output_dir = expanduser("~\\Music") for album_title, artist in albums: songs_dict = find_album_songs(album_title, artist) if songs_dict is None: continue print("songs dict: {}\n".format(songs_dict)) for i, song_title ...
def generate_new_request_event(self): event_time = self.clock + self.get_interarrival() self.num_of_request += 1 new_request = Request(self.num_of_request, FileStore.get_file(), self.clock) new_request_event = Event("new_request", self.clock, event_time, new_request) self.add_new...
This code simulates a system processing events (e.g., requests, queue operations) over time, tracking metrics like average request time and cache miss rate. It processes events from a queue, updates the simulation clock, handles event types (new requests, queue arrivals, departures, file receipt), and prints performanc...
def run(self): print('start') self.generate_new_request_event() while self.queue.qsize() > 0 and self.clock < self.time_limit: event: Event = self.queue.get()[1] self.clock = event.get_event_time() event_type = event.get_type() if(self.clock % 1 ==...
def motif_finding(dataset_path): ''' This function takes the dataset_path, extracts the sequences and motiflength and runs the gibbs sampling ''' sequences = [] ml = 0 with open(dataset_path +'/sequences.fa') as fp: lines = fp.readlines() for line in lines: if('>' not in line): sequ...
(The function `thread_process` executes the Gibbs sampling algorithm 200 times on a dataset to identify optimal motif predictions. It tracks the highest scoring result (based on information content per column) and stores the corresponding PWM, predicted sites, and average runtime. After iterations, it saves the best ou...
def thread_process(dataset_path): ''' This function is run in a thread. It runs gibbs sampling algorithm 200 times on a given dataset and stores the best results ''' best_score, best_run_time, best_predicted_pwm, best_predicted_sites = 0, 0, None, [] avg_runtime = 0.0 for i in range(200): run_time, p...
def msgProtocol(packet, serverAddress): packet = packet.decode() # get <T>type</T> msgType = packet[packet.find("<T>")+3:packet.find("</T>")] # get <ID>clientName</ID> from packet recieved clientName = packet[packet.find('<ID>')+4:packet.find('</ID>')] # get [hashKey] from packet ...
The function `receiveMessage` continuously receives UDP messages, processes them using a protocol, and handles actions like resending lost messages, pushing terminal updates for "leave" or "msg" types, and shutting down the client if the server goes down. It uses global server info and a client socket for communication...
def recieveMessage(): global serverInfo while True: recievedMessage, serverAddress = clientSocket.recvfrom(2048) msgRcv = msgProtocol(recievedMessage, serverAddress) if msgRcv[0] == "ack": if msgRcv[2] == "msgLost": sen...
def run_episode(self,epsilon, evaluate=False): rewards = [] states = [] actions = [] done = False state = self.env.reset() states.append(state) while not done: random_number = np.random.random() if random_number < epsilon:...
This function runs multiple episodes of a reinforcement learning agent, collecting total rewards and individual rewards per episode. It initializes exploration rate (epsilon), decreases it over time (unless evaluating), and optionally generates smoothed reward plots. The agent's states, all rewards, and total rewards a...
def run_all_episodes(self,title, evaluate=False): all_total_rewards = [] all_rewards = [] epsilon = self.initial_epsilon # at the start only explore power = 1 for episode in range(1, self.episodes + 1): states,rewards = self.run_episode(epsilon, eval...
def updateLR(self): lr = self.get_lr( self.iter_num) if self.decay_lr else self.learning_rate for param_group in self.optimizer.param_groups: param_group['lr'] = lr return lr def evalStep(self, lr, running_mfu): losses = self.estimate_loss() print( ...
The code performs a training loop for a machine learning model, updating the learning rate, executing training steps, logging loss and performance metrics (like MFU), saving model checkpoints, and checking early stopping conditions. It handles distributed training, evaluates periodically, updates iteration counts, and ...
def trainLoop(self, local_iter_num, running_mfu, t0): raw_model = self.model.module if self.ddp else self.model lr = self.updateLR() if self.iter_num % self.eval_interval == 0 and self.master_process: self.evalStep(lr, running_mfu) # if self.iter_num == 0 and self.eval_onl...
def activations(self) -> dict[str, dict[str, torch.Tensor]]: """Loads the model layers into hooks. Allows for layer activations to be accessed when data is input into model. Returns: Activations of all layers of all models contained in self.model E...
The code's main task is to visualize a neural network by processing each data entry, computing activations, normalizing them, and passing the structured data to a visualization method. It raises an error if no visualization method is specified, ensures data is prepared with activations, and triggers the visualization u...
def visualize(self) -> None: """Visualizes neural network with chosen visualization methods. Raises: Exception if self.visual is None. """ if self.visual is None: raise Exception( "Visualization not specific (self.visual is None), " ...