dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def load_from_pyscf_chkfile(chkfile, base="scf"): mol = lib.chkfile.load_mol(chkfile) with h5py.File(chkfile, "r") as fh5: try: hcore = fh5["/scf/hcore"][:] except KeyError: hcore = scf.hf.get_hcore(mol) try: X = fh5["/scf/orthoAORot"][:] excep...
This function generates IPie input files from a PySCF checkpoint file, creating Hamiltonian and wavefunction files. It processes molecular data, basis transformations, and electron counts, with options for MCSCF, orthogonal AO, frozen core, and UHF handling. The output depends on parameters like `gen_ham`, `ortho_ao`, ...
def gen_ipie_input_from_pyscf_chk_mod( pyscf_chkfile: str, hamil_file: str = "hamiltonian.h5", wfn_file: str = "wavefunction.h5", verbose: bool = True, chol_cut: float = 1e-5, ortho_ao: bool = False, mcscf: bool = False, linear_dep_thresh: float = 1e-8, ...
def Profile(Motifs): t = len(Motifs) count = Count(Motifs) profile = {key: ([value/t for value in count[key]]) for key in count} return profile def ProfileMostProbableKmer(text, k, profile): l = len(text) max_p = -1 max_profile = None for i in range(l-k+1): tmp = Pr(text[i:i+k], profile) if tmp > max_p: ...
The code implements the Greedy Motif Search algorithm to find the best set of k-length motifs across t DNA sequences. It initializes with the first k-mers from each sequence, then iterates over all possible starting positions in the first DNA string. For each position, it constructs a motif set by selecting the most pr...
def GreedyMotifSearch(Dna, k, t): BestMotifs = [] for i in range(0, t): BestMotifs.append(Dna[i][0:k]) n = len(Dna[0]) for i in range(n-k+1): Motifs = [] Motifs.append(Dna[0][i:i+k]) for j in range(1, t): P = Profile(Motifs[0:j]) Motifs.append(ProfileMostProbableKmer(Dna[j], k, P)) if Score(Motifs) ...
def ProfileWithPseudocounts(Motifs): k = len(Motifs[0]) count = CountWithPseudocounts(Motifs) profile = {} count_values = list(count.values()) for key in count: profile[key] = [] for i in range(k): profile[key].append(count[key][i]/(count_values[0][i] + count_values[1][i]+count_values[2][i]+count_va...
This function performs Greedy Motif Search with pseudocounts to identify the best set of k-mers from t DNA strings. It initializes candidate motifs, iterates through all possible starting positions in the first DNA string, constructs motifs using profile-based probability with pseudocounts, and updates the best motifs ...
def GreedyMotifSearchWithPseudocounts(Dna, k, t): BestMotifs = [] for i in range(0, t): BestMotifs.append(Dna[i][0:k]) n = len(Dna[0]) for i in range(n-k+1): Motifs = [] Motifs.append(Dna[0][i:i+k]) for j in range(1, t): P = ProfileWithPseudocounts(Motifs[0:j]) Motifs.append(ProfileMostProbableKmer(Dn...
def RandomMotifs(Dna, k, t): result = [] for dna in Dna: rand = random.randint(0, len(dna)-k) result.append(dna[rand:rand+k]) return result def ProfileWithPseudocounts(Motifs): k = len(Motifs[0]) count = CountWithPseudocounts(Motifs) profile = {} count_values = list(count.values()) for key in count: profi...
The code implements the Randomized Motif Search algorithm to identify the best set of k-length motifs in t DNA sequences. It iteratively generates random motifs, constructs a probability profile with pseudocounts, and refines motifs using this profile. The process repeats until the motif score no longer improves, retur...
def RandomizedMotifSearch(Dna, k, t): M = RandomMotifs(Dna, k, t) BestMotifs = M while True: Profile = ProfileWithPseudocounts(M) M = Motifs(Profile, Dna) if Score(M) < Score(BestMotifs): BestMotifs = M else: return BestMotifs
def create_window(title, fields, action): window = tk.Tk() window.title(title) entry_vars = [tk.StringVar() for _ in fields] for i, (label_text, _) in enumerate(fields): tk.Label(window, text=label_text).grid(row=i, column=0, sticky="e", padx=5, pady=5) tk.Entry(window, textvariable=ent...
This code creates a role-specific management system GUI by dynamically generating input fields based on the user's role (e.g., login, train, passenger). It destroys the previous window, initializes a new interface with role-specific data fields, and links form submission to either employee_action or project_action func...
def open_management_system(user_role): global root root.destroy() fields = { "login": [("Login ID:", ""), ("Username:", ""), ("Password:", "")], "train": [("Train ID:", ""), ("Train Name:", ""),("Source Station:",""),("Destination Station:",""),("Depature Time",""),("Arrival Time","")], ...
def create_window(title, fields, action): window = tk.Tk() window.title(title) entry_vars = [tk.StringVar() for _ in fields] for i, (label_text, _) in enumerate(fields): tk.Label(window, text=label_text).grid(row=i, column=0, sticky="e", padx=5, pady=5) tk.Entry(window, textvariable=ent...
This function generates a role-specific management system interface, dynamically creating input forms based on the provided user_role (e.g., employee, department, project). It destroys the previous GUI window, loads predefined fields for data entry, and initializes a new window with role-appropriate forms. Upon submiss...
def open_management_system(user_role): global root root.destroy() fields = { "employee": [("Employee ID:", ""), ("First Name:", ""), ("Last Name:", ""), ("Email:", ""), ("Phone Number:", ""), ("Hire Date:", "")], "department": [("Department ID:", ""), ("Department Name:", "")], "posi...
def generate_puzzle(self): self.solve_board(self.board) for _ in range(81): row = random.randint(0, 8) col = random.randint(0, 8) temp = self.board[row][col] self.board[row][col] = 0 count = 0 solution_copy = [row[:] for row in self...
The code initializes a new game based on the specified difficulty level by setting the number of cells to remove (40 for Easy, 50 for Medium, 60 for Hard). It creates a 9x9 game board, generates a puzzle, removes the designated number of cells to create empty spaces, identifies these empty cells, and finally renders th...
def new_game(self, level): if level == 'Easy': num_cells = 40 elif level == 'Medium': num_cells = 50 elif level == 'Hard': num_cells = 60 self.board = [[0] * 9 for _ in range(9)] self.generate_puzzle() self.remove_cells(num_cells) ...
def matmul(self, a, b): res = np.zeros([a.shape[0], b.shape[1]], dtype=int) for i in range(res.shape[0]): for j in range(res.shape[1]): res[i][j] = self.dot(a[i, :], b[:, j]) return res def add(self, a, b): sum = a ^ b return sum def div(self, a, b): ...
This code computes the inverse of a matrix using Gaussian elimination. It first handles non-square matrices by forming A^T A, then augments the matrix with an identity matrix. It performs forward elimination to create upper triangular form, normalizes rows, and back-substitutes to obtain the inverse. For non-square mat...
def inverse(self, A): if A.shape[0] != A.shape[1]: A_T = np.transpose(A) A_ = self.matmul(A_T, A) else: A_ = A A_ = np.concatenate((A_, np.eye(A_.shape[0], dtype=int)), axis=1) dim = A_.shape[0] for i in range(dim): if not A_[i, i]:...
def get_net_assets(self): # asset value + cash amount = total assets net_assets = self.get_cash() if self.asset_owned: net_assets += self.get_asset_value() return net_assets def get_continual_profit(self): return self.get_net_assets() - self.starting_cash def get_tran...
The code processes an asset price input to determine the latest model decision for trading. It updates model metrics, selects the optimal model if no asset is owned, and executes buy/sell actions based on decisions. It tracks cash, assets, and profit history, updating states like asset ownership and recording transacti...
def progress_models(self, asset_price): """ Takes in a datapoint representing the most recent price, and calls the model with the information. Also handles deciding between the multiple inputs from the models. :param asset_price: Most recent price. :return: The latest model decis...
def has_gradient(self): """Returns true if _backward and _forward_backward can be called by an attack, False otherwise. """ try: self.__model.gradient self.__model.predictions_and_gradient except AttributeError: return False else: ...
This method computes model predictions and gradients for a given image and label, handling defaults and bounds checks. It returns predictions, gradients, and optionally adversarial status, tracking call counts for monitoring.
def predictions_and_gradient( self, image=None, label=None, strict=True, return_details=False): """Interface to model.predictions_and_gradient for attacks. Parameters ---------- image : `numpy.ndarray` Single input with shape as expected by the model (...
def make_move_helper(self, board, depth, maximizing_player, alpha = -20000, beta = 20000, forbidden_move=None, file = None): if depth == 0: return (self.evaluate_board(board, file), None) if maximizing_player: moves = self.order_moves(board.legal_moves, board, self.color) if forbidden_move: moves.remo...
The main task of the code is to determine the best move for a game-playing AI by evaluating the board state using a helper function, tracking evaluation count and time efficiency, and handling special cases like draws or ties by adjusting the move selection. It returns the optimal move after considering performance met...
def make_move(self, board, screen = None, file = None): start = time.time() self.num_eval = 0 num, best_move = self.make_move_helper(board, self.depth, True, file = file) end = time.time() print('time: ' + str(end-start)) print('moves: ' + str(self.num_eval)) print('ratio: ' + str(self.num_eval/(end-start...
def make_xception_blocks( input_layer, channels, kernel_sizes ): sub_channels = int( channels/len(kernel_sizes) ) assert sub_channels * len(kernel_sizes) == channels, 'sub-channels and channels not match, adjust the channels or the size of sub-kernels' layer_blocks = [] for kernel_size in kernel_sizes: ...
This code defines a generator model with an encoder-decoder architecture, using Xception blocks, pooling, upsampling, and a transformer module. It processes input images through progressively smaller encoder layers, applies repeated transformations, then reconstructs features via decoders with skip connections. The mod...
def generator( input_channels=1, output_channels=1, transform_repeater=16, output_activation='tanh', name=None ): input_layer = Input( shape=(None, None, input_channels) ) encoder_128 = make_xception_blocks( make_block( input_layer, 64, with_normalization=False ), 64, (1, 3, 5, 7) ) encoder_64 = make_xcept...
def check_for_linebreak_chracter_and_move_position(self, i: int) -> bool: letter = self.text[i] if letter == "\n": self.current_y += self.settings.line_spacing_px self.current_x = self.settings.start_x return True return False def create_inbetweens_also_return...
The function generates a concatenated string (`text_and_inbetween_elements_block`) by interleaving text elements and inbetween elements from `self.text`, while tracking their names in separate lists. It skips line breaks, processes each element with helper methods, and appends an additional inbetween element at the end...
def create_text_and_inbetween_block(self): text_and_inbetween_elements_block: str = "" text_stimuli: list[str] = [] inbetween_stimuli: list[str] = [] inbetween_elements: str inbetween_name: str text_element: str text_name: str for i in range(len(self.tex...
def create_text_and_inbetween_block(self): text_and_inbetween_elements_block: str = "" text_stimuli: list[str] = [] inbetween_stimuli: list[str] = [] inbetween_elements: str inbetween_name: str text_element: str text_name: str for i in range(len(self.tex...
The main task of the code is to generate and concatenate multiple Inquisit script blocks into a unified output string. It combines blocks for defaults, values, expressions, text, and trial segments using "\n\n" as a delimiter, assigning the result to `self.out_string` for structured script creation.
def create_and_join_inquisit_blocks(self) -> None: text_inbetween_block: str = self.create_text_and_inbetween_block() self.out_string = "\n\n".join([ self.create_defaults_block(), self.create_values_block(), self.create_expressions_block(), text_inbetween_...
def get_numbers(ds): return ds[0].split(',') def get_boards(ds): j = 0 boards = {} board = [] for i in range(2, len(ds)): if ds[i] == '': boards[j] = board board = [] j += 1 continue board.append([x for x in ds[i].split(' ') if x != '']...
The code solves a puzzle by determining the winning board from a list of boards using a sequence of numbers, then calculates and returns the score of that winning board based on the numbers drawn up to the winning number.
def puzzle1(ds): res = '' numbers = get_numbers(ds) boards = get_boards(ds) winner, winning_number = get_winning_board(boards, numbers) res = get_score(boards[winner], numbers[:winning_number]) return res
def get_numbers(ds): return ds[0].split(',') def get_boards(ds): j = 0 boards = {} board = [] for i in range(2, len(ds)): if ds[i] == '': boards[j] = board board = [] j += 1 continue board.append([x for x in ds[i].split(' ') if x != '']...
The code determines the losing board in a game by identifying the last board to win using a sequence of numbers. It calculates the score for this board based on the numbers drawn up to the winning number and returns the result.
def puzzle2(ds): res = '' numbers = get_numbers(ds) boards = get_boards(ds) winner, winning_number = get_loser_board(boards, numbers) res = get_score(boards[winner], numbers[:winning_number]) return res
def print_books(c: MySQLConnection, user_id: int|None = None, exclude_wishlist: bool = True) -> None: """Print books 5 at a time. Optionally print only books from a wishlist, or all books except a wishlist.""" offset = 0 limit = 5 while True: # Python's prepared statement support appears to just prepare a new sta...
The main task of the code is to present a menu-driven interface allowing users to view books, store locations, manage their account, or quit. It continuously loops, processing user input to call corresponding functions: `print_books()`, `print_locations()`, or `account_menu()`, exiting on 'Q'. The function handles user...
def main_menu(c: MySQLConnection) -> None: """Print and handle the main menu""" while True: match input( "View Books (B)\n" + "View Store Locations (S)\n" + "My Account (A)\n" + "Quit (Q)\n" ).lower(): case "b": print_books(c) case "s": print_locations(c) case "a": account_menu(c)...
def update_filters(self, filters: str) -> None: """Updates the filter Currently, this is destructive, so new values are not merged with old ones. """ log.debug(f'Updating filters to {filters}') parts = filters.split('&') for part in parts: value, k...
The main task of the code is to continuously scrape and process new Pokémon encounter data, filtering out duplicates from a database, and sending notifications for unique encounters. It runs in a loop while active, using specified filters and delays between iterations to manage data retrieval and transmission efficient...
def __scraping_loop(self, filters = None) -> None: """ Repeatedly gets data and sends messages with it """ if filters: self.update_filters(filters) while self.__running: now_time = int(datetime.now(self.__tz).timestamp()) for poke in self.__get_data(): ...
def get_all_note_features(data_dir): midi_file_list = glob.glob(data_dir + '/*.midi.npy') note_features_all = [] audio_all = [] for midi_file in tqdm(midi_file_list): data = np.load(midi_file.replace('.midi', '.synth_params'), allow_pickle=True).item() data.update({'midi': np.load(mid...
The function processes musical note data by generating statistical plots, segmenting and preprocessing note features into tensor formats, and saving multiple versions of the processed data (segmented, non-segmented, and audio) as pickle files for machine learning tasks. It organizes outputs by dataset split and ensures...
def make_and_save_pickles(data_dir, split, pickle_output_dir, stats_plot_output_dir): split_stats_plot_output_dir = os.path.join(stats_plot_output_dir, f'{split}') os.makedirs(split_stats_plot_output_dir, exist_ok=True) note_features_all, audio_all = get_all_note_features(data_dir) not...
def preprocess(self, q_pitch, out): f0_midi = ddsp.core.hz_to_midi(out['f0_hz']) f0_midi_dv = f0_midi - q_pitch # f0 residual f0_midi_dv_onehot = get_onehot_f0_dv(f0_midi_dv) ld = out['loudness_db'] ld_onehot = get_onehot_ld(ld) return tf.concat([f0_midi_dv_onehot, ld_onehot], -1) def encode_co...
The main task of the code is to generate outputs using a partial teacher-forcing mechanism for sequence reconstruction. It combines predicted outputs with ground-truth data via a teacher-force mask, iteratively producing sequences by encoding conditions, applying one-step predictions, and sampling results. The process ...
def partial_teacher_force(self, q_pitch, z_midi_decoder, out, teacher_force_mask, training=False, display_progressbar=False): """For the expression generator reconstruction comparison. (Table 1 (c) in paper)""" # right shift and encode out out = se...
def make_file_contents(csv_file): """ Creates the 2d array for the messages """ csv_contents = _read_csv_file(csv_file) unique_words = _get_unique_words(csv_contents) index_dict = _get_index_dict(unique_words) file_contents = _transform_csv_contents(csv_contents, index_dict, len(unique_words...
The code initializes a class by loading data from a CSV file, processing it into contents, unique words, and an index dictionary. It then computes column thresholds and updates the contents using a helper method, preparing the data for further analysis or operations.
def __init__(self, csv_file): (contents, unique_words, index_dict) = make_file_contents(csv_file) self.contents = contents self.unique_words = unique_words self.index_dict = index_dict self.column_thresholds = make_column_thresholds(contents) self._update_contents()
def get_param_error(planet: Series, pkey: str) -> float: """ Get average uncertainty for a single parameter based on :param planet: Series with planet parameter info :type planet: Series :param pkey: Key of the parameter for which we want the error :type pkey: str :return: Mean uncertainty ...
The function retrieves orbital parameters from a planet's data for RV curve calculations. It checks for missing values, samples parameters with uncertainties if specified, handles special cases like transit time, and ensures all parameters are arrays (repeating scalars if needed) for consistent processing.
def get_orbit_params(planet: Series, n_samples: int = 0) -> Series: """ Get parameters that are required to compute RV curve from archive row :param planet: Archive row with planet info stored in a pandas series :type planet: Series :param n_samples: Number of samples to draw (use best value if 0),...
def can_read_from_db(): return run_pg_query(f'SELECT * FROM accounts LIMIT 1;') def can_write_from_db(account_name): return run_pg_modify(f'INSERT INTO accounts(name,owner_email,created_on) VALUES(\'{account_name}\', \'{test_account["email"]}\', CURRENT_DATE);') def can_delete_from_db(account_name): return ...
The main task of the code is to verify the readiness of a database for read, write, and delete operations. It checks if reading from the database is possible, generates a UUID for the check, and then validates write and delete operations using this UUID. If any operation fails, it logs a warning and returns False; othe...
def do_ready_check_db_operation(): # Check read from DB if not can_read_from_db(): logging.warning("could not read from DB during ready check") return False # Generate UUID for this check run_uuid = test_account['name-prefix'] + str(uuid.uuid1()) logging.info("selected account ...
def test_zone(lon, lat, vic_map_data): zone = get_zone_from_point(Point(lon, lat), vic_map_data) print(zone) def get_docs(db, limit=100): result = db.view("_all_docs", limit=limit) return [db[row.id] for row in result] def process_geo_and_save_docs(target_db, no_zone_db, docs, vic_map_data): for doc...
The main task of the code is to process geolocation data from Twitter documents stored in a CouchDB database, categorizing them into zone-specific or no-zone databases based on a provided map file. It reads configuration details, connects to CouchDB, fetches documents in batches, applies zone detection using the map, a...
def main(): # read map file with open("vic_geo.json", "r") as f: vic_map_data = json.load(f) # Test zone function test_zone(144.962227, -37.812328, vic_map_data) # Connect to the database config = configparser.ConfigParser() config.read("config.ini") admin = config.get("couchD...
def subscribe(): payload = {'type': 'SUBSCRIBE', 'subscribe': { 'framework_info': { 'user': 'testuser', 'name': 'testframework' } } } r = requests.post(APIROOT, json=payload, ...
The code establishes a connection to an event stream by subscribing, retrieves the stream ID from the response headers, and continuously processes incoming events in an infinite loop using the retrieved stream ID.
def start_conn(): global STREAM req = subscribe() STREAM = req.headers['Mesos-Stream-Id'] while True: event = get_event(req) handle_event(event)
def get_keypress(self): """ Listen for key press """ keys = event.getKeys() if keys: return keys[0] else: return None def advance(self): """ Advance the moving checks or bars """ if self.behavior.name == "BOUNCE": ...
The code presents a Kalatsky stimulus by displaying alternating checkerboard or bar patterns on a screen, reversing colors at set intervals using a flip timer. It initializes visual elements, handles user input to terminate the stimulus, and cycles through predefined patterns while maintaining synchronization via timin...
def present(self): """ Prsent Kalatsky stimulus """ flip_timer = core.CountdownTimer(self.flip_period) colors = self.initial_colors # draw checkerboard or bars for i in np.linspace(start=(self.check_height/2)-1, stop=1-(self.check_height/2), num=self.number_of_c...
def roi_pooling(self, slow_features, fast_features, proposals): if slow_features is not None: if self.config.MODEL.ROI_ACTION_HEAD.MEAN_BEFORE_POOLER: slow_features = slow_features.mean(dim=2, keepdim=True) slow_x = self.pooler(slow_features, proposals) if not...
The code processes input features (slow/fast) and proposals/keypoints through ROI pooling, max pooling, and fusion modules. It extracts person/object/hand/pose features, applies a transformer for pose estimation, and fuses outputs. The function returns processed features and a final output tensor after fully connected ...
def forward(self, slow_features, fast_features, proposals, objects=None, keypoints=None, extras={}, part_forward=-1): ia_active = hasattr(self, "hit_structure") if part_forward == 1: person_pooled = cat([box.get_field("pooled_feature") for box in proposals]) if objects is None: ...
def read_data_upload_s3(): application.logger.info("adding file to s3") global url global fname fname = url[url.rfind("/") + 1:] location = os.getcwd() + "/" + url[url.rfind("/") + 1:] data = urllib.urlopen(url) datatowrite = data.read() with open(location, 'wb') as f: f.write(d...
The main task of the code is to load data by reading and uploading it to S3, creating a database, and updating DynamoDB, while logging progress and managing a global message variable.
def load_data(): global msg msg = "" application.logger.info("inside load_data") read_data_upload_s3() create_db() update_dynamoDb()
def load_data(): read_data_upload_s3() update_dynamoDb() def queryData(q1,q2): dynamodb = boto3.client('dynamodb') tempDb= boto3.resource('dynamodb') table = tempDb.Table('programfourestoragetable') response = [] if dbName not in dynamodb.list_tables()['TableNames']: print("DAtabas...
The main task of the code is to load data, execute a query with parameters "Ray" and an empty string using `queryData()`, and subsequently clear the data. The commented-out `clear_data()` calls suggest potential alternative steps or debugging points, but the final `clear_data()` is actively executed to finalize data pr...
def main(): load_data() #clear_data() #clear_data() q1 = "Ray" q2 = "" queryData(q1,q2) clear_data()
def move(self) -> None: if self.engine.step() == "Colision": return "Colision" if self.engine.food_eaten is True: pg.mixer.music.play() self.score += 1 self.show_score() self.draw_matrix(self.engine.desk) def ending(self) -> None: self....
The code defines a game loop that handles Pygame events, including quitting the window, processing movement events for collision detection, and responding to arrow key inputs to control game actions. It updates the display and maintains a consistent frame rate using a clock.
def run(self) -> None: while True: for event in pg.event.get(): if event.type == QUIT: # Window quit pg.quit() sys.exit() if event.type == self.MOVEEVENT: if self.move() == "Colision": ...
def train(model, iterator, optimizer, criterion, epoch): model.train() epoch_loss = 0 pbar = tq.tqdm(desc="Epoch {}".format(epoch), total=len(iterator), unit="batch") for i, batch in enumerate(iterator): src = batch.src trg = batch.trg optimizer.zero_...
The main task of the code is to train and evaluate a sequence-to-sequence model with attention mechanisms for German-to-English translation using the Multi30k dataset. It loads and tokenizes data with spaCy, builds vocabulary, trains a bidirectional encoder-decoder model with specified attention types (none/mean/sdp), ...
def main(): logging.info('Using device: {}'.format(dev)) logging.info("Loading tokenizers and dataset") spacy_de = spacy.load('de_core_news_sm')#de_core_news_sm.load() spacy_en = spacy.load('en_core_web_sm')#en_core_web_sm.load() SRC = Field(tokenize = lambda text: [tok.text for tok in spacy...
def _check_if_path_is_active_for_date(path, date): path_should_be_restored = False path_to_restore = None with open(config_data['history_log'], mode='r') as file: csv_reader = csv.reader(file) rows = list(csv_reader) # Reverse the list of rows to...
The function restores backup files for a specified date into a recover directory, extracts zip archives, handles errors like invalid zips or missing files, and recursively processes subfolders to ensure all necessary backups are restored.
def _restore_backup_for_current_folder(current_folder, date): global backups_combined # Check if current folder needs to be restored restore_file, path_to_restore = _check_if_path_is_active_for_date(current_folder, date) # Restore files for current folder if restore_file: ...
def list_files_without_hidden(folder_path): # Get all files in the current folder, excluding hidden files return [f for f in os.listdir(folder_path) if not f.startswith('.')] def _create_backup_for_current_folder(current_folder): global backups_created global folders_checked # Get the ex...
This function recursively traverses subfolders of a given directory, creating backups for each non-hidden subfolder and processing nested directories by calling itself on each subfolder's path.
def cycle_through_subfolders(folder_path): for source_subfolder in list_files_without_hidden(folder_path): full_source_subfolder_path = os.path.join(folder_path,source_subfolder) if not os.path.isfile(full_source_subfolder_path): _create_backup_for_current_folder(full_sou...
def load(filename): filename = os.path.join(SAVED_MODELS_FOLDER, filename) try: f = open(filename, 'rb') steps, args = pickle.load(f) f.close() except FileNotFoundError: print('Could not open file {}'.format(filename)) sys.exit() return steps, args def runs(env, ...
The code's main task is to run simulations in a reinforcement learning environment, varying parameters `alphas` and `lambdas`. It initializes the environment, loads pre-saved data if specified, otherwise executes simulations to compute average steps. Results are saved and visualized in a 3D plot showing steps against `...
def main(): global args # sets the seed for random experiments np.random.seed(args.seed) env = gym.make(args.env) env._max_episode_steps = args.max_steps alphas = args.alphas lambdas = args.lambdas if args.load is not None: # load pre-saved data filename = args.load ...
def ms_conv3x3(in_channels, out_channels, stride=1, padding=0, pad_mode='same', has_bias=False): """Get a conv2d layer with 3x3 kernel size.""" init_value = weight_variable((out_channels, in_channels, 3, 3)) return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, paddi...
This code defines a ResNet model's initialization, configuring convolutional layers, batch normalization, ReLU activation, and max-pooling operations. It constructs residual blocks with specified layers, adjusts output channels through stages, and applies downsampling via pooling and convolution. The network processes ...
def __init__(self, input_channel, output_channel, block, layers): super(ResNet, self).__init__() self.output_channel_block = [int(output_channel / 4), int(output_channel / 2), output_channel, output_channel] self.inplanes = int(output_channel / 8) self.conv0_1 = ms_conv3x3(input_channe...
def get_files_from_directory(directory, headers): """ Recursively retrieves the files within a directory. """ files = [] api_url = directory['url'] response = requests.get(api_url, headers=headers) if response.status_code == 200: contents = response.json() for i...
The code retrieves a GitHub repository's structure via the GitHub API, extracts files with specific extensions (JavaScript/CSS), and generates a JSON-formatted network structure representing files, their metadata (size, path), dependencies, and hooks. It recursively processes directories and returns the structured data...
def get_project_structure(repo_url): # access_token = 'your_github_token_here' access_token = os.getenv("GITHUB_API_KEY") print(repo_url) api_url = f'{repo_url}' global repo_content_url repo_content_url = api_url # api_url = f'https://api.github.com/repos/MohyiddineDilmi/air-borne/contents' ...
def get_function_name(): """ Get name of function this is called from. """ return sys._getframe(1).f_code.co_name def get_dirs(instance): """ Each instance has a set of directories that should be checked. Some directories won't be checked if the DS already deploys to those directories. ...
The code updates configuration files by processing specific file types (e.g., .conf, .xml) in designated directories, modifying content via `modify_KO`, and writing changes if not in dry-run mode. It logs directory structures, excludes irrelevant files/directories, and records manual changes in a log file. The function...
def update_configuration_files(): # Set up logging. f_name = get_function_name() log_format = f_name + ": " + "{0}" # Get directories appropriate to the instance. instance_dirs = get_dirs(INSTANCE) # logging.debug(log_format.format(log_text)) message = log_format.format("Created list of d...
def get_function_name(): """ Get name of function this is called from. """ return sys._getframe(1).f_code.co_name def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i:i+n] def modify_KO(original_content, file=None, identifier=No...
The `update_SHC_KOs` function updates user-owned knowledge objects (KOs) in a system by modifying their search queries based on index mappings. It fetches KOs via REST APIs (saved searches, eventtypes, macros, views), identifies valid KOs authored by non-'nobody' users, and applies modifications. When `ops=True`, it pr...
def update_SHC_KOs(ops=False, audit=True, chunk_size=5, sleep_period=300): """Assumes 5 KO executions per period and a 5-minute rest period.""" """ TESTING: #### Create KO for a user (saved search where 'index=DUMMY_INDEX_SHC_TEST'). #### Create index_map.csv that maps DUMMY_INDEX_SHC_TEST to TEST_...
def calculateSurfaceStats(self, bmeshObj): """ Calculates the sum of areas of the triangles of the patch """ #Total area (sum of triangle areas) self.totalArea = np.sum([bmeshObj.faces[faceIdx].calc_area() for faceIdx in self.getFacesIdxIterator()]) #Max edge length ...
The code defines a method `computeProperties` that recalculates geometric descriptors of a 3D mesh patch by invoking three sub-functions: calculating surface statistics, patch eigenvalues, and sampling normals. This serves as a streamlined interface to update the patch's geometric properties in a single call.
def computeProperties(self, bmeshObj): """ Syntaxic sugar to (re-)calculate the geometric descriptors of the patch """ self.calculateSurfaceStats(bmeshObj) self.calculatePatchEigenValues(bmeshObj) self.samplePatchNormals(bmeshObj)
def find_stations_within_box(X, Y): download_map() f = open("map.kml", 'r', encoding="utf-8") doc = parser.parse(f).getroot() station_ids = [] for folder in doc.Document.Folder.Folder: for station in folder.Placemark: lon = float(station.LookAt.longitude) lat = float(...
The code downloads and processes weather data from specified stations, adjusting time ranges based on data availability. It saves data in CSV or DFS0 formats, merges files if requested, and optionally generates a shapefile. Logs errors and adjustments during execution.
def download(station_ids=[], start=None, end=None, csv=True, dfs0=False, merge=False, shapefile=False, shp_fname="Stations.shp", X=None, Y=None): log = open("Error logs.txt", "w") mainStart = start mainEnd = end if X != None and Y != None: station_ids = find_stations_within_box(X, Y) fo...
def define_var(variable): if variable == "Meteorological": return "stdmet", "h" elif variable == "Currents": return "adcp", "a" elif variable == "Wind": return "cwind", "c" print("Variable is not defined!") quit() def find_stations_within_box(X, Y): download_map() f =...
The code downloads meteorological data from specified stations over a given time range, adjusting start/end years based on data availability. It saves data as CSV or DFS0 files, merges datasets if requested, and optionally creates a shapefile. Logs are recorded during execution, handling station coordinates, data forma...
def download(station_ids=[], start=None, end=None, csv=True, dfs0=False, merge=False, shapefile=False, shp_fname="Stations.shp", X=None, Y=None, variable="Meteorological"): log = open("logs.txt", "w") var, letter = define_var(variable) if type(station_ids) != list: station_ids = [station_ids] ma...
def check_collision(board, shape, offset): off_x, off_y = offset for cy, row in enumerate(shape): for cx, cell in enumerate(row): try: if cell and board[ cy + off_y ][ cx + off_x ]: return Tru...
This method handles dropping a Tetris piece. If the game isn't over/paused, it increases the score (if manual), moves the piece down, checks for collisions. On collision, it locks the piece into the board, clears full rows, updates the score for cleared lines, and returns True. Otherwise, returns False.
def drop(self, manual): if not self.gameover and not self.paused: self.score += 1 if manual else 0 self.stone_y += 1 if check_collision(self.board, self.stone, ...
def move(self, delta_x): if not self.gameover and not self.paused: new_x = self.stone_x + delta_x if new_x < 0: new_x = 0 if new_x > cols - len(self.stone[0]): new_x = ...
This code implements an AI for Tetris using a genetic algorithm. It defines game controls, manages AI actions (movement, rotation, dropping), and evolves a population of weightings through generations. During training, it records scores, lines cleared, and levels, selects top-performing weightings, and applies mutation...
def run(self): key_actions = { 'ESCAPE': self.quit, 'LEFT': lambda:self.move(-1), 'RIGHT': lambda:self.move(+1), 'DOWN': lambda:self.drop(True), 'UP': ...
def load_inputs(self, controller): controller.current_model = self.entry_model.get() controller.current_spec = self.entry_spec.get() controller.draw_new() def save_current_fit(self, controller): if not os.path.exists(user_settings.OUTPUT_LOG_DIR + 'intsyn.log'): with open(use...
This code initializes a GUI interface with input fields for model and spectrum paths, buttons to open, clear, save, and navigate through a list of inputs, and loads existing settings if available. It sets up a canvas with labeled entries and action buttons for data handling and list management.
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.canvas = tk.Canvas(controller, width=700, height=100, relief='raised') self.canvas.pack() label_mod = tk.Label(controller, text='Path to model:') self.canvas.create_window(70, 25, window=label_mod) ...
def move_up(self) -> None: self._list = transpose(self.get_tiles()) self.move_left() self._list = transpose(self.get_tiles()) def move_down(self) -> None: self._list = transpose(self.get_tiles()) self.move_right() self._list = transpose(self.get_tiles()) def move_left(sel...
The main task of the code is to attempt a movement in the specified direction (up, down, left, right) by calling the corresponding method, then check if the move altered the internal state by comparing the original list with the new list. It returns True if the move changed the state, otherwise False.
def attempt_move(self, move: str) -> bool: new_list = self._list[:] if move == UP: self.move_up() elif move == DOWN: self.move_down() elif move == LEFT: self.move_left() elif move == RIGHT: self.move_right() return self._li...
def seEspera(t,preanalisis): if(t!=None): if(t==preanalisis): return True; return False; def error(t1,t2,line): print("Se esperaba ",t1, "en linea ",line," se recibio ",t2) def LISTA_ENTERO(): DE() t=l.obtenerToken(); if(t!=None): if t.getSubTipo()== SubTipoToken.COMA: p...
This function validates an integer declaration by checking if the current token is of type 'ENTERO', processes a list of integers, and verifies the presence of a semicolon, raising errors for invalid tokens or missing syntax elements.
def DECLARACION_ENTERO(): t=l.obtenerToken() if(t!=None): if(not seEspera(t.getSubTipo(),SubTipoToken.ENTERO)): error(SubTipoToken.ENTERO,t.getSubTipo(),t.getnumLinea()); else: print("Se reconoce palabra ENTERO") LISTA_ENTERO() t=l.obtenerToken() if(t!=None): ...
def seEspera(t,preanalisis): if(t!=None): if(t==preanalisis): return True; return False; def error(t1,t2,line): print("Se esperaba ",t1, "en linea ",line," se recibio ",t2) def LISTA_REAL(): DR() t=l.obtenerToken(); if(t!=None): if t.getSubTipo()== SubTipoToken.COMA: pri...
The code defines a function `DECLARACION_REAL()` that parses and validates a real number declaration. It checks if the first token is of subtype `REAL`, raising an error if not, then processes a list of real values via `LISTA_REAL()`. It subsequently verifies the next token is a semicolon (`PUNTOYCOMA`), issuing an err...
def DECLARACION_REAL(): t=l.obtenerToken() if(t!=None): if(not seEspera(t.getSubTipo(),SubTipoToken.REAL)): error(SubTipoToken.REAL,t.getnumLinea()); else: print("Se reconoce real") LISTA_REAL() t=l.obtenerToken() if(t!=None): if(not seEspera(t.getSubTipo(...
def seEspera(t,preanalisis): if(t!=None): if(t==preanalisis): return True; return False; def error(t1,t2,line): print("Se esperaba ",t1, "en linea ",line," se recibio ",t2) def LISTA_LOGICO(): DL() t=l.obtenerToken(); if(t!=None): if t.getSubTipo()== SubTipoToken.COMA: p...
The main task of the code is to parse a logical declaration in a programming language. It checks if the current token is of type "LOGICO" (logical), validates its syntax, processes a list of logical elements via LISTA_LOGICO(), and ensures the next token is a semicolon (";"). Errors are reported if expected token types...
def DECLARACION_LOGICO(): t=l.obtenerToken() if(t!=None): if(not seEspera(t.getSubTipo(),SubTipoToken.LOGICO)): error(SubTipoToken.LOGICO,t.getSubTipo(),t.getnumLinea()); else: print("Se reconoce palabra LOGICO") LISTA_LOGICO() t=l.obtenerToken() if(t!=None): ...
def seEspera(t,preanalisis): if(t!=None): if(t==preanalisis): return True; return False; def error(t1,t2,line): print("Se esperaba ",t1, "en linea ",line," se recibio ",t2) def LISTA_CARACTER(): DC() t=l.obtenerToken(); if(t!=None): if t.getSubTipo()== SubTipoToken.COMA: ...
The main task of the code is to parse and validate a character declaration in a programming language. It checks if the first token is a valid 'character' type, prints a confirmation if valid, then processes a list of characters. It subsequently verifies the next token is a semicolon, printing confirmation or triggering...
def DECLARACION_CARACTER(): t=l.obtenerToken() if(t!=None): if(not seEspera(t.getSubTipo(),SubTipoToken.CARACTER)): error(SubTipoToken.CARACTER,t.getSubTipo(),t.getnumLinea()) else: print("Se reconoce caracter") LISTA_CARACTER() t=l.obtenerToken() if(t!=None): ...
def seEspera(t,preanalisis): if(t!=None): if(t==preanalisis): return True; return False; def N(): t = l.obtenerToken() if (t != None): if seEspera(t.getSubTipo(), SubTipoToken.NEGACION): F() else: l.regresarToken(t) F()
This function processes tokens for multiplicative operators (*, /, %). If a token matches one of these operators, it calls N() to handle operands and recursively processes the next token (TP()). If no operator is found, it returns the token. The function likely builds a parse tree for arithmetic expressions with operat...
def TP(): t = l.obtenerToken() if (t != None): if seEspera(t.getSubTipo(), SubTipoToken.OPERADOR_MULTIPLICACION) or seEspera(t.getSubTipo(), SubTipoToken.OPERADOR_DIVISION) or seEspera(t.getSubTipo(), SubTipoToken.OPERADOR_MODULO): N() TP() else: l.regresarTok...
def seEspera(t,preanalisis): if(t!=None): if(t==preanalisis): return True; return False; def T(): N() TP()
The function EP() parses expressions involving addition and subtraction operators. It retrieves a token, checks if it is an operator (SUMA or RESTA), processes the operator by calling T() and recursively invoking EP() for subsequent operations, or returns the token if no operator is found, facilitating recursive descen...
def EP(): t = l.obtenerToken() if (t != None): if seEspera(t.getSubTipo(), SubTipoToken.OPERADOR_SUMA) or seEspera(t.getSubTipo(), SubTipoToken.OPERADOR_RESTA): T() EP() else: l.regresarToken(t)
def face_age_alexnet(self, x, scope_name='alexnet', if_age=False, reuse=False): with tf.variable_scope(scope_name, reuse=reuse) as scope: # 1st Layer: Conv (w ReLu) -> Pool -> Lrn conv1 = conv(x, 11, 11, 96, 4, 4, padding='VALID', name='conv1') pool1 = max_pool(conv1, 3, 3, 2...
The code trains a Least Squares GAN (LSGAN) with transfer learning for age-related image synthesis. It uses a ResNet generator to produce images conditioned on age labels, while a PatchDiscriminator distinguishes real/fake images. The generator is optimized using LSGAN loss, age classification loss via AlexNet, and fea...
def train_age_lsgan_transfer(self, source_img_227, source_img_128, imgs, true_label_fea_128, true_label_fea_64, false_label_fea_64, fea_layer_name, age_label): """ :param source_img_227: remove mean and size is 227 :param source_img_128: remove mean and size is 1...
def process_target_img(root_folder, img_path, img_size): img = cv2.imread(root_folder + img_path) img = img[:, :, [2, 1, 0]] # rescale image img = cv2.resize(img, (img_size, img_size)) img = img.astype(np.float32) img = img / 127.5 - 1. return img def reset_pointer(self, index): """ ...
The code prepares a batch of target images and associated labels for training, retrieves corresponding source images, updates data pointers, and returns processed images, labels, and features for a machine learning model. It handles data iteration, label pairing, and image scaling for transfer learning tasks.
def next_batch_transfer(self, source_index, source_image_size=227): index = self.true_labels[self.label_pair_index] paths = self.images[index][self.pointer[index]:self.pointer[index] + self.batch_size] # Read images imgs = np.ndarray([self.batch_size, self.scale_size[0], self.scale_size[...
def process_target_img(root_folder, img_path, img_size): img = cv2.imread(root_folder + img_path) img = img[:, :, [2, 1, 0]] # rescale image img = cv2.resize(img, (img_size, img_size)) img = img.astype(np.float32) img = img / 127.5 - 1. return img def reset_pointer(self, index): """ ...
This function retrieves a batch of images and associated labels for training, updates data pointers, and returns processed images, source images, one-hot labels, feature labels, error labels, and age labels. It handles batch indexing, pointer management, and data reset when reaching dataset limits, supporting tasks lik...
def next_age_batch_transfer(self, source_index): index = self.true_labels[self.label_pair_index] paths = self.images[index][self.pointer[index]:self.pointer[index] + self.batch_size] # Read images imgs = np.ndarray([self.batch_size, self.scale_size[0], self.scale_size[1], 3]) for...
def process_target_img(root_folder, img_path, img_size): img = cv2.imread(root_folder + img_path) img = img[:, :, [2, 1, 0]] # rescale image img = cv2.resize(img, (img_size, img_size)) img = img.astype(np.float32) img = img / 127.5 - 1. return img def reset_pointer(self, index): """ ...
The function retrieves a batch of images and associated data for training, including processed images, one-hot labels, label features, and error labels. It updates pointers for data iteration, resets pointers when reaching dataset limits, and returns images in different resolutions along with additional features for mo...
def next_batch_transfer2(self, source_index=0): index = self.true_labels[self.label_pair_index] paths = self.images[index][self.pointer[index]:self.pointer[index] + self.batch_size] # Read images imgs = np.ndarray([self.batch_size, self.scale_size[0], self.scale_size[1], 3]) for ...
def load_voting_locs(input_vl_file, use_open_spots): ret = [] i = 0 if not use_open_spots: with open(input_vl_file, newline='') as voting_locs: reader = csv.DictReader(voting_locs, delimiter=',') for row in reader: ret.append(VotingLoc(row, i)) i += 1 return ret voting_loc_by_key = {} with ope...
The code processes volunteer and voting location data to match volunteers to locations based on date and county preferences. It loads voting locations, filters those exceeding quota, categorizes volunteers by date and county preferences using regex, and matches volunteers to eligible locations for each date, prioritizi...
def run(input_vl_file, use_open_spots): voting_locs = load_voting_locs(input_vl_file, use_open_spots) print("MORE THAN 2") for vl in voting_locs: if vl.open_spots > PER_LOCATION_QUOTA: print(str(vl)) raw_volunteers = load_volunteers() vols_by_id = {v.id: v for v in raw_volunteers} vls_by_id = {vl.id: vl f...
def parse_region_file(fpath, sep="\t", skip=0, header=1, add_chr=True, discard_celltype=BLACKLIST_CELLTYPE, bampath="./"): """Parse position file.""" snp_pos_map = {} if skip >...
The main task of the code is to plot ASoC (Allele-Specific Occupancy) read counts for specified SNPs using BAM files and region data. It parses command-line arguments for input files, parameters, and output settings, processes region files to extract SNP positions, fetches read counts around each SNP, generates visuali...
def main(): """The main entry of the script.""" # CLI arguments parser = argparse.ArgumentParser(description="Plot ASoC read counts.") parser.add_argument("-r", "--region-file", required=True, metavar="FILE", help="A tab-delimited file including SNP positions.") parser.add_ar...
def check_netcdf_file(): """check the input netCDF model file and make sure it exist and extract info Return values: this_file: file name with no extension """ # check the model file and extract necessary information # must be in the argument list if NETCDF_FILE_NAME is None: print...
The function `make_model_geocsv` converts a netCDF model file into a GeoCSV format by extracting spatial (X, Y, Z) and model variables, preserving precision via string conversion. It handles 2D/3D data, generates CSV files in "single" or "depth" modes, and validates variable dimensions. Headers and data are written dyn...
def make_model_geocsv(): """create GeoCSV file from a netCDF model file Keyword arguments: model_file: the netCDF model file name """ model_file, base_file_name = check_netcdf_file() print(f"[INFO] Input netCDF File: {model_file}", flush=True) data_header = list() model_data = Dataset...
def specific_backend_path(): global _BACKEND_PATH global _VENV_PYTHON_PATH global _VENV_PIP_PATH _BACKEND_PATH = input("Please enter desired backend path") _BACKEND_PATH.replace("\n", "") print("Backend Path is updated!") _VENV_PIP_PATH = f"{_BACKEND_PATH}/venv/bin/pip" _VENV_PYTHON_PAT...
This function processes command-line arguments to initiate specific system setup tasks. It checks the input argument and triggers corresponding actions: defining a prepath (-s), starting installation (-i), configuring NGINX (-n), or setting a Daphne daemon (-d). If an unrecognized argument is provided, it raises an err...
def system_arguments(arg): global _BASE_PATH if _BASE_PATH == "": _BASE_PATH = os.getcwd() if arg == '-s': print("Prepath definition is captured!") specific_backend_path() elif arg == '-i': print("Installation has begun!") installation() elif arg == '-n': ...
def course_codes(self): ##token setting for next detail page self.token_creator(self.basePage) ## course codes retrieval self.courseDict = self.course_button_binding(self.basePage) return self.courseDict def course_detail_page(self,course_code_value): token = {'ctl00_RadS...
This method extracts course content from a detailed page by first retrieving course codes, generating a token for authentication, and then parsing the course details page to extract and return the content.
def course_content_list(self): self.course_codes() detailPage = self.course_detail_page(self.courseDict[self.course]) self.token_creator(detailPage) course_content = self.course_content_extractor(detailPage) return course_content
def course_codes(self): ##token setting for next detail page self.token_creator(self.basePage) ## course codes retrieval self.courseDict = self.course_button_binding(self.basePage) return self.courseDict def course_detail_page(self,course_code_value): token = {'ctl00_RadS...
The code initiates a download process by retrieving course details, extracting necessary tokens from a webpage, and using them to send a POST request. It then streams the response, saves the received file with a dynamically determined filename, and returns the filename. The task involves handling web tokens, HTTP reque...
def initiater(self,res_button_value): return_var = None print("starting Initiator....") self.course_codes() detailPage = self.course_detail_page(self.courseDict[self.course]) tokenList = list(self.varToken.keys()) tokenList.remove('ctl00_RadScriptManager1_TSM') se...
def construct_model(): vgg = tf.keras.applications.vgg19.VGG19(include_top=False, weights='imagenet') vgg.trainable = False style_outputs = [vgg.get_layer(name).output for name in STYLE_LAYERS] content_outputs = [vgg.get_layer(name).output for name in CONTENT_LAYERS] model_outputs = style_outputs + content_outp...
This code performs neural style transfer by generating an image that combines the content of the input content image with the artistic style of the input style image. It uses a pre-trained model to extract features, applies a loss function balancing content and style weights, and iteratively optimizes an initial image ...
def style_transfer(content_path, style_path, iters=1000, content_weight=1e3, style_weight=1e-2): model = construct_model() for layer in model.layers: layer.trainable = False style_features, content_features = get_features(model, content_path, style_path) gram_style_features = [gram_matrix(feature) for feature...
def verify_account(self): self.current_amount.clear() try: first_name = str(self.input_first.text()).strip().upper() last_name = str(self.input_last.text()).strip().upper() account_num = str(self.input_account.text()).strip() pin = str(self.input_pin.text(...
This code initializes a GUI interface by setting up the user interface and connecting button actions to specific functions: account verification, balance modification, displaying frames for deposit/withdrawal, and clearing inputs. It links UI elements to methods handling user interactions, enabling functionalities like...
def __init__(self): super().__init__() self.setupUi(self) self.verify.clicked.connect(lambda: self.verify_account()) # account verification self.submit.clicked.connect(lambda: self.account_modify()) # lead to balance change self.deposit.clicked.connect(lambda: self.show_frame()...
def read_header(header, line_num, lines): while line_num < len(lines): line = lines[line_num] if "TRACK" in line: break if "TITLE" in line: header.title = get_quoted_string(line) if "FILE" in line: fi, fo = get_file_and_format(line) path = os.path.split(header.cuefile) header.audiofile = os.path...
This function processes a CUE file by reading its header and track information, handling potential I/O and encoding errors. It parses the file's structure, extracts metadata, estimates duration if unspecified, and returns a CueHeader object along with a list of parsed tracks.
def process_cuefile(filename: str, passed_duration: int = 99999) -> Tuple[CueHeader, list]: header = CueHeader() header.cuefile = filename header.duration_in_frames = passed_duration # we'll try to read this later from wave file track_list = [] try: fileobject = open(filename, "r", encoding="utf-8") except IOE...
def on_off(self): if self.tmp == 0: self.on() self.tmp = 1 else: self.off() self.tmp = 0 def light_up(self, t=1): if self.pct + t * self.unit > 1: self.pct = 1 else: self.pct = self.pct + t * self.unit self.o...
The code configures three buttons on a panel to trigger specific actions when clicked: the first toggles an on/off state, the second activates a light-up function, and the third initiates a light-down function. It assigns lambda functions to each button's on_click event, linking them to corresponding methods (on_off, l...
def _setting(self): #config for actions self.panel.buttons[0].on_click(lambda x: self.on_off()) self.panel.buttons[1].on_click(lambda x: self.light_up()) self.panel.buttons[2].on_click(lambda x: self.light_down())
def restart(self): self.count = 0 self.totalReward = 0.0 self.workingState = self.gameEnv.start()[:] self.initializeVtableStateEntry(self.workingState) def egreedy(self, state): self.initializeVtableStateEntry(state) # Explore or be greedy if random.uniform(0,1) < self.epsilon: return...
The main task of the code is to perform Q-learning using epsilon-greedy exploration in a reinforcement learning setup. It iteratively selects actions, updates the value table with new state-action values based on rewards, accumulates total rewards, and progresses through the environment until reaching a terminal state ...
def qLearn(self): self.restart() # while terminal state not reached and counter hasn't expired, use epsilon-greedy search while not self.workingState[-1] and self.count < self.numSteps: # Take the epsilon-greedy action nextAction = self.egreedy(self.workingState) currentState, reward = se...
def _pad_img(img, window_size, subdivisions): """ Add borders to img for a "valid" border pattern according to "window_size" and "subdivisions". Image is an np array of shape (x, y, nb_channels). """ aug = int(round(window_size * (1 - 1.0/subdivisions))) more_borders = ((aug, aug), (aug, aug...
The function `predict_img_with_smooth_windowing` applies a prediction function (`pred_func`) to overlapping square patches of an input image, then smoothly merges the results to reconstruct the full prediction. It pads the image, processes rotated/mirrored subdivisions, and combines predictions using tiling with overla...
def predict_img_with_smooth_windowing(input_img, window_size, subdivisions, nb_classes, pred_func): """ Apply the `pred_func` function to square patches of the image, and overlap the predictions to merge them smoothly. See 6th, 7th and 8th idea here: http://blog.kaggle.com/2017/05/09/dstl-satellite-...
def check_response_validity(response,problem_list): resp = response.copy() assigned_assets = [] n_correct_responses = 0 response_magnitude = 0 for problem in problem_list: prob_type = problem.name action = problem.action response_magnitude += problem.severity for _ in...
The main task of the code is to calculate the total cost of schedule violations by summing penalties for validity, time, and efficiency violations. It combines hard constraints (validity + time violations) multiplied by a penalty and soft constraints (efficiency violations), returning the total cost along with the tota...
def getCost(response, problem_list): """ Calculates the total cost of the various violations in the given schedule ... :param response: a list of binary values describing the given asset response :param problem_list: a list of objects of class Problem() :return: the calculated cost """ ...
def count(a: list) -> int: """ Return count number of items in a list. :param a: numbers list """ if len(a) == 0: return 0 else: return 1 + count(a[1:]) def quicksort(a: list) -> list: """ Fast quick sort. Return sorted list. :param a: numbers list """ if c...
The function `get_median` calculates the median of a list of numbers, whether ordered or unordered. It first determines the length of the list, sorts it using quicksort, and then computes the median from the sorted list. The median is the middle value for an odd-length list or the average of the two central values for ...
def get_median(a: list) -> float: """ Return median value for ordered or unordered numbers list. :param a: numbers list """ n = count(a) s = quicksort(a) return get_median_custom(s, n)
def app_login(): user = input('Enter UserID: ') password = input('Enter Password: ') return login(user, password) def app_add_user(): user = get_unique_user_id() passwd = input("Enter Secure Password: ") return adduser(userid=user, hashed_password=hashlib.sha1(passwd.encode()).hexdigest()) def ...
The code implements a command-line interface for a travel management system, allowing users to log in, register, add/cancel trips, view trip details, and exit. It maintains user authentication state and routes commands to corresponding functions while enforcing login requirements for trip-related operations.
def run(): c_user = None no_exit = True help_text = """ ------------------TravelManage----------------- Command Description h Show this help command n Add new Trip (Opens New Trip) l Login to use...
def generate_test(N): # Discretized pendulum tracking Q = np.zeros((N,2,2)) R = np.zeros((N,1,1)) q = 0.1 t = 0.01 Q0 = np.array([[q*t*t*t/3,q*t*t/2],[q*t*t/2,q*t]]) R0 = np.array([[1]]) for i in range(N): Q[i] = Q0 R[i] = R0 m0 = np.zeros((2,1)) P0 = np.zeros((2,...
The code runs 20 trials of a test, generating data and models each time. It calculates the RMSE (Root Mean Square Error) for two models (m and m2) against the same data (x), accumulating errors. After averaging the errors across trials, it plots the results and prints the final RMSE of the first model. The task evaluat...
def test(): N = 1000 error1 = 0 error2 = 0 for i in range(20): m,c,x,y,m2,c2 = generate_test(N) error1 = error1 + rmse(m,x) error2 = error2 + rmse(m2,x) plot_data(m,c,x,y,m2,c2,error1/20,error2/20) print(rmse(m,x))
def generate_test(T,N): # Discretized pendulum tracking d = 2 Q = np.zeros((T,2,2)) R = np.zeros((T,1,1)) q = 0.1 t = 0.01 Q0 = np.array([[q*t*t*t/3,q*t*t/2],[q*t*t/2,q*t]]) R0 = np.array([[1]]) for i in range(T): Q[i] = Q0 R[i] = R0 m0 = np.zeros((d,1)) P0 = ...
The code's main task is to generate synthetic test data (x, y, m, v) using `generate_test`, compute the Root Mean Squared Error (RMSE) between model predictions `m` and actual values `x`, then visualize the data, model outputs, and error metrics via `plot_data`. It simulates a scenario where a model's performance is ev...
def test(): T = 1000 N = 600 x,y,m,v = generate_test(T,N) error = rmse(m,x) plot_data(x,y,m,v,error)
def is_cell_free(self, x: int, y: int) -> bool: if x < 0 or x >= self.__width: return False elif y < 0 or y >= self.__height: return False else: for _figure in self.__figures: for _cell in _figure.get_cells_with_main(): if _...
This function attempts to rotate a falling figure in a grid. It checks if the next rotation state would collide with existing cells. If conflicts arise, it tries to resolve them recursively; if unresolved, it returns None. If valid, it applies the rotation.
def try_figure_rotate(self): future_state_number = self.__falling_figure.get_state_number() + 1 future_state = self.__falling_figure.get_state(future_state_number) main_cell = self.__falling_figure.get_main_cell().get_coords() for row in range(len(future_state)): for column ...
def synchronize_cell(self, cell): points = self.grid_to_pixels_cell(cell.get_x(), cell.get_y()) self.canvas().coords(cell.get_number(), points[0].x, points[0].y, points[1].x, points[1].y) def grid_to_pixels_cell(self, x: int, y: int): vec = [self.grid_to_pixels_point(x, y), self.grid_to_pixels_p...
The main task of the code is to refresh the visual display of falling figures in a game by synchronizing existing cells, creating new ones for uncreated cells, removing deleted cells, calculating the vertical position for the falling figure's next state, and updating level/score text. It handles dynamic rendering, move...
def refresh_figures(self): for _figure in controller.controller.grid().get_figures_with_falling(): for cell in _figure.get_cells_with_main(): if cell.is_created(): self.synchronize_cell(cell) else: points = self.grid_to_pixels_c...
def rot(theta): return np.array([[np.cos(theta), -np.sin(theta)],[np.sin(theta), np.cos(theta)]]) def gen_hole_profile(width=1, height=1, resolution=1000): side_x = np.linspace(-width/2, width/2, int(width*resolution)) side_y = np.linspace(0, height, int(height*resolution)) hole_x = np.concatenate([side...
This code animates the visualization of a peg and hole interaction, displaying contact points and force vectors in both inertial and peg frames. It clears and redraws two subplots for each frame, plotting geometric profiles, contact locations, and directional arrows. The inertial frame shows the scenario with gravity v...
def animate(i): y_basis = rot(-theta[i])@np.array([0,-1]) resolution = 10000 ax = axs[0] hole = gen_hole_profile(resolution=resolution) peg, peg_corners, _, _ = gen_peg_profile(resolution=resolution) scenario = gen_scenario(peg, hole, peg_corners, theta[i], resolution, mu...
def load_from_files(self, files: List[str]) -> Dict[str, Any]: # Keep this method as staticmethod, so it can be used from interactive environments config: Dict[str, Any] = {} if not files: return deepcopy(constants.MINIMAL_CONFIG) # We expect here a list of config filename...
The main task of the code is to load and process a bot's configuration by reading files from sys.argv arguments, processing logging, run mode, and optimization settings, verifying exchange support, resolving trading pairs, and returning a structured configuration dictionary with an original config copy for reference.
def load_config(self) -> Dict[str, Any]: """ Extract information for sys.argv and load the bot configuration :return: Configuration dictionary """ # Load all configs config: Dict[str, Any] = self.load_from_files(self.args.get("config", [])) # Keep a copy of the o...
def read_probe_tsv(self, file): """read in probe tsv file file structure ALKintron19_1 CTGCAGCTCCATCTGCATGGCTTGCAGCTCCTGGTGCTTC ALKintron19_2 CGGCGGTACACTGCAGGTGGGTGGTCAGCTGCAACATGGC """ probe_dict = {} with open(file, 'r') as fr: fr.readli...
This code initializes a class to process BAM files by categorizing reads based on probe data. It reads input paths, probe TSV/BED files, and opens BAM files for output. It sets thresholds for sequence length and alignment quality, processes reads to classify them as on-target, off-target, supplementary, or unmapped, an...
def __init__(self, **kwargs): self.raw_input_seq_path = kwargs.get('input_seq_path') self.raw_output_dir = kwargs.get('output_dir') self.raw_probes_tsv_path = kwargs.get('probe_tsv_path') self.raw_probes_bed_path = kwargs.get('probe_bed_path') self.raw_paired= kwargs.get('paired_...
def not_private(name): return not (name.startswith('_') and (not name.startswith('__'))) def unwrap_assign(node, names): "inplace, recursive update of list of names" if isinstance(node, _ast.Name) : names.append(node.id) elif isinstance(node, _ast.Starred) : names.append(node.value.id) elif isi...
This function extracts non-private function, class, and variable names from source code using AST parsing. It handles syntax errors, processes assignments/annotations, and enforces rules for reserved names like '_all_', which triggers validation and special name collection logic.
def find_names(code:str, st:StackTrace) -> (bool, set): "Find all function, class and variable names in the given source code." try: tree = ast.parse(code).body except SyntaxError as e: return st.report_caught_syntax_error(e), None names = set() for node in tree: if isinstance(node, (_ast.Fu...
def async_load_notebooks(Directory:Path, Recurse:bool=True) -> Iterator[NotebookStruct]: "Crawl for notebooks in the `path` directory, and load in a background thread." for FilePath in crawl_directory(Directory, Recurse): yield read_notebook(FilePath) def parse_all(Notebooks:Iterator[NotebookStruct], st:StackTr...
The function `convert2py` converts Jupyter `.ipynb` files to Python `.py` files by loading, parsing, merging, and writing them. It handles errors during parsing, merging, or writing, reporting issues and halting if critical failures occur. Success is tracked, and statistics are reported if enabled. The output includes ...
def convert2py(RecursiveFileSearch:bool=True, st:StackTrace=None) -> Tuple[bool, dict, dict]: "Load, Parse, Merge, and Write .ipynb files to .py files." Success:bool = True config = Config() # NOTE: Verify that a settings.ini file exists. Context = {} # NOTE: LOAD Notebooks =...
def from_string_cell(source:str, st:StackTrace) -> (bool, str): "Take a cells source code containing a single string and return the content of that string." try: tree = ast.parse(source).body except SyntaxError as e: return st.report_caught_syntax_error(e), None if len(tree) == 1: node = tree[0]...
This function exports a notebook cell to a .py file by validating parameters, converting source code, determining export targets, and configuring an ExportUnitStruct with the processed code and settings. It checks mutual exclusivity of 'to'/'to_path' flags, resolves export paths, handles internal/external export logic,...
def kw_export(Notebook:NotebookStruct, cell_info:CellInfoStruct, Comment:CommentStruct, st:StackTrace) -> bool: "This cell will be exported from the notebook to a .py file." success:bool = True result = Comment.ParsingResult is_set = Comment.IsSet export_unit = ExportUnitStruct(cell_info) if (i...
def get_next_argument(args:list, name:str, cursor:int, suppress_error:bool=False) -> (bool, int, str): "Gets the next argument from the list.\nReturns success, the cursor, and the next argument" cursor_1 = cursor + 1 try: return True, cursor_1, args[cursor_1] except IndexError: if not suppress_e...
This function parses input arguments based on the specified `arg_type`, updates the `result` dictionary with the parsed value under the corresponding `arg_name`, and modifies the `state` dictionary (including cursor position and error reporting). It handles type-specific parsing for strings, booleans, integers, floats,...
def handle_one_argument(result:dict, state:dict, arg_type:type, arg_default:object) -> bool: "Parse the input args based on arg_type, and set arg_name in result to that value." # NOTE: 'state' and 'result' are references not values, and modified from here. args = state['args'] arg_name = state['name...
def report_error(err:Exception): if arg_parse_SILENT: pass elif arg_parse_RAISE_ERROR : raise err elif arg_parse_REPORT_ERROR: print(f'[{err.__class__.__name__}]: {err}') def typify(type_or_value:object) -> (type, object): """Takes a type or a value. Returns a tuple of the type (or type of the val...
This function parses command-line arguments according to a predefined command structure, validating each argument's type and ensuring required parameters are set. It processes arguments starting with '-', maps them to command keys, handles errors like invalid arguments or duplicates, and returns parsed values along wit...
def parse_arguments(command:dict, args:[str]) -> (bool, dict, dict): "Finds, casts, and returns values from command, in the given comment." # TODO: check that the type of all commands is supported ahead of time? # TODO: handle quoted arguments? # TODO: support command aliases? if isinstance(args...
def display_game_board(): print("\n") print(game_board[0] + " | " + game_board[1] + " | " + game_board[2] + " 1 | 2 | 3") print("---------") print(game_board[3] + " | " + game_board[4] + " | " + game_board[5] + " 4 | 5 | 6") print("---------") print(game_board[6] + " | " + game_board[7] ...
The code defines a function `play_game()` that initializes a game loop to handle player turns, check for game-over conditions, and determine the winner. It displays the game board, alternates between players, and ends when a player wins or the game draws, announcing the result accordingly.
def play_game(): display_game_board() while game_still_on: handle_turn(current_player) check_if_game_over() flip_player() if winner == "X" or winner == "O": print(f"Congratulations {winner} you won!") elif winner == None: print("Game draw.")
def __renderTitle(self): self.root.title( f"Fish Generation : {self.GENERATION} | Average completion time : {self.deltaTime}") def simulateSwarm(self): for _ in range(int(self.maxLifeSpan.get())): for fish in self.fishSwarm: if fish.finished: c...
The code's main task is to execute a simulation cycle by rendering a title, initializing a time delta, simulating swarm behavior, handling mating/reproduction, and incrementing the generation counter, likely part of an evolutionary algorithm or swarm intelligence simulation.
def run(self): self.__renderTitle() self.deltaTime = 0 self.simulateSwarm() self.mating() self.GENERATION += 1
def clear(self): self.canvas.delete(self.visual) def __calculate(self): # x directions: positive number right, negative number left # y directions: positive numver down, negative number up # drift: left or right # velocity: up or down self.acceleration += self.DNA[self.li...
The code's main task is to update and render an object's state when it is alive and not finished. It clears previous data, calculates new state, renders it visually, and increments a lifecycle counter. The commented-out lines suggest a potential drift mechanism was considered but disabled.
def draw(self): if self.alive and not self.finished: # a_list = [0, 5] # distribution = [.6, .4] # self.drift = random.choices(a_list, distribution)[0] self.clear() self.__calculate() self.__render() self.lifecircle += 1
def create_df(): df = pd.read_csv("posters_dataset.csv", sep="\t") df = df.dropna() df = df[df["file_exists"] == True] df = df[:10] return df def build_csv(df: pd.DataFrame): print("Building CSV...") df.apply(lambda row: write_features_to_row(row), axis=1) def output_to_console(filepath: str...
The code processes command-line arguments to either generate a TSV file from a CSV dataset or perform image prediction. If a CSV path is provided, it creates and exports a DataFrame. If an image path is given, it outputs predictions to the console. Otherwise, it randomly selects an image from a directory for prediction...
def main(args: argparse.Namespace): if args.csv_filepath: df = create_df() build_csv(df) df.to_csv("metadata/dataset.features.tsv", sep="\t", index=False) elif args.img_filepath: output_to_console(args.img_filepath, predict=True) else: output_to_console( s...
def tokenize_and_explode(args, df): """Tokenizes the words/labels and creates a row for each token Args: df (DataFrame): dataframe of labels tokenizer (tokenizer): from transformers Returns: DataFrame: a new dataframe object with the words tokenized """ df['token'] = df.wor...
The function generates token embeddings and predictions for each conversation in a dataframe using a specified model. It tokenizes input, processes model outputs to extract embeddings and logits, computes top predictions and probabilities, and adds these results along with surprise and entropy metrics to the dataframe....
def generate_embeddings_with_context(args, df): df = tokenize_and_explode(args, df) if 'gpt2' in args.embedding_type: args.tokenizer.pad_token = args.tokenizer.eos_token final_embeddings = [] final_top1_word = [] final_top1_prob = [] final_true_y_prob = [] for conversation in df.conv...
def extract_conversation_contents(CONFIG, conversation): """Return labels (lines) from conversation text Args: file ([type]): [description] ex_words ([type]): [description] Returns: list: list of lists with the following contents in that order ['word', 'onset', 'off...
The function `combine_podcast_datums` integrates transcript, cloze, and conversation data into a unified podcast label dataset. It extracts conversation content, aligns data at two levels using configuration parameters, and returns a structured DataFrame. The primary task is to merge and align multi-source data for pod...
def combine_podcast_datums(CONFIG, conversation): """[summary] Note: This function was exclusively written to handle podcast label creation which is a combination of 1. transcript 2. cloze datum 3. conversation datum Args: CONFIG ([type]): [description] conversation ([type]...
def create_sentence(args, conversation): """[summary] Args: labels ([type]): [description] Returns: [type]: [description] """ convo_sections = split_convo_to_sections(conversation) conversation = process_sections(args, convo_sections) return conversation def shift_onsets(co...
The function `process_labels` adjusts label onsets to align with the length of a stitched signal and prepares labels for processing. It modifies `stitch_index`, shifts label onsets based on conversation start times, adds conversation IDs and names, and indexes sentences sequentially. The processed labels are consolidat...
def process_labels(args, stitch_index, labels, conversations): """Adjust label onsets to account for stitched signal length. Also perform stemming on the labels. Args: trimmed_stitch_index (list): stitch indices of trimmed signal labels (list): of tuples (word, speaker, onset, offset, accur...
def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument('--model-name', type=str, default='bert-large-uncased-whole-word-masking') parser.add_argument('--embedding-type', type=str, default='glove') parser.add_argument('--context-lengt...
The main task of the code is to generate embeddings for conversational utterances based on specified models (e.g., GLOVE, GPT2, BERT, Blenderbot) and parameters, filter conversation data, and save the resulting embeddings and processed data to a pickle file. It handles different embedding types, context-aware generatio...
def main(): args = parse_arguments() select_tokenizer_and_model(args) setup_environ(args) utterance_df = load_pickle(args) utterance_df = select_conversation(args, utterance_df) if len(utterance_df) == 0: print("Conversation data does not exist") return embeddings = None ...
def process_labels(args, stitch_index, labels, conversations): """Adjust label onsets to account for stitched signal length. Also perform stemming on the labels. Args: trimmed_stitch_index (list): stitch indices of trimmed signal labels (list): of tuples (word, speaker, onset, offset, accur...
The function processes labels and associated data to generate a structured DataFrame, enhances it with linguistic features like word frequency, lemmatization, and stemming, then serializes the result into a pickle file for storage, using parameters to define the output name and structure.
def create_labels_pickles(args, stitch_index, labels, convo_labels_size, convs, label_str=None): labels_df = process_labels(args, stitch_index, labels, convs) labels_df = create_prod...
def __inp(self, n = 3): lower_words = self.query.lower().split() is_word = [i in self.vocab for i in lower_words] word_list = [] names = [] for idx, i in enumerate(lower_words): if is_word[idx]: word_list.append(i) else: nam...
The function `recommendTopThree` generates a ranked list of top 3 business recommendations by combining direct match scores, distance from user location, and venue capacity. It first checks if existing matches (`self.matches`) are fewer than 3, then supplements with additional data via `__inp()`. It calculates normaliz...
def recommendTopThree(self): if self.l < 3: arr = [] for i in range(self.l): arr.append(json.loads(self.matches.iloc[i].to_json())) resp = self.__inp(3 - self.l) for i in resp['businesses']: arr.append(self.format(i)) ...
def haversideND(self, lon1, lat1, lon2, lat2, meters = True): assert len(lon1) == len(lat1), "Longitudes and latitudes should have same length" lst = [] for i in range(len(lon1)): lst.append(self.haversine(lon1[i], lat1[i], lon2, lat2, meters)) return lst def __searchAndFilte...
This code initializes a preference search by filtering and ranking places based on a user's query and location. It validates inputs, loads location data from a database, calculates distances using the Haversine formula, filters matches, computes scores combining distance, capacity, and relevance, and stores top 3 resul...
def __init__(self, query, latitude, longitude): """ Initializes a Preference search. query -- User's search latitude -- User's Latitude longitude -- User's Longitude """ assert type(query) == str, "Query should be a string" assert type(latitude) == float,...
def get_tile(self, x, y): if x < 0 or y < 0 or x >= self.width or y >= self.height: return 0 return self.tiles[x + y * self.width] def get_uv_from_tile_id(tile_id, columns): return vec2_t(tile_id % columns, math.floor(tile_id / columns)) def mesh_block(pos, omitted_blocks, uv): offset_tangent_bit...
The code generates 3D mesh vertices for a tile-based structure by iterating over a grid. For each tile, it retrieves UV coordinates, checks for block data in a dictionary, and constructs vertices using mesh functions. Blocks are processed with adjusted Z-positions, while tiles without block data are handled separately....
def build_vertices(self): vertices = [] for y in range(self.width): for x in range(self.height): tile = self.get_tile(x, y) - 1 pos = vec3_t(x, y, 0) tile_uv = get_uv_from_tile_id(tile, self.columns) if tile in self.tiledict: blocks = self.t...
def emit_i32(f, i32): f.write(struct.pack('i', i32)) def emit_entity_t(f, entity): emit_i32(f, entity.entity_id) emit_vec2_t(f, entity.pos) def emit_mesh_vertex_t(f, vertex): emit_vec3_t(f, vertex.pos) emit_vec2_t(f, vertex.uv) def emit_lump(f, fileofs, filelen): emit_i32(f, fileofs) emit_i32(f, filelen)
This function serializes a worldmap object into a binary file at the specified path. It writes tiles, entities, and vertices data to separate sections, records their file offsets and lengths, then writes a header containing version, map dimensions, and lump metadata for each data section to enable structured file acces...
def map_save(worldmap, path): with open(path, "wb") as f: f.seek(SIZEOF_HEADER) tiles_fileofs = f.tell() for tile in worldmap.tiles: emit_i32(f, tile) tiles_filelen = f.tell() - tiles_fileofs entities_fileofs = f.tell() for entity in worldmap.build_entities(): emit_entity...
def _try_to_flip(self): if random.random() < self.flip_triangle_rate: self._flip() def _set_ideal_spot(self, new_points): if self.no_partners == 2: self.ideal_spot = self._get_ideal_spot_two_partners( new_points) else: # TODO ra...
The code's main task is to move an object to a valid "ideal spot" based on new points, ensuring the spot is valid by flipping, adjusting, or randomly selecting it if initial attempts fail. It uses iterative checks and fallback strategies like flipping the object, fixing the spot, or generating a random spot to resolve ...
def move(self, new_points): self._try_to_flip() self._set_ideal_spot(new_points) if self.verbose: print(f"\nID: {self.num}") print(f"True Ideal: {self.ideal_spot}") # Makes it so ideal spot is a valid spot # While moving to the ideal spot, points may mo...
def create_points(no_points=15, no_partners=2, dim=2): points = [] for i in range(0, no_points): point = Point(num=i) point.set_coord(point.get_new_coord(dim)) points.append(point) assign_partners(points, no_partners) return points def draw_points(points, colors, label=False): ...
The code simulates the movement of points towards convergence by iteratively adjusting their positions, visualizing their trajectories with matplotlib, and checking for loop detection. It initializes points, updates their coordinates in a loop, draws them with color-coded paths, and saves an animation if convergence is...
def main(): # With current config, it doesn't converge or loop (within 5500 rounds) seed = 8 random.seed(seed) no_points = 5 no_partners = 2 points = create_points(no_points, no_partners) colors = cm.rainbow(np.linspace(0, 1, len(points))) fig, ax = plt.subplots(1, 1, figsize=(12, 10)...
def get_x(s, i): num_bodies = get_n_bodies(s) return s[num_bodies + i] def get_m(s, i): return s[i] def get_r(s, i, j): p1 = get_position(s, i) p2 = get_position(s, j) r = np.linalg.norm(p2 - p1) return r
The function calculates the x-component of acceleration for body `i` due to gravitational interaction with body `j`, using the formula $ a = \frac{m_2 (x_2 - x_1)}{r^3} $, where $ m_2 $ is the mass of body `j`, $ x_1 $ and $ x_2 $ are positions of bodies `i` and `j`, and $ r $ is the distance between them.
def x_accel(s, i, j): x1 = get_x(s, i) x2 = get_x(s, j) m2 = get_m(s, j) r = get_r(s, i, j) return m2 * (x2 - x1) / (r) ** (3)
def get_y(s, i): num_bodies = get_n_bodies(s) return s[2 * num_bodies + i] def get_m(s, i): return s[i] def get_r(s, i, j): p1 = get_position(s, i) p2 = get_position(s, j) r = np.linalg.norm(p2 - p1) return r
This function calculates a value proportional to the acceleration component in the y-direction between two points, using their y-coordinates, the mass of the second point, and the cube of the distance between them. It returns the result of m2*(y2 - y1)/r³, where m2 is the mass of the second object, y1 and y2 are y-coor...
def y_accel(s, i, j): y1 = get_y(s, i) y2 = get_y(s, j) m2 = get_m(s, j) r = get_r(s, i, j) return m2 * (y2 - y1) / (r) ** (3)
def get_z(s, i): num_bodies = get_n_bodies(s) return s[3 * num_bodies + i] def get_m(s, i): return s[i] def get_r(s, i, j): p1 = get_position(s, i) p2 = get_position(s, j) r = np.linalg.norm(p2 - p1) return r
The function calculates the z-component of acceleration due to gravitational interaction between two masses, using their positions and the distance between them, following a formula akin to Newton's law of gravitation, returning the result as a scalar value.
def z_accel(s, i, j): z1 = get_z(s, i) z2 = get_z(s, j) m2 = get_m(s, j) r = get_r(s, i, j) return m2 * (z2 - z1) / (r) ** (3)