### Clone CodonTransformer repository and install requirements Source: https://github.com/adibvafa/codontransformer/blob/main/README.md Clones the CodonTransformer GitHub repository and installs its dependencies from requirements.txt. Takes about 10-30 seconds depending on already installed requirements. ```sh git clone https://github.com/adibvafa/CodonTransformer.git cd CodonTransformer pip install -r requirements.txt ``` -------------------------------- ### Install CodonTransformer via pip Source: https://github.com/adibvafa/codontransformer/blob/main/README.md Installs the CodonTransformer package from PyPI. Requires python>=3.9 and supports all major operating systems. ```sh pip install CodonTransformer ``` -------------------------------- ### Import dependencies and set device Source: https://github.com/adibvafa/codontransformer/blob/main/CodonTransformerDemo.ipynb Imports required libraries and sets the computation device to CUDA if available, otherwise CPU. Used at the start of the notebook. ```python import warnings from tqdm import tqdm import pandas as pd import torch from transformers import AutoTokenizer, BigBirdForMaskedLM from CodonTransformer.CodonJupyter import ( UserContainer, display_organism_dropdown, display_protein_input, format_model_output, ) from CodonTransformer.CodonPrediction import predict_dna_sequence warnings.filterwarnings("ignore") DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") ``` -------------------------------- ### Predict DNA sequence with CodonTransformer Source: https://github.com/adibvafa/codontransformer/blob/main/README.md Loads the CodonTransformer model and tokenizer, then predicts a DNA sequence for a given protein and organism. Requires torch, transformers, and the CodonTransformer package; uses CUDA when available. The example prints the formatted output via format_model_output. ```python import torch from transformers import AutoTokenizer, BigBirdForMaskedLM from CodonTransformer.CodonPrediction import predict_dna_sequence from CodonTransformer.CodonJupyter import format_model_output device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Load model and tokenizer tokenizer = AutoTokenizer.from_pretrained("adibvafa/CodonTransformer") model = BigBirdForMaskedLM.from_pretrained("adibvafa/CodonTransformer").to(device) # Set your input data protein = "MALWMRLLPLLALLALWGPDPAAAFVNQHLCGSHLVEALYLVCGERGFFYTPKTRREAEDLQVGQVELGG" organism = "Escherichia coli general" # Predict with CodonTransformer output = predict_dna_sequence( protein=protein, organism=organism, device=device, tokenizer=tokenizer, model=model, attention_type="original_full", deterministic=True ) print(format_model_output(output)) ``` -------------------------------- ### Load model and tokenizer Source: https://github.com/adibvafa/codontransformer/blob/main/CodonTransformerDemo.ipynb Loads the CodonTransformer tokenizer and BigBirdForMaskedLM model from the Hugging Face hub and moves the model to the device. ```python # Load model and tokenizer tokenizer = AutoTokenizer.from_pretrained("adibvafa/CodonTransformer") model = BigBirdForMaskedLM.from_pretrained("adibvafa/CodonTransformer").to(DEVICE) ``` -------------------------------- ### Single sequence optimization - user input Source: https://github.com/adibvafa/codontransformer/blob/main/CodonTransformerDemo.ipynb Creates a UserContainer and displays input widgets for protein sequence and organism selection. The protein sequence should end with '*', '_', or an amino acid. ```python # Sample: MALWMRLLPLLALLALWGPDPAAAFVNQHLCGSHLVEALYLVCGERGFFYTPKTRREAEDLQVGQVELGG, Homo sapiens user = UserContainer() display_protein_input(user) display_organism_dropdown(user) ``` -------------------------------- ### Multiple sequences - load dataset Source: https://github.com/adibvafa/codontransformer/blob/main/CodonTransformerDemo.ipynb Reads a CSV file with columns 'protein_sequence' and 'organism' (other columns allowed) and initializes a 'predicted_dna' column. The dataset_path and output_path must be updated to actual paths. ```python # Update with the actual path to your dataset dataset_path = "demo/sample_dataset.csv" output_path = "demo/sample_predictions.csv" dataset = pd.read_csv(dataset_path, index_col=0) dataset["predicted_dna"] = None dataset.head() ``` -------------------------------- ### display_protein_input(container: UserContainer) -> None Source: https://github.com/adibvafa/codontransformer/blob/main/README.md Displays a widget for entering a protein sequence and saves the entered sequence to the container. ```APIDOC ## display_protein_input(container: UserContainer) -> None ### Description Display a widget for entering a protein sequence and saves the entered sequence to the container. ### Parameters - **container** (UserContainer) - Required - The container to store the entered protein sequence. ### Returns None ``` -------------------------------- ### Configure ambiguous amino acid handling with ProteinConfig Source: https://github.com/adibvafa/codontransformer/blob/main/README.md Configures protein preprocessing by setting ambiguous amino acid behavior to 'standardize_random' and overriding the mapping for 'X' to ['A', 'G', 'S']. The default behavior is 'standardize_random', which randomly selects an amino acid from the mapping list; other options are 'standardize_deterministic' (first amino acid) and 'raise_error' (treats ambiguous amino acids as invalid). ```python from CodonTransformer.CodonUtils import ProteinConfig # Configure protein preprocessing config = ProteinConfig() config.set('ambiguous_aminoacid_behavior', 'standardize_random') config.set('ambiguous_aminoacid_map_override', {'X': ['A', 'G', 'S']}) # Run CodonTransformer ... ``` -------------------------------- ### display_organism_dropdown(organism2id: Dict[str, int], container: UserContainer) -> None Source: https://github.com/adibvafa/codontransformer/blob/main/README.md Displays a dropdown widget for selecting an organism from a list and updates the organism ID in the provided container. ```APIDOC ## display_organism_dropdown(organism2id: Dict[str, int], container: UserContainer) -> None ### Description Display a dropdown widget for selecting an organism from a list and updates the organism ID in the provided container. ### Parameters - **organism2id** (Dict[str, int]) - Required - A dictionary mapping organism names to their IDs. - **container** (UserContainer) - Required - The container to store the selected organism ID. ### Returns None ``` -------------------------------- ### UserContainer Source: https://github.com/adibvafa/codontransformer/blob/main/README.md A container class to store user inputs for organism and protein sequence. It has attributes for the selected organism ID and the input protein sequence. ```APIDOC ## UserContainer ### Description A container class to store user inputs for organism and protein sequence. ### Attributes - **organism** (int) - The selected organism ID - **protein** (str) - The input protein sequence ``` -------------------------------- ### Single sequence optimization - predict and display Source: https://github.com/adibvafa/codontransformer/blob/main/CodonTransformerDemo.ipynb Calls predict_dna_sequence with the user-provided protein and organism, using deterministic prediction by default. The temperature can be set for non-deterministic prediction. Prints the formatted model output. ```python output = predict_dna_sequence( protein=user.protein, organism=user.organism, device=DEVICE, tokenizer=tokenizer, model=model, attention_type="original_full", deterministic=True, # Can set temperature for non deterministic prediction ) print(format_model_output(output)) ``` -------------------------------- ### Multiple sequences - predict and save Source: https://github.com/adibvafa/codontransformer/blob/main/CodonTransformerDemo.ipynb Iterates over each row in the dataset, predicts the DNA sequence using predict_dna_sequence, stores the result in the 'predicted_dna' column, and saves the updated dataset to the output CSV. ```python for index, data in tqdm( dataset.iterrows(), desc=f"CodonTransformer Predicting", unit=" Sequences", total=dataset.shape[0], ): outputs = predict_dna_sequence( protein=data["protein_sequence"], organism=data["organism"], device=DEVICE, tokenizer_object=tokenizer, model_object=model, ) dataset.loc[index, "predicted_dna"] = outputs.predicted_dna dataset.to_csv(output_path) dataset.head() ``` -------------------------------- ### format_model_output(output: DNASequencePrediction) -> str Source: https://github.com/adibvafa/codontransformer/blob/main/README.md Formats the DNA sequence prediction output in a visually appealing and easy-to-read manner. Takes a DNASequencePrediction object and returns a formatted string. ```APIDOC ## format_model_output(output: DNASequencePrediction) -> str ### Description Format the DNA sequence prediction output in a visually appealing and easy-to-read manner. ### Parameters - **output** (DNASequencePrediction) - Required - The DNA sequence prediction object to format. ### Returns - **str** - The formatted string representation of the output. ``` -------------------------------- ### predict_dna_sequence Source: https://github.com/adibvafa/codontransformer/blob/main/README.md Predicts DNA sequence(s) from a given protein sequence and organism. Supports deterministic and stochastic decoding with configurable sampling parameters. ```APIDOC ## predict_dna_sequence ### Description Predicts DNA sequence(s) from a given protein sequence and organism. Supports deterministic and stochastic decoding with configurable sampling parameters. ### Parameters - **protein** (`str`) - Required - Input protein sequence - **organism** (`Union[int, str]`) - Required - Organism ID (integer) or name (string) (e.g., "Escherichia coli general") - **device** (`torch.device`) - Required - PyTorch device object specifying whether to run on CPU or GPU - **tokenizer** (`Union[str, PreTrainedTokenizerFast, None]`) - Optional, default `None` - Either a file path to load tokenizer from, a pre-loaded tokenizer object, or None to load from HuggingFace's "adibvafa/CodonTransformer" - **model** (`Union[str, torch.nn.Module, None]`) - Optional, default `None` - Either a file path to load model from, a pre-loaded model object, or None to load from HuggingFace's "adibvafa/CodonTransformer" - **attention_type** (`str`) - Optional, default `"original_full"` - Type of attention mechanism to use in model - 'block_sparse' for memory efficient or 'original_full' for standard attention - **deterministic** (`bool`) - Optional, default `True` - If True, uses deterministic decoding (picks most likely tokens). If False, samples tokens based on probabilities adjusted by temperature - **temperature** (`float`) - Optional, default `0.2` - Controls randomness in non-deterministic mode. Lower values (0.2) are conservative and pick high probability tokens, while higher values (0.8) allow more diversity. Must be positive - **top_p** (`float`) - Optional, default `0.95` - Nucleus sampling threshold - only tokens with cumulative probability up to this value are considered. Balances diversity and quality of predictions. Must be between 0 and 1 - **num_sequences** (`int`) - Optional, default `1` - Number of different DNA sequences to generate. Only works when deterministic=False. Each sequence will be sampled based on the temperature and top_p parameters. Must be positive - **match_protein** (`bool`) - Optional, default `False` - Constrains predictions to only use codons that translate back to the exact input protein sequence. Only recommended when using high temperatures or error prone input proteins (e.g. not starting with methionine or having numerous repetitions) ### Returns `Union[DNASequencePrediction, List[DNASequencePrediction]]` containing predicted DNA sequence(s) and metadata. ``` -------------------------------- ### predict_dna_sequence Source: https://github.com/adibvafa/codontransformer/blob/main/README.md Predicts the DNA sequence for a given protein using the CodonTransformer model. This function is the primary entry point for sequence prediction. ```APIDOC ## predict_dna_sequence(protein: str, organism: Union[int, str], device: torch.device, tokenizer: Union[str, PreTrainedTokenizerFast], model: Union[str, torch.nn.Module], attention_type: str = "original_full", deterministic: bool = True, temperature: float = 0.2, top_p: float = 0.95, num_sequences: int = 1, match_protein: bool = False) -> DNASequencePrediction ### Description Predict the DNA sequence for a given protein using the CodonTransformer model. ### Parameters - **protein** (str) - Required - The protein sequence to predict DNA for. - **organism** (Union[int, str]) - Required - The organism identifier (ID or name). - **device** (torch.device) - Required - The device to run the model on. - **tokenizer** (Union[str, PreTrainedTokenizerFast]) - Required - Tokenizer path or object. - **model** (Union[str, torch.nn.Module]) - Required - Model path or object. - **attention_type** (str) - Optional - Attention type, default "original_full". - **deterministic** (bool) - Optional - Whether to use deterministic sampling, default True. - **temperature** (float) - Optional - Sampling temperature, default 0.2. - **top_p** (float) - Optional - Nucleus sampling probability, default 0.95. - **num_sequences** (int) - Optional - Number of sequences to generate, default 1. - **match_protein** (bool) - Optional - Whether to ensure the predicted sequence matches the protein. ### Returns - **DNASequencePrediction** - The predicted DNA sequence(s) and associated data. ### Example ```python prediction = predict_dna_sequence("MKTIIALSYIFCLVFADYKDDDDK", organism=0, device=torch.device('cpu'), tokenizer="path/to/tokenizer", model="path/to/model") ``` ## sample_non_deterministic(logits, temperature, top_p) ### Description Samples token indices from logits using temperature scaling and nucleus (top-p) sampling. This function is used internally for non-deterministic sequence generation. ### Parameters - **logits** (torch.Tensor) - Required - Logits from the model output. - **temperature** (float) - Optional - Temperature for scaling logits (default: 0.2). - **top_p** (float) - Optional - Nucleus sampling probability threshold (default: 0.95). ### Returns - **List[int]** - List of sampled token indices. ## load_model ### Description Load a BigBirdForMaskedLM model from a file or checkpoint. ### Parameters - **path** (str) - Required - Path to the model file or checkpoint. - **device** (torch.device) - Optional - Device to load the model onto. Defaults to None (auto-detection). - **num_organisms** (int) - Optional - Number of organisms for model configuration. - **remove_prefix** (bool) - Optional - Whether to remove a prefix from state dict keys. Defaults to True. - **attention_type** (str) - Optional - Attention type for the model. Defaults to "original_full". ### Returns - **torch.nn.Module** - The loaded BigBirdForMaskedLM model. ## load_bigbird_config(num_organisms: int) -> BigBirdConfig ### Description Loads the configuration object used to train the BigBird transformer. ### Parameters - **num_organisms** (int) - Required - The number of organisms to configure the model for. ### Returns - **BigBirdConfig** - The configuration object for the BigBird transformer. ## create_model_from_checkpoint(checkpoint_dir: str, output_model_dir: str, num_organisms: int) -> None ### Description Saves a model to disk using a previous checkpoint. This function is useful for converting a checkpoint into a model file that can be loaded later. ### Parameters - **checkpoint_dir** (str) - Required - Directory containing the checkpoint files. - **output_model_dir** (str) - Required - Directory where the model will be saved. - **num_organisms** (int) - Required - Number of organisms used in the model configuration. ### Returns None ## load_tokenizer(tokenizer_path: str) -> PreTrainedTokenizerFast ### Description Creates and returns a tokenizer object from the given tokenizer path. ### Parameters - **tokenizer_path** (str) - Required - Path to the tokenizer file. ### Returns - **PreTrainedTokenizerFast** - The tokenizer object. ## tokenize(batch: List[Dict[str, Any]], tokenizer_path: str = "", tokenizer_object: Optional[PreTrainedTokenizerFast] = None, max_len: int = 2048) -> BatchEncoding ### Description Tokenizes sequences given a batch of input data. Accepts either a tokenizer path or a tokenizer object. ### Parameters - **batch** (List[Dict[str, Any]]) - Required - Batch of input data to tokenize. - **tokenizer_path** (str) - Optional - Path to the tokenizer file. - **tokenizer_object** (Optional[PreTrainedTokenizerFast]) - Optional - A tokenizer object to use instead of loading from path. - **max_len** (int) - Optional - Maximum sequence length for tokenization (default: 2048). ### Returns - **BatchEncoding** - The tokenized batch of input data. ## validate_and_convert_organism(organism: Union[int, str]) -> Tuple[int, str] ### Description Validates and converts the organism input to both ID and name. ### Parameters - **organism** (Union[int, str]) - Required - The organism identifier, either as an integer ID or a string name. ### Returns - **Tuple[int, str]** - A tuple containing the organism ID and name. ## get_high_frequency_choice_sequence(protein: str, codon_frequencies: Dict[str, Tuple[List[str], List[float]]]) -> str ### Description Return a DNA sequence optimized using the High Frequency Choice (HFC) approach. ### Parameters - **protein** (str) - Required - The protein sequence to optimize. - **codon_frequencies** (Dict[str, Tuple[List[str], List[float]]]) - Required - A dictionary mapping amino acids to codon lists and their frequencies. ### Returns - **str** - The optimized DNA sequence. ### Example ```python sequence = get_high_frequency_choice_sequence(protein, codon_frequencies) ``` ## precompute_most_frequent_codons(codon_frequencies: Dict[str, Tuple[List[str], List[float]]]) -> Dict[str, str] ### Description Precomputes the most frequent codon for each amino acid to speed up HFC optimization. ### Parameters - **codon_frequencies** (Dict[str, Tuple[List[str], List[float]]]) - Required - A dictionary mapping amino acids to a tuple of codon lists and their frequencies. ### Returns - **Dict[str, str]** - A dictionary mapping each amino acid to its most frequent codon. ## get_background_frequency_choice_sequence(protein: str, codon_frequencies: Dict[str, Tuple[List[str], List[float]]]) -> str ### Description Return a DNA sequence optimized using the Background Frequency Choice (BFC) approach. ### Parameters - **protein** (str) - Required - The protein sequence to optimize. - **codon_frequencies** (Dict[str, Tuple[List[str], List[float]]]) - Required - A dictionary mapping amino acids to codon lists and their frequencies. ### Returns - **str** - The optimized DNA sequence. ## precompute_cdf(codon_frequencies: Dict[str, Tuple[List[str], List[float]]]) -> Dict[str, Tuple[List[str], Any]] ### Description Precompute the cumulative distribution function (CDF) for each amino acid to enable efficient background frequency choice sampling. ### Parameters - **codon_frequencies** (Dict[str, Tuple[List[str], List[float]]]) - Required - A dictionary mapping amino acids to a tuple of codon lists and their frequencies. ### Returns - **Dict[str, Tuple[List[str], Any]]** - A dictionary mapping each amino acid to a tuple containing the list of codons and the precomputed CDF values. ## get_background_frequency_choice_sequence_optimized(protein: str, codon_frequencies: Dict[str, Tuple[List[str], List[float]]]) -> str ### Description An efficient implementation of the BFC approach, up to 8 times faster than the original. ### Parameters - **protein** (str) - Required - The protein sequence to optimize. - **codon_frequencies** (Dict[str, Tuple[List[str], List[float]]]) - Required - A dictionary mapping amino acids to a tuple of codon lists and their frequencies. ### Returns - **str** - The optimized DNA sequence using the BFC approach. ## get_uniform_random_choice_sequence(protein: str, codon_frequencies: Dict[str, Tuple[List[str], List[float]]]) -> str ### Description Return a DNA sequence optimized using the Uniform Random Choice (URC) approach. ### Parameters - **protein** (str) - Required - The protein sequence to optimize. - **codon_frequencies** (Dict[str, Tuple[List[str], List[float]]]) - Required - A dictionary mapping amino acids to a tuple of codon lists and their frequencies. ### Returns - **str** - The optimized DNA sequence. ## get_icor_prediction(input_seq: str, model_path: str, stop_symbol: str) -> str ### Description Return an optimized codon sequence for the given protein sequence using ICOR (Improving Codon Optimization with Recurrent Neural Networks). ### Parameters - **input_seq** (str) - Required - The protein sequence to optimize. - **model_path** (str) - Required - Path to the ICOR model. - **stop_symbol** (str) - Required - The stop symbol used in the sequence. ### Returns - **str** - The optimized codon sequence. ``` ```APIDOC ## predict_dna_sequence(protein: str, organism: Union[int, str], device: torch.device, tokenizer: Union[str, PreTrainedTokenizerFast], model: Union[str, torch.nn.Module], attention_type: str = "original_full", deterministic: bool = True, temperature: float = 0.2, top_p: float = 0.95, num_sequences: int = 1, match_protein: bool = False) -> DNASequencePrediction ### Description Predict the DNA sequence for a given protein using the CodonTransformer model. ### Parameters - **protein** (str) - Required - The protein sequence to predict DNA for. - **organism** (Union[int, str]) - Required - The organism identifier (ID or name). - **device** (torch.device) - Required - The device to run the model on. - **tokenizer** (Union[str, PreTrainedTokenizerFast]) - Required - Tokenizer path or object. - **model** (Union[str, torch.nn.Module]) - Required - Model path or object. - **attention_type** (str) - Optional - Attention type, default ```