alsebo package

Subpackages

Submodules

alsebo.optimizer module

alsebo.optimizer.acquisition_function(preds: list[tuple[ndarray, ndarray]], obj_config: dict, strategy: str = 'UCB', beta: float = 2.0, weights: list[float] | None = None) ndarray[source]

Computes a scalar acquisition score for each candidate sequence.

Combines per-objective UCB scores using weighted scalarization. Objective directions ("min" or "max") are read from obj_config so that minimization objectives are flipped before scoring.

Parameters:
  • preds (list[tuple[np.ndarray, np.ndarray]]) – List of (mean, std) prediction tuples, one per objective, as returned by seq_space_prediction().

  • obj_config (dict) – Objective configuration dict containing directions (list of "min"/"max" strings) and optionally weights (list of floats summing to 1). Equal weights are used if not provided.

  • strategy (str) – Acquisition strategy to use. Currently supports "UCB" (Upper Confidence Bound), defaults to "UCB".

  • beta (float) – Exploration-exploitation trade-off parameter for UCB. Higher values favour exploration, defaults to 2.0.

  • weights (list[float] or None) – Per-objective weights for scalarization. Overridden by obj_config["weights"] if present, defaults to None.

Returns:

Acquisition scores for each candidate sequence.

Return type:

np.ndarray, shape (n_candidates,)

alsebo.optimizer.get_next_seq_bo(seq_ids: Series, obj_config: dict, preds: list[tuple[ndarray, ndarray]], top_k: int = 10, strategy: str = 'UCB', weights: list[float] | None = None) tuple[Series, ndarray, ndarray][source]

Selects the top-k candidate sequences recommended for the next experiment.

Scores all candidates using the acquisition function and returns the highest-scoring sequences along with their scores and indices.

Parameters:
Returns:

Tuple of (next_best_seqs, top_scores, top_idx) where next_best_seqs are the recommended sequences, top_scores are their acquisition scores, and top_idx are their positions in x_space.

Return type:

tuple[pd.Series, np.ndarray, np.ndarray]

alsebo.optimizer.gpr(x_train: DataFrame | ndarray, y_train: DataFrame | ndarray) list[GaussianProcessRegressor][source]

Trains Gaussian Process Regression model(s) on sequence data.

Fits one GPR model per objective using a composite kernel (ConstantKernel * Matern + WhiteKernel). Handles both single-objective and multi-objective cases by fitting one model per output column.

Parameters:
  • x_train (pd.DataFrame or np.ndarray, shape (n_samples, n_features)) – Feature encodings of the training sequences.

  • y_train (pd.DataFrame or np.ndarray, shape (n_samples,) or (n_samples, n_objectives)) – Objective values for the training sequences. A 1-D array or single-column 2-D array is treated as single-objective; a multi-column 2-D array triggers one model per column.

Returns:

List of fitted GaussianProcessRegressor models, one per objective.

Return type:

list[GaussianProcessRegressor]

alsebo.optimizer.read_seq_files(exp_dir: str, obj_config: dict, file_name: str = 'seq_exp_data.csv') tuple[DataFrame, DataFrame, DataFrame, Series][source]

Loads training data and the candidate sequence space from CSV files.

Reads the experimental results CSV to extract sequence encodings and objective values, then loads the full candidate sequence space and removes sequences that have already been tested.

Parameters:
  • exp_dir (str) – Path to the experiment directory containing the CSV files.

  • obj_config (dict) – Objective configuration dict with at least a names key listing the objective column names.

  • file_name (str) – Filename of the experimental data CSV relative to exp_dir, defaults to "seq_exp_data.csv".

Returns:

Tuple of (x_train, y_train, x_space, seq_ids) where x_train and x_space are feature encodings, y_train holds objective values for tested sequences, and seq_ids lists of untested candidate sequences.

Return type:

tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.Series]

alsebo.optimizer.save_next_batch_results(exp_dir: str, next_best_seqs: Series, idx: ndarray, x_space: DataFrame, obj_config: dict, obj_values: list[list], file_name: str = 'seq_exp_data.csv') None[source]

Appends the experimental results of the recommended batch to the training CSV.

Combines the sequence feature encodings, sequences, and measured objective values into a single row per sequence and appends them to the experiment data file. Raises ValueError if the batch size or number of objectives does not match obj_values.

Parameters:
  • exp_dir (str) – Path to the experiment directory where the CSV is stored.

  • next_best_seqs (pd.Series) – recommended sequences, as returned by get_next_seq_bo().

  • idx (np.ndarray) – Integer indices of the recommended sequences within x_space, as returned by get_next_seq_bo().

  • x_space (pd.DataFrame) – Feature encodings of the full untested candidate space.

  • obj_config (dict) – Objective configuration dict with a names key listing the objective column names.

  • obj_values (list[list[float]]) – Measured objective values for the recommended batch. Shape must be (top_k, n_objectives).

  • file_name (str) – Filename of the experimental data CSV relative to exp_dir, defaults to "seq_exp_data.csv".

Returns:

None

Return type:

None

alsebo.optimizer.seq_space_prediction(models: list[GaussianProcessRegressor], x_space: DataFrame | ndarray) list[tuple[ndarray, ndarray]][source]

Generates posterior mean and standard deviation predictions over the candidate space.

Runs each trained GPR model over all candidate sequences and collects the predictive mean and standard deviation for use in the acquisition function.

Parameters:
  • models (list[GaussianProcessRegressor]) – List of fitted GPR models, one per objective.

  • x_space (pd.DataFrame or np.ndarray, shape (n_candidates, n_features)) – Feature encodings of the untested candidate sequences.

Returns:

List of (mean, std) tuples, one tuple per objective.

Return type:

list[tuple[np.ndarray, np.ndarray]]

alsebo.seq_space module

alsebo.seq_space.compute_dca_features(seq_indices: list[int], localfields: ndarray, couplings: ndarray) ndarray[source]

Computes per-position DCA feature values for a single sequence.

For each position i, combines the local field contribution with the sum of pairwise coupling terms across all other positions.

Parameters:
  • seq_indices (list[int]) – Amino acid indices for each position in the sequence, mapped from the standard alphabet '-ACDEFGHIKLMNPQRSTVWY'.

  • localfields (np.ndarray, shape (n_aa, sequence_length)) – Local field parameters from the DCA model, indexed as localfields[aa_index, position].

  • couplings (np.ndarray, shape (sequence_length, sequence_length, n_aa, n_aa)) – Pairwise coupling parameters from the DCA model, indexed as couplings[i, j, aa_i, aa_j].

Returns:

DCA feature vector for the sequence.

Return type:

np.ndarray, shape (sequence_length,)

alsebo.seq_space.generate_dca_features(exp_dir: str, msa_fname: str, gen_sequences: list[str]) ndarray[source]

Computes DCA (Direct Coupling Analysis) features for a list of sequences.

Fits a mean-field DCA model on the provided MSA, then computes per-position DCA feature vectors for each generated sequence via compute_dca_features().

Parameters:
  • exp_dir (str) – Path to the experiment directory containing the MSA file.

  • msa_fname (str) – Filename of the multiple sequence alignment file relative to exp_dir.

  • gen_sequences (list[str]) – List of amino acid sequences to featurize.

Returns:

DCA feature matrix, one row per sequence.

Return type:

np.ndarray, shape (n_sequences, sequence_length)

alsebo.seq_space.generate_esm_features(gen_sequences: list[str], batch_size: int = 32, model_name: str = 'facebook/esm2_t30_150M_UR50D') ndarray[source]

Generates mean-pooled ESM embeddings for a list of protein sequences.

Loads the specified ESM model, runs batched inference, and returns a single mean-pooled embedding vector per sequence by averaging over non-padding tokens (excluding <cls> and <eos> special tokens).

Parameters:
  • gen_sequences (list[str]) – List of amino acid sequences to embed.

  • batch_size (int) – Number of sequences to process per forward pass, defaults to 32.

  • model_name (str) – HuggingFace model identifier for the ESM model to load, defaults to "facebook/esm2_t30_150M_UR50D".

Returns:

ESM embedding matrix, one mean-pooled vector per sequence.

Return type:

np.ndarray, shape (n_sequences, embedding_dim)

alsebo.seq_space.generate_latent_features(fasta_path: str) ndarray[source]

Extracts latent coordinates from FASTA sequence headers.

Parses each record’s header as a pair of space-separated floats (z0 and z1) representing 2-D latent space coordinates. Records with unparseable headers are skipped with a warning.

Parameters:

fasta_path (str) – Path to the FASTA file whose headers contain latent coordinates in the format "z0 z1".

Returns:

Latent coordinate matrix, one row per successfully parsed sequence.

Return type:

np.ndarray, shape (n_sequences, 2)

alsebo.seq_space.generate_seq_space(exp_dir: str, msa_fname: str, gen_seq_fasta_fname: str = 'generated_seqs.fasta', featuarization_method: str = 'DCA') ndarray[source]

Featurizes the generated sequence space and saves it to a CSV file.

Reads generated sequences from a FASTA file, computes features using the specified method (DCA, ESM, or latent), and writes a seq_space.csv to exp_dir with one row per sequence.

Parameters:
  • exp_dir (str) – Path to the experiment directory where inputs are read from and seq_space.csv is written to.

  • msa_fname (str) – Filename of the multiple sequence alignment file relative to exp_dir, used by the DCA featurization method.

  • gen_seq_fasta_fname (str) – Filename of the generated sequences FASTA file relative to exp_dir, defaults to "generated_seqs.fasta".

  • featuarization_method (str) – Featurization method to use. One of "DCA", "ESM", or "latent". Defaults to "DCA".

Returns:

Feature matrix for all generated sequences.

Return type:

np.ndarray, shape (n_sequences, n_features)

alsebo.skeleton module

This is a skeleton file that can serve as a starting point for a Python console script. To run this script uncomment the following lines in the [options.entry_points] section in setup.cfg:

console_scripts =
     fibonacci = alsebo.skeleton:run

Then run pip install . (or pip install -e . for editable mode) which will install the command fibonacci inside your current environment.

Besides console scripts, the header (i.e. until _logger…) of this file can also be used as template for Python modules.

Note

This file can be renamed depending on your needs or safely removed if not needed.

References

alsebo.skeleton.fib(n)[source]

Fibonacci example function

Parameters:

n (int) – integer

Returns:

n-th Fibonacci number

Return type:

int

alsebo.skeleton.main(args)[source]

Wrapper allowing fib() to be called with string arguments in a CLI fashion

Instead of returning the value from fib(), it prints the result to the stdout in a nicely formatted message.

Parameters:

args (List[str]) – command line parameters as list of strings (for example ["--verbose", "42"]).

alsebo.skeleton.parse_args(args)[source]

Parse command line parameters

Parameters:

args (List[str]) – command line parameters as list of strings (for example ["--help"]).

Returns:

command line parameters namespace

Return type:

argparse.Namespace

alsebo.skeleton.run()[source]

Calls main() passing the CLI arguments extracted from sys.argv

This function can be used as entry point to create console scripts with setuptools.

alsebo.skeleton.setup_logging(loglevel)[source]

Setup basic logging

Parameters:

loglevel (int) – minimum loglevel for emitting messages

alsebo.training_space module

alsebo.training_space.generate_sequence_training_file(exp_dir: str, obj_config: dict, obj_values: list[list], file_name: str = 'seq_exp_data.csv') None[source]

Combines the initial training sequences with their measured objective values.

Reads the sampled training sequences from training_seqs.csv, attaches the provided objective values as new columns, and writes the combined DataFrame to the experiment data CSV. Raises ValueError if the number of sequences does not match the number of objective rows.

Parameters:
  • exp_dir (str) – Path to the experiment directory containing training_seqs.csv and where the output CSV will be written.

  • obj_config (dict) – Objective configuration dict with a names key listing the objective column names.

  • obj_values (list[list[float]]) – Measured objective values for each training sequence. Shape must be (n_training_sequences, n_objectives).

  • file_name (str) – Output filename for the experiment data CSV relative to exp_dir, defaults to "seq_exp_data.csv".

Returns:

None

Return type:

None

alsebo.training_space.sample_initial_training_sequnces(exp_dir: str, training_seq_size: int, manipold: str = 'TSNE') None[source]

Samples a diverse initial training set from the candidate sequence space.

Projects the sequence feature space down to 2-D using the chosen manifold method, then runs k-means clustering and picks the sequence closest to each cluster centroid. The selected sequences are saved to training_seqs.csv in exp_dir.

Parameters:
  • exp_dir (str) – Path to the experiment directory containing seq_space.csv and where training_seqs.csv will be written.

  • training_seq_size (int) – Number of diverse sequences to select (equals the number of k-means clusters).

  • manipold (str) – Dimensionality reduction method to use before clustering. "TSNE" uses t-SNE and "PCA" uses PCA, defaults to "TSNE".

Returns:

None

Return type:

None

Module contents