### Test Installation Source: https://github.com/google-deepmind/alphamissense/blob/main/README.md Runs the installation test script to verify the setup. ```bash venv/bin/python test/test_installation.py ``` -------------------------------- ### Setup Python Environment Source: https://github.com/google-deepmind/alphamissense/blob/main/README.md Sets up a Python virtual environment and installs project dependencies. ```bash python3 -m venv ./venv virtualenv/bin/pip install -r requirements.txt virtualenv/bin/pip install -e . ``` -------------------------------- ### Install Dependencies Source: https://github.com/google-deepmind/alphamissense/blob/main/README.md Installs necessary system dependencies for AlphaMissense using apt. ```bash sudo apt install python3.11-venv aria2 hmmer ``` -------------------------------- ### AlphaMissense Installation and Dependencies Source: https://context7.com/google-deepmind/alphamissense/llms.txt This bash script outlines the necessary system dependencies and steps to clone the AlphaMissense repository, set up a virtual environment, and install the project and its requirements. ```bash # 1. System dependencies sudo apt install python3.11-venv aria2 hmmer # 2. Clone and enter git clone https://github.com/deepmind/alphamissense.git cd alphamissense # 3. Virtual environment python3 -m venv ./venv virtualenv/bin/pip install -r requirements.txt virtualenv/bin/pip install -e . ``` -------------------------------- ### Verify AlphaMissense Installation Source: https://context7.com/google-deepmind/alphamissense/llms.txt This command verifies the AlphaMissense installation by running its built-in test suite, which skips the computationally intensive large database search. ```bash # 4. Verify installation (uses bundled test FASTA, skips large DB search) virtualenv/bin/python test/test_installation.py ``` -------------------------------- ### AlphaMissense End-to-End Workflow Example Source: https://context7.com/google-deepmind/alphamissense/llms.txt This Python script demonstrates the full end-to-end workflow of AlphaMissense, from setting up the data pipeline and processing a variant to running the model and interpreting the pathogenicity score. ```python # Full end-to-end workflow import jax import jax.numpy as jnp from alphamissense.data import pipeline_missense from alphamissense.model import config, modules_missense # --- Step 1: Build data pipeline --- pipeline = pipeline_missense.DataPipeline( jackhmmer_binary_path='/usr/bin/jackhmmer', protein_sequence_file='proteins.fasta', uniref90_database_path='/db/uniref90/uniref90.fasta', mgnify_database_path='/db/mgnify/mgy_clusters_2022_05.fa', small_bfd_database_path='/db/small_bfd/bfd-first_non_consensus_sequences.fasta', use_precomputed_msas=True, ) # --- Step 2: Process variant --- sample = pipeline.process( protein_id='P04637', # TP53 reference_aa='R', alternate_aa='H', position=175, # TP53 hotspot R175H msa_output_dir='/cache/P04637', ) # --- Step 3: Run model --- cfg = config.model_config() model_runner = modules_missense.RunModel(cfg, params=None) # pass loaded params here sample_jnp = jax.tree_map(jnp.asarray, sample) output = model_runner.predict(sample_jnp, random_seed=0) # --- Step 4: Interpret result --- score = float(output['logit_diff']['variant_pathogenicity']) print(f'TP53 R175H pathogenicity logit: {score:.4f}') # Expected: strong positive score (well-known pathogenic hotspot) ``` -------------------------------- ### Initialize Data Pipeline Source: https://github.com/google-deepmind/alphamissense/blob/main/README.md Initializes the AlphaMissense data pipeline with paths to genetic databases and the protein sequence file. Ensure 'DATABASES_DIR' is set and the FASTA file is provided. ```python from alphamissense.data import pipeline_missense protein_sequence_file = ... pipeline = pipeline_missense.DataPipeline( jackhmmer_binary_path=..., # Typically '/usr/bin/jackhmmer'. protein_sequence_file=protein_sequence_file, uniref90_database_path=DATABASES_DIR + '/uniref90/uniref90.fasta', mgnify_database_path=DATABASES_DIR + '/mgnify/mgy_clusters_2022_05.fa', small_bfd_database_path=DATABASES_DIR + '/small_bfd/bfd-first_non_consensus_sequences.fasta', ) sample = pipeline.process( protein_id=..., # Sequence identifier in the FASTA file. reference_aa=..., # Single capital letter, e.g. 'A'. alternate_aa=..., position=..., # Integer, note that the position is 1-based! msa_output_dir=msa_output_dir, ) ``` -------------------------------- ### Clone Repository Source: https://github.com/google-deepmind/alphamissense/blob/main/README.md Clones the AlphaMissense repository and navigates into the directory. ```bash git clone https://github.com/deepmind/alphamissense.git cd ./alphamissense ``` -------------------------------- ### config.model_config() Source: https://context7.com/google-deepmind/alphamissense/llms.txt Loads and returns the default model configuration as a ConfigDict. Allows customization for specific model variants like 'model_3' and adjustment of parameters like recycling iterations. ```APIDOC ## config.model_config() ### Description Loads model configuration. ### Method `config.model_config(name: str = None) -> ml_collections.ConfigDict` ### Parameters * **name** (str, optional) - Specifies the model variant. Use 'model_3' to enable the extra MSA stack. ### Request Example ```python from alphamissense.model import config # Default config (model 1 / model 2 — no extra MSA stack) cfg = config.model_config() # Model 3 variant — enables extra MSA stack cfg3 = config.model_config('model_3') assert cfg3.model.embeddings_and_evoformer.enable_extra_msa_stack is True # Adjust recycling iterations (useful for testing) cfg.model.num_recycle = 1 print('Evoformer blocks:', cfg.model.embeddings_and_evoformer.evoformer_num_block) # 48 print('MSA crop size: ', cfg.model.embeddings_and_evoformer.num_msa) # 256 print('Pair channel: ', cfg.model.embeddings_and_evoformer.pair_channel) # 128 ``` ### Response * **ml_collections.ConfigDict** - A configuration object for the AlphaMissense model. ``` -------------------------------- ### Instantiate and Apply AlphaMissense Model Source: https://github.com/google-deepmind/alphamissense/blob/main/README.md Instantiates the AlphaMissense model as a JAX module, initializes its parameters, and applies it to a processed sample. Requires 'jax', 'haiku', and the AlphaMissense model components. The output contains pathogenicity scores. ```python from alphamissense.model import config from alphamissense.model import modules_missense def _forward_fn(batch): model = modules_missense.AlphaMissense(config.model_config().model) return model(batch, is_training=False, return_representations=False) random_seed = 0 prng = jax.random.PRNGKey(random_seed) params = hk.transform(_forward_fn).init(prng, sample) apply = jax.jit(hk.transform(_forward_fn).apply) output = apply(params, prng, sample) ``` -------------------------------- ### Crop Sequences with `Cropper` Source: https://context7.com/google-deepmind/alphamissense/llms.txt Crops long sequences around a variant site and pads to a uniform size. It uses spatial cropping if atom positions are available, otherwise falls back to a centered contiguous window. ```python from alphamissense.data.pipeline_missense import Cropper import numpy as np cropper = Cropper(crop_size=256, msa_crop_size=2048) # `features` must contain: aatype, msa, msa_mask, deletion_matrix, # residue_index, seq_mask, variant_aatype, variant_mask, # all_atom_positions, all_atom_mask, variant_position, cluster_bias_mask features = cropper.crop(features) # After crop, all sequence-level arrays have shape[0] == 256 # All MSA-level arrays have shape[0] == 2048 assert features['aatype'].shape == (256,) assert features['msa'].shape == (2048, 256) assert features['seq_length'] == 256 assert features['num_alignments'] == 2048 ``` -------------------------------- ### Initialize and Use DataPipeline for Feature Construction Source: https://context7.com/google-deepmind/alphamissense/llms.txt The DataPipeline class constructs input features for the AlphaMissense model. It requires paths to genetic databases and configuration for MSA search and feature cropping. The process() method generates a feature dictionary for a given variant. ```python from alphamissense.data import pipeline_missense DATABASES_DIR = '/data/databases' pipeline = pipeline_missense.DataPipeline( jackhmmer_binary_path='/usr/bin/jackhmmer', protein_sequence_file='/data/sequences.fasta', # FASTA with all target proteins uniref90_database_path=DATABASES_DIR + '/uniref90/uniref90.fasta', mgnify_database_path=DATABASES_DIR + '/mgnify/mgy_clusters_2022_05.fa', small_bfd_database_path=DATABASES_DIR + '/small_bfd/bfd-first_non_consensus_sequences.fasta', mgnify_max_hits=5_000, uniref_max_hits=10_000, small_bfd_max_hits=5_000, sequence_crop_size=256, # Residues per sample msa_crop_size=2048, # MSA sequences per sample use_precomputed_msas=True # Re-use cached MSA files if present ) # Process a single variant: Ala→Cys substitution at position 3 sample = pipeline.process( protein_id='Q08708', # Must match a FASTA description line reference_aa='A', # Single capital letter alternate_aa='C', position=3, # 1-based msa_output_dir='/data/msa_cache/Q08708', pathogenicity=None, # Provide True/False only for training ) # sample is a dict of numpy arrays, e.g.: # sample['aatype'].shape -> (256,) # sample['msa'].shape -> (2048, 256) # sample['variant_mask'].shape -> (256,) # sample['all_atom_positions'] -> (256, 37, 3) print(sorted(sample.keys())) # ['aatype', 'all_atom_mask', 'all_atom_positions', 'cluster_bias_mask', # 'deletion_matrix', 'deletion_mean', 'msa', 'msa_mask', 'msa_profile', # 'num_alignments', 'residue_index', 'seq_length', 'seq_mask', # 'variant_aatype', 'variant_mask', 'variant_position'] ``` -------------------------------- ### Load AlphaMissense Model Configuration Source: https://context7.com/google-deepmind/alphamissense/llms.txt Loads the default model configuration or a specific variant like 'model_3' which enables the extra MSA stack. Useful for adjusting parameters like recycling iterations or MSA crop size. ```python from alphamissense.model import config # Default config (model 1 / model 2 — no extra MSA stack) cfg = config.model_config() # Model 3 variant — enables extra MSA stack cfg3 = config.model_config('model_3') assert cfg3.model.embeddings_and_evoformer.enable_extra_msa_stack is True # Adjust recycling iterations (useful for testing) cfg.model.num_recycle = 1 print('Evoformer blocks:', cfg.model.embeddings_and_evoformer.evoformer_num_block) # 48 print('MSA crop size: ', cfg.model.embeddings_and_evoformer.num_msa) # 256 print('Pair channel: ', cfg.model.embeddings_and_evoformer.pair_channel) # 128 ``` -------------------------------- ### Fetch AlphaFold DB Structure with `get_atom_positions` Source: https://context7.com/google-deepmind/alphamissense/llms.txt Downloads and parses AlphaFold Database CIF files for spatial cropping. Requires `gcloud` CLI authentication. Provides a fallback for unavailable structures using empty arrays. ```python from alphamissense.data.pipeline_missense import get_atom_positions, get_empty_atom_positions try: atom_features = get_atom_positions('Q08708') # atom_features['all_atom_positions'] -> float32 (N_res, 37, 3) # atom_features['all_atom_mask'] -> int32 (N_res, 37) print('Structure loaded, residues:', atom_features['all_atom_positions'].shape[0]) except (ValueError, FileNotFoundError): # Fallback when structure is unavailable — all-zero arrays num_res = 200 atom_features = get_empty_atom_positions(num_res) print('Using empty atom positions (contiguous crop will be used)') ``` -------------------------------- ### modules_missense.RunModel Source: https://context7.com/google-deepmind/alphamissense/llms.txt A high-level container for the AlphaMissense model, simplifying its usage by wrapping JIT-compiled apply and lazy parameter initialization. It can use pre-trained parameters or initialize randomly. ```APIDOC ## modules_missense.RunModel ### Description High-level model container that wraps AlphaMissense with JIT-compiled apply and lazy parameter initialization. ### Method `RunModel(cfg, params=None)` ### Parameters * **cfg** - Model configuration object. * **params** (optional) - Pre-trained model parameters. If None, parameters are initialized randomly. ### Request Example ```python import jax import jax.numpy as jnp from alphamissense.model import config, modules_missense cfg = config.model_config() # Initialize with random params (no trained weights available publicly) model_runner = modules_missense.RunModel(cfg, params=None) sample_jnp = jax.tree_map(jnp.asarray, sample) # sample from DataPipeline.process() # Lazily initializes params on first call output = model_runner.predict(sample_jnp, random_seed=42) # Access pathogenicity score logit_diff = output['logit_diff']['variant_row_logit_diff'] # shape (256,) pathogenicity = output['logit_diff']['variant_pathogenicity'] # scalar print('Variant pathogenicity score:', float(pathogenicity)) # Higher positive value → model assigns more probability to the reference AA # → more likely the substitution disrupts protein function (pathogenic) # Inspect output structure import tree for path, arr in tree.flatten_with_path(output): print('.'.join(map(str, path)), arr.shape if hasattr(arr, 'shape') else arr) ``` ### Response * **dict** - A dictionary containing model outputs, including pathogenicity scores and representations. ``` -------------------------------- ### parsers.parse_fasta() Source: https://context7.com/google-deepmind/alphamissense/llms.txt Parses FASTA strings into sequences and descriptions. This utility function takes a FASTA formatted string and returns lists of sequences and their corresponding descriptions. ```APIDOC ## parsers.parse_fasta() ### Description Parse FASTA strings into sequences and descriptions. Parses FASTA strings into sequences and descriptions. ### Parameters - **fasta_string** (str): A string containing data in FASTA format. ### Returns - A tuple containing two lists: `sequences` (list of str) and `descriptions` (list of str). ### Request Example ```python from alphamissense.data import parsers fasta_string = """> >Q08708 FGFR2 isoform MAEGEITTFTALTEKFNLPPGNYKKPKLLYCSNG >P04637 TP53 MEEPQSDPSVEPPLSQETFSDLWKLLPENNVLSPLPSQAMDDLMLSPDDIEQWFTEDP """ sequences, descriptions = parsers.parse_fasta(fasta_string) print(descriptions) # ['Q08708 FGFR2 isoform', 'P04637 TP53'] print(sequences[0]) # 'MAEGEITTFTALTEKFNLPPGNYKKPKLLYCSNG' ``` ``` -------------------------------- ### Parse FASTA Strings with `parsers.parse_fasta` Source: https://context7.com/google-deepmind/alphamissense/llms.txt Parses FASTA formatted strings into lists of sequences and descriptions. Useful for loading sequence data from various bioinformatics sources. ```python from alphamissense.data import parsers fasta_string = ">Q08708 FGFR2 isoform\nMAEGEITTFTALTEKFNLPPGNYKKPKLLYCSNG\n>P04637 TP53\nMEEPQSDPSVEPPLSQETFSDLWKLLPENNVLSPLPSQAMDDLMLSPDDIEQWFTEDP\n" sequences, descriptions = parsers.parse_fasta(fasta_string) print(descriptions) # ['Q08708 FGFR2 isoform', 'P04637 TP53'] print(sequences[0]) # 'MAEGEITTFTALTEKFNLPPGNYKKPKLLYCSNG' ``` -------------------------------- ### AlphaMissense Haiku Module Forward Pass Source: https://context7.com/google-deepmind/alphamissense/llms.txt Implements the core AlphaMissense neural network forward pass using Haiku. Requires a JAX PRNG key and sample data, and returns a dictionary containing pathogenicity scores. ```python import jax import haiku as hk from alphamissense.model import config, modules_missense cfg = config.model_config() cfg.model.num_recycle = 1 # Reduce for faster testing def _forward_fn(batch): model = modules_missense.AlphaMissense(cfg.model) return model(batch, is_training=False, return_representations=False) prng = jax.random.PRNGKey(0) # `sample` is a FeatureDict from DataPipeline.process(), converted to jnp arrays import jax.numpy as jnp sample_jnp = jax.tree_map(jnp.asarray, sample) params = hk.transform(_forward_fn).init(prng, sample_jnp) apply = jax.jit(hk.transform(_forward_fn).apply) output = apply(params, prng, sample_jnp) score = output['logit_diff']['variant_pathogenicity'] print('Pathogenicity logit:', float(score)) ``` -------------------------------- ### RunModel High-Level Model Container Source: https://context7.com/google-deepmind/alphamissense/llms.txt A convenience class wrapping the AlphaMissense model with JIT-compiled apply and lazy parameter initialization. It can accept pre-trained parameters or initialize randomly for testing. ```python import jax import jax.numpy as jnp from alphamissense.model import config, modules_missense cfg = config.model_config() # Initialize with random params (no trained weights available publicly) model_runner = modules_missense.RunModel(cfg, params=None) sample_jnp = jax.tree_map(jnp.asarray, sample) # sample from DataPipeline.process() # Lazily initializes params on first call output = model_runner.predict(sample_jnp, random_seed=42) # Access pathogenicity score logit_diff = output['logit_diff']['variant_row_logit_diff'] # shape (256,) pathogenicity = output['logit_diff']['variant_pathogenicity'] # scalar print('Variant pathogenicity score:', float(pathogenicity)) # Higher positive value → model assigns more probability to the reference AA # → more likely the substitution disrupts protein function (pathogenic) # Inspect output structure import tree for path, arr in tree.flatten_with_path(output): print('.'.join(map(str, path)), arr.shape if hasattr(arr, 'shape') else arr) ``` -------------------------------- ### make_msa_features() Source: https://context7.com/google-deepmind/alphamissense/llms.txt Constructs MSA feature arrays from parsed alignments. This function takes a list of `parsers.Msa` objects and assembles deduplicated integer-tokenized MSA arrays. ```APIDOC ## make_msa_features() ### Description Takes a list of `parsers.Msa` objects (from different databases) and assembles deduplicated integer-tokenized MSA arrays. Used internally after Jackhmmer runs but also useful when loading pre-computed alignments. ### Parameters - **msa_list** (list of `parsers.Msa`): A list of parsed Multiple Sequence Alignment objects from various sources. ### Returns - A dictionary containing MSA features: `msa`, `deletion_matrix`, `msa_mask`, and `num_alignments`. ### Request Example ```python from alphamissense.data import parsers from alphamissense.data.pipeline_missense import make_msa_features with open('/data/msa_cache/Q08708/uniref90_hits.sto') as f: uniref90_msa = parsers.parse_stockholm(f.read()) with open('/data/msa_cache/Q08708/mgnify_hits.sto') as f: mgnify_msa = parsers.parse_stockholm(f.read()) msa_features = make_msa_features([uniref90_msa, mgnify_msa]) # msa_features['msa'] -> int32 (N_seqs, seq_len) — tokenized residues # msa_features['deletion_matrix'] -> float32 (N_seqs, seq_len) # msa_features['msa_mask'] -> bool (N_seqs, seq_len) # msa_features['num_alignments'] -> int32 (seq_len,) — same value repeated print('Deduplicated MSA depth:', msa_features['num_alignments'][0]) ``` ``` -------------------------------- ### Gather MSA Features Directly with DataPipeline Source: https://context7.com/google-deepmind/alphamissense/llms.txt The gather_msa_features() method allows direct execution of MSA tools for a given ProteinVariant. It saves Stockholm-format results to a specified directory and returns a deduplicated MSA feature dictionary. This is useful for fine-grained control over MSA generation. ```python from alphamissense.data.pipeline_missense import ProteinVariant variant = ProteinVariant( sequence="MAEGEITTFTALTEKFNLPPGNYKKPKLLYCSNG", position=3, reference_aa='E', alternate_aa='K', protein_id='Q08708', pathogenicity=None, ) msa_features = pipeline.gather_msa_features( variant=variant, msa_output_dir='/data/msa_cache/Q08708', ) # msa_features['msa'].shape -> (N_alignments, seq_len) # msa_features['msa_mask'] -> boolean mask ``` -------------------------------- ### get_atom_positions() Source: https://context7.com/google-deepmind/alphamissense/llms.txt Fetches AlphaFold DB structure for spatial cropping. Downloads and parses the AlphaFold Database v4 CIF file for a given UniProt protein ID. ```APIDOC ## get_atom_positions() ### Description Fetch AlphaFold DB structure for spatial cropping. Downloads the AlphaFold Database v4 CIF file for a given UniProt protein ID from Google Cloud Storage, parses it, and returns `all_atom_positions` (shape `[N, 37, 3]`) and `all_atom_mask` (shape `[N, 37]`). Requires `gcloud` CLI authentication. ### Parameters - **uniprot_id** (str): The UniProt ID of the protein. ### Returns - A dictionary containing `all_atom_positions` and `all_atom_mask`. ### Request Example ```python from alphamissense.data.pipeline_missense import get_atom_positions, get_empty_atom_positions try: atom_features = get_atom_positions('Q08708') # atom_features['all_atom_positions'] -> float32 (N_res, 37, 3) # atom_features['all_atom_mask'] -> int32 (N_res, 37) print('Structure loaded, residues:', atom_features['all_atom_positions'].shape[0]) except (ValueError, FileNotFoundError): # Fallback when structure is unavailable — all-zero arrays num_res = 200 atom_features = get_empty_atom_positions(num_res) print('Using empty atom positions (contiguous crop will be used)') ``` ``` -------------------------------- ### Parse A3M Alignment Files Source: https://context7.com/google-deepmind/alphamissense/llms.txt Reads an A3M-format alignment file into an Msa object. Note that lowercase insertions are counted in the deletion matrix and stripped from sequences. ```python from alphamissense.data import parsers with open('/data/alignments/query.a3m') as f: a3m_string = f.read() msa = parsers.parse_a3m(a3m_string) # Lowercase insertions are counted in deletion_matrix and stripped from sequences print('Aligned sequences:', len(msa.sequences)) print('Deletion matrix shape:', len(msa.deletion_matrix), 'x', len(msa.deletion_matrix[0])) ``` -------------------------------- ### modules_missense.AlphaMissense Source: https://context7.com/google-deepmind/alphamissense/llms.txt Haiku Module for the core AlphaMissense neural network. It performs the full forward pass with recycling and outputs pathogenicity scores. This module is typically used indirectly via RunModel or hk.transform. ```APIDOC ## modules_missense.AlphaMissense (Haiku module) ### Description Core neural network implementing the full AlphaMissense forward pass with recycling. ### Method `AlphaMissense(cfg.model)(batch, is_training: bool, return_representations: bool) -> dict` ### Parameters * **cfg.model** - Model configuration object. * **batch** - Input feature batch. * **is_training** (bool) - Flag indicating if the model is in training mode. * **return_representations** (bool) - Flag to include representations in the output. ### Request Example ```python import jax import haiku as hk from alphamissense.model import config, modules_missense cfg = config.model_config() cfg.model.num_recycle = 1 # Reduce for faster testing def _forward_fn(batch): model = modules_missense.AlphaMissense(cfg.model) return model(batch, is_training=False, return_representations=False) prng = jax.random.PRNGKey(0) # `sample` is a FeatureDict from DataPipeline.process(), converted to jnp arrays import jax.numpy as jnp sample_jnp = jax.tree_map(jnp.asarray, sample) params = hk.transform(_forward_fn).init(prng, sample_jnp) apply = jax.jit(hk.transform(_forward_fn).apply) output = apply(params, prng, sample_jnp) score = output['logit_diff']['variant_pathogenicity'] print('Pathogenicity logit:', float(score)) # Positive logit_diff → reference amino acid more likely → variant may be pathogenic ``` ### Response * **dict** - A dictionary containing model outputs, including 'logit_diff' with pathogenicity scores. ``` -------------------------------- ### Construct MSA Feature Arrays with `make_msa_features` Source: https://context7.com/google-deepmind/alphamissense/llms.txt Assembles deduplicated integer-tokenized MSA arrays from parsed alignment objects. This function is useful for loading pre-computed alignments or after running tools like Jackhmmer. ```python from alphamissense.data import parsers from alphamissense.data.pipeline_missense import make_msa_features with open('/data/msa_cache/Q08708/uniref90_hits.sto') as f: uniref90_msa = parsers.parse_stockholm(f.read()) with open('/data/msa_cache/Q08708/mgnify_hits.sto') as f: mgnify_msa = parsers.parse_stockholm(f.read()) msa_features = make_msa_features([uniref90_msa, mgnify_msa]) # msa_features['msa'] -> int32 (N_seqs, seq_len) — tokenized residues # msa_features['deletion_matrix'] -> float32 (N_seqs, seq_len) # msa_features['msa_mask'] -> bool (N_seqs, seq_len) # msa_features['num_alignments'] -> int32 (seq_len,) — same value repeated print('Deduplicated MSA depth:', msa_features['num_alignments'][0]) ``` -------------------------------- ### Build Per-Sequence Feature Tensors with `variant_sequence_features` Source: https://context7.com/google-deepmind/alphamissense/llms.txt Constructs residue-level feature arrays for a ProteinVariant. Use when you need to generate features like amino acid type, variant type, and masks for a single protein sequence and its mutation. ```python from alphamissense.data.pipeline_missense import ProteinVariant, variant_sequence_features variant = ProteinVariant( sequence="MAEGEITTFTALTEKFNLPPGNYKKPKLLYCSNG", position=10, reference_aa='T', alternate_aa='A', protein_id='Q08708', pathogenicity=True, ) features = variant_sequence_features(variant) # features['aatype'] -> int32 array of reference amino-acid indices # features['variant_aatype'] -> int32 array with alternate AA at position 10 # features['variant_mask'] -> [0,0,...,1,...,0] mask at position 10 # features['variant_position'] -> scalar int32 = 9 (0-based) print('variant position (0-based):', features['variant_position']) print('pathogenicity label:', features['pathogenicity']) ``` -------------------------------- ### Cropper Source: https://context7.com/google-deepmind/alphamissense/llms.txt Performs spatial or contiguous sequence cropping around a variant site. It crops long sequences and pads them to a uniform size, using 3D structure information if available, otherwise falling back to a centered window. ```APIDOC ## Cropper ### Description Spatial or contiguous sequence cropping. Crops long sequences around the variant site and pads to uniform `crop_size` × `msa_crop_size`. Uses spatial cropping (closest residues in 3D to the variant) when AFDB atom positions are available, otherwise falls back to a centered contiguous window. ### Initialization - `crop_size` (int): The desired length of the cropped sequence. - `msa_crop_size` (int): The desired number of MSA sequences to crop. ### Method - `crop(features)`: Crops the provided feature dictionary. ### Parameters for `crop` method - **features** (dict): A dictionary containing feature tensors. Must include: `aatype`, `msa`, `msa_mask`, `deletion_matrix`, `residue_index`, `seq_mask`, `variant_aatype`, `variant_mask`, `all_atom_positions`, `all_atom_mask`, `variant_position`, `cluster_bias_mask`. ### Returns - A dictionary with cropped and padded feature tensors. ### Request Example ```python from alphamissense.data.pipeline_missense import Cropper import numpy as np cropper = Cropper(crop_size=256, msa_crop_size=2048) # `features` must contain: aatype, msa, msa_mask, deletion_matrix, # residue_index, seq_mask, variant_aatype, variant_mask, # all_atom_positions, all_atom_mask, variant_position, cluster_bias_mask features = cropper.crop(features) # After crop, all sequence-level arrays have shape[0] == 256 # All MSA-level arrays have shape[0] == 2048 assert features['aatype'].shape == (256,) assert features['msa'].shape == (2048, 256) assert features['seq_length'] == 256 assert features['num_alignments'] == 2048 ``` ``` -------------------------------- ### Parse Stockholm MSA Files Source: https://context7.com/google-deepmind/alphamissense/llms.txt Reads a Stockholm-format Multiple Sequence Alignment (MSA) file into an Msa object. Handles reading the file content and parsing it. ```python from alphamissense.data import parsers with open('/data/msa_cache/Q08708/uniref90_hits.sto') as f: stockholm_string = f.read() msa = parsers.parse_stockholm(stockholm_string) print(f'MSA depth: {len(msa)} sequences') print(f'First sequence: {msa.sequences[0][:30]}...') print(f'Descriptions sample: {msa.descriptions[:3]}') # Msa.truncate() limits depth msa_small = msa.truncate(max_seqs=512) ``` -------------------------------- ### RunModel.eval_shape() Inspect Output Shapes Source: https://context7.com/google-deepmind/alphamissense/llms.txt Inspects the output shapes of the AlphaMissense model without performing full inference. Returns a ShapeDtypeStruct tree, useful for understanding the model's output dimensions. ```python from alphamissense.model import config, modules_missense import jax, jax.numpy as jnp cfg = config.model_config() model_runner = modules_missense.RunModel(cfg, params=None) sample_jnp = jax.tree_map(jnp.asarray, sample) shape_tree = model_runner.eval_shape(sample_jnp) # Returns ShapeDtypeStruct tree — no actual computation performed print(shape_tree['logit_diff']['variant_pathogenicity']) ``` -------------------------------- ### RunModel.eval_shape() Source: https://context7.com/google-deepmind/alphamissense/llms.txt Inspects the output shapes of the AlphaMissense model for a given input batch without performing full inference. Returns a ShapeDtypeStruct tree. ```APIDOC ## RunModel.eval_shape() ### Description Inspects output shapes without running full inference. ### Method `model_runner.eval_shape(sample_jnp)` ### Parameters * **sample_jnp** - Input data batch as JAX numpy arrays. ### Request Example ```python from alphamissense.model import config, modules_missense import jax, jax.numpy as jnp cfg = config.model_config() model_runner = modules_missense.RunModel(cfg, params=None) sample_jnp = jax.tree_map(jnp.asarray, sample) shape_tree = model_runner.eval_shape(sample_jnp) # Returns ShapeDtypeStruct tree — no actual computation performed print(shape_tree['logit_diff']['variant_pathogenicity']) # ShapeDtypeStruct(shape=(), dtype=float32) ``` ### Response * **ShapeDtypeStruct tree** - A tree structure detailing the shapes and dtypes of the model's outputs. ``` -------------------------------- ### parsers.parse_a3m() Source: https://context7.com/google-deepmind/alphamissense/llms.txt Parses Multiple Sequence Alignment (MSA) data from the A3M format into an Msa object. This function handles the specific structure of A3M files, including lowercase insertions. ```APIDOC ## parsers.parse_a3m() ### Description Parses A3M-format alignment files. ### Method `parsers.parse_a3m(a3m_string: str) -> Msa` ### Parameters * **a3m_string** (str) - The content of the A3M file. ### Request Example ```python from alphamissense.data import parsers with open('/data/alignments/query.a3m') as f: a3m_string = f.read() msa = parsers.parse_a3m(a3m_string) # Lowercase insertions are counted in deletion_matrix and stripped from sequences print('Aligned sequences:', len(msa.sequences)) print('Deletion matrix shape:', len(msa.deletion_matrix), 'x', len(msa.deletion_matrix[0])) ``` ### Response * **Msa object** - An object containing the parsed MSA data, including sequences and deletion matrix information. ``` -------------------------------- ### Define a Missense Variant with ProteinVariant Source: https://context7.com/google-deepmind/alphamissense/llms.txt Use the ProteinVariant dataclass to define a single amino-acid substitution. Ensure the reference amino acid matches the sequence at the specified position. Computed properties provide reference and alternate sequences. ```python from alphamissense.data.pipeline_missense import ProteinVariant variant = ProteinVariant( sequence="MAEGEITTFTALTEKFNLPPGNYKKPKLLYCSNG", position=3, # 1-based index reference_aa='E', # Must match sequence[position-1] alternate_aa='K', protein_id='Q08708', pathogenicity=None, # Optional ground truth label (True=pathogenic) ) print(variant.reference_sequence) # "MAEGEITTFTALTEKFNLPPGNYKKPKLLYCSNG" print(variant.alternate_sequence) # "MAKGEITTFTALTEKFNLPPGNYKKPKLLYCSNG" ``` -------------------------------- ### Interpreting Logit Difference Pathogenicity Score Source: https://context7.com/google-deepmind/alphamissense/llms.txt This snippet shows how to interpret the scalar pathogenicity score derived from the LogitDiffPathogenicityHead. The score indicates whether the model prefers the reference or alternate amino acid, suggesting potential pathogenicity. ```python # This head is instantiated automatically inside AlphaMissenseIteration. # Its output is accessed via: # output['logit_diff']['variant_pathogenicity'] — scalar score # output['logit_diff']['variant_row_logit_diff'] — per-residue logit diff # Example: interpreting the score score = float(output['logit_diff']['variant_pathogenicity']) if score > 0: print(f'Score {score:.3f}: model prefers reference AA → potentially pathogenic') else: print(f'Score {score:.3f}: model prefers alternate AA → potentially benign') ``` -------------------------------- ### variant_sequence_features() Source: https://context7.com/google-deepmind/alphamissense/llms.txt Builds per-sequence feature tensors for a given ProteinVariant. This function constructs all residue-level feature arrays without external tool execution. ```APIDOC ## variant_sequence_features() ### Description Standalone function that constructs all residue-level feature arrays for a `ProteinVariant` without running any external tools. Produces `aatype`, `variant_aatype`, `variant_mask`, `residue_index`, and optionally `pathogenicity`. ### Parameters - **variant** (`ProteinVariant`): An object containing protein sequence, variant position, and other relevant details. ### Returns - A dictionary containing feature tensors such as `aatype`, `variant_aatype`, `variant_mask`, `residue_index`, and `pathogenicity`. ### Request Example ```python from alphamissense.data.pipeline_missense import ProteinVariant, variant_sequence_features variant = ProteinVariant( sequence="MAEGEITTFTALTEKFNLPPGNYKKPKLLYCSNG", position=10, reference_aa='T', alternate_aa='A', protein_id='Q08708', pathogenicity=True, ) features = variant_sequence_features(variant) # features['aatype'] -> int32 array of reference amino-acid indices # features['variant_aatype'] -> int32 array with alternate AA at position 10 # features['variant_mask'] -> [0,0,...,1,...,0] mask at position 10 # features['variant_position'] -> scalar int32 = 9 (0-based) print('variant position (0-based):', features['variant_position']) print('pathogenicity label:', features['pathogenicity']) ``` ``` -------------------------------- ### parsers.parse_stockholm() Source: https://context7.com/google-deepmind/alphamissense/llms.txt Parses Multiple Sequence Alignment (MSA) data from the Stockholm format into an Msa object. This function is useful for loading MSA data from common bioinformatics file formats. ```APIDOC ## parsers.parse_stockholm() ### Description Parses Stockholm-format MSA files. ### Method `parsers.parse_stockholm(stockholm_string: str) -> Msa` ### Parameters * **stockholm_string** (str) - The content of the Stockholm file. ### Request Example ```python from alphamissense.data import parsers with open('/data/msa_cache/Q08708/uniref90_hits.sto') as f: stockholm_string = f.read() msa = parsers.parse_stockholm(stockholm_string) print(f'MSA depth: {len(msa)} sequences') print(f'First sequence: {msa.sequences[0][:30]}...') print(f'Descriptions sample: {msa.descriptions[:3]}') # Msa.truncate() limits depth msa_small = msa.truncate(max_seqs=512) ``` ### Response * **Msa object** - An object containing the parsed MSA data, including sequences and descriptions. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.