API Reference
This page documents the main public entry points and the builders used in
the tutorials. Start with FEAST.simulate() for reference-based data
and FEAST.generate() for a slice designed from a blueprint.
Simulation and fitting
- FEAST.simulate(reference=None, target=None, *, condition_on=None, marginal_model='parameter_cloud', parameter_cloud=None, transport=None, fit_config=None, alteration=None, seed=None, parameter_mode='hungarian', spatial_mode=None, verbose=True, **kwargs)[source]
Simulate an ST slice through one reference-to-target field backbone.
Reference-based parameter-cloud simulation and label-conditioned transfer share the same public function and OT field implementation.
target=Nonemeans the reference geometry is the target. Setcondition_onandmarginal_model='empirical_reference'for conditional empirical-rank transfer.- Parameters:
reference – Reference AnnData, sequence of AnnData objects, or a fitted
SimulationReference.target – Optional target AnnData or
SliceBlueprint. Target expression is not read by the conditional path.condition_on (str | None) – Reference and target
.obscolumn used for label conditioning. Omit for global reference-based simulation.marginal_model (str) –
"parameter_cloud"or"empirical_reference".parameter_cloud – Optional global or label-specific parameter cloud for conditioned parameter-cloud decoding.
transport (TransportConfig | None) – Shared
TransportConfig. ASimulationConfigmay be supplied when conditional quantile-field controls are also needed.fit_config (ReferenceFitConfig | None) – Reference fitting controls for conditioned generation.
alteration (AlterationConfig | None) – Optional
Alterationconfig to systematically modify expression statistics (mean, variance, or sparsity).seed (int | None) – Run-wide seed for reproducible fitting, assignment, transport, and count generation. Seeded output is independent of ambient NumPy state.
parameter_mode (str) –
"hungarian"(generative fitting) or"reference_stats"(use reference stats directly).spatial_mode (str | None) –
"reference_rank"(rank-based spatial assignment) or"ot_spatial"(optimal-transport spatial assignment). When omitted, FEAST selects OT iftargetortransportis provided and reference-rank assignment otherwise.verbose (bool) – Print progress messages.
kwargs – Advanced parameters passed through to the underlying simulator (e.g.
assignment_solver,ppf_method,beta_n_jobs).
- Returns:
Simulated slice with identical genes and spatial coordinates.
- Return type:
- FEAST.generate(blueprint, param_cloud, *, patterns=None, seed=0, config=None, **kwargs)[source]
Generate a virtual ST slice from a blueprint and parameter cloud.
Build a synthetic slice from scratch — no reference data needed. Use
SliceBlueprintto define the spatial layout andparam_cloudto specify per-gene expression distributions.- Parameters:
blueprint –
SliceBlueprint(or AnnData / dict / path to one) defining spot coordinates and domain labels.param_cloud – DataFrame or dict with columns
mean,variance,zero_propfor each gene.patterns – Optional spatial pattern specification (e.g. gradients, hotspots).
seed (int) – Random seed for reproducible output.
config (SimulationConfig | None) –
SimulationConfigfor transport and quantile-field settings.kwargs – Passed through to
simulate_from_design().
- Returns:
Virtual slice.
- Return type:
- FEAST.fit(adata, *, max_zero_prop_components=8, beta_early_stopping_patience=2, beta_n_jobs=1, ppf_method='interp', visualize_fits=False)[source]
Fit a parameter-cloud model to real ST data.
The returned
GeneParameterSimulatorcan be serialised, inspected, altered, and used for repeated simulation without re-fitting.- Parameters:
adata – Reference
AnnData.max_zero_prop_components (int) – Maximum number of components considered for the zero-proportion marginal model.
beta_early_stopping_patience (int) – Component-search patience for the beta mixture.
beta_n_jobs (int) – Parallel workers used by the beta-mixture component search.
ppf_method (str) – Student-t mixture inverse-CDF implementation,
"interp"or"exact".visualize_fits (bool) – Show diagnostic marginal-fit plots.
- Returns:
Fitted simulator ready for parameter inspection or count decoding.
- Return type:
- FEAST.de_novo.fit_reference(reference_slices, label_key, config=None)[source]
- Parameters:
reference_slices (AnnData | Sequence[AnnData])
label_key (str)
config (ReferenceFitConfig | None)
- Return type:
- FEAST.estimate_assignment_randomness(reference, label_key=None, *, spatial_key='spatial', n_genes=20, ar_step=0.1, max_ar=0.5, n_neighbors=6, random_seed=None, transport=None)[source]
Estimate assignment_randomness via a quick mini-sweep on the reference.
Spatially splits the reference in half, runs the full de-novo conditional pipeline on a small gene panel at each AR candidate, and returns the value that best preserves spatial autocorrelation (Moran’s I correlation between generated and held-out halves).
This mirrors the logic of the full cross-slice benchmark but operates on a single slice split, with a small gene set, so it completes in seconds.
- Parameters:
reference (AnnData | SimulationReference) – Reference
AnnDataor a fittedSimulationReference. If an AnnData, label_key must be provided.label_key (str | None) – Column in
.obswith domain/region labels. Required when reference is an AnnData.spatial_key (str) – Key in
.obsmfor spatial coordinates (default"spatial").n_genes (int) – Number of high-variance genes to use in the mini-sweep. More genes improve stability but increase runtime linearly.
ar_step (float) – Step size between AR candidates. Tested values are
[0.0, ar_step, 2*ar_step, ..., max_ar]. Use a finer step (e.g. 0.05) for higher precision at the cost of more OT runs.max_ar (float) – Maximum AR value to test. Values above ~0.5 rarely help.
n_neighbors (int) – Number of spatial neighbors for Moran’s-I computation.
random_seed (int | None) – Seed for reproducible results.
transport (TransportConfig | None) – Optional transport configuration used for every mini-sweep candidate.
- Returns:
Estimated assignment_randomness in [0.0, max_ar].
- Return type:
Notes
If the reference has fewer than 50 spots, only a single domain label, or the spatial split fails to produce two viable halves, the function returns 0.0 (pure OT, no randomness).
Configuration
- FEAST.Alteration
alias of
AlterationConfig
- class FEAST.TransportConfig(epsilon=0.05, sinkhorn_iter=1000, sinkhorn_tol=1e-05, unbalanced_transport=True, reg_m=5.0, transport_nonconvergence='raise', geometry_weight=1.0, boundary_weight=0.25, assignment_randomness=0.0, latent_clip_eps=1e-06, gene_chunk_size=512, max_transport_pairs=25000000, sinkhorn_method='sinkhorn', transport_backend='numpy', transport_device=None, transport_dtype='float64')[source]
Configuration for the shared reference-to-target OT field transport.
transport_dtypeselects"float64"(default) or"float32"solver arithmetic on either backend. Coordinate/cost preparation, returned plans and latent fields retain their existing float32 representation. Precision does not change the iteration limit, tolerance or nonconvergence policy.- Parameters:
epsilon (float)
sinkhorn_iter (int)
sinkhorn_tol (float)
unbalanced_transport (bool)
reg_m (float)
transport_nonconvergence (str)
geometry_weight (float)
boundary_weight (float)
assignment_randomness (float)
latent_clip_eps (float)
gene_chunk_size (int)
max_transport_pairs (int | None)
sinkhorn_method (str)
transport_backend (str)
transport_device (str | None)
transport_dtype (str)
Transport uses NumPy on CPU with float64 solver arithmetic by default.
For GPU transport, use transport_backend="torch" and
transport_device="cuda:0" in a compatible CUDA environment.
- class FEAST.ReferenceFitConfig(min_gene_spots: 'int' = 20, min_gene_mean: 'float' = 0.1, max_gene_zero_prop: 'float' = 0.98, boundary_neighbors: 'int' = 6, coordinate_scale: 'Optional[Sequence[float]]' = None)[source]
- class FEAST.SimulationConfig(epsilon=0.05, sinkhorn_iter=1000, sinkhorn_tol=1e-05, unbalanced_transport=True, reg_m=5.0, transport_nonconvergence='raise', geometry_weight=1.0, boundary_weight=0.25, assignment_randomness=0.0, latent_clip_eps=1e-06, gene_chunk_size=512, max_transport_pairs=25000000, sinkhorn_method='sinkhorn', transport_backend='numpy', transport_device=None, transport_dtype='float64', reference_weight_eta=4.0, boundary_multiplier=1.1, diffusion_level=0.0, boundary_softness=0.0, coordinate_scale=None, verbose=False, quantile_field_mode='auto', rank_scope='auto', target_parameter_mode='reference_weighted_log', tie_policy='stable_ordinal', tie_jitter_scale=1e-09, min_rank_scope_size=20, store_latent_scores=False, store_quantiles='auto', max_stored_quantile_elements=50000000, reference_conflict_policy='average', program_noise_scale=0.0, program_normalization='zscore')[source]
Reference-conditioned generation config built on shared OT settings.
- Parameters:
epsilon (float)
sinkhorn_iter (int)
sinkhorn_tol (float)
unbalanced_transport (bool)
reg_m (float)
transport_nonconvergence (str)
geometry_weight (float)
boundary_weight (float)
assignment_randomness (float)
latent_clip_eps (float)
gene_chunk_size (int)
max_transport_pairs (int | None)
sinkhorn_method (str)
transport_backend (str)
transport_device (str | None)
transport_dtype (str)
reference_weight_eta (float)
boundary_multiplier (float)
diffusion_level (float)
boundary_softness (float)
verbose (bool)
quantile_field_mode (str)
rank_scope (str)
target_parameter_mode (str)
tie_policy (str)
tie_jitter_scale (float)
min_rank_scope_size (int)
store_latent_scores (bool)
store_quantiles (Any)
max_stored_quantile_elements (int)
reference_conflict_policy (str)
program_noise_scale (float)
program_normalization (str)
De novo builders
- class FEAST.SliceBlueprint(coordinates: 'np.ndarray', coordinate_mode: 'str' = 'generic', grid_type: 'str' = 'generic', mask: 'Optional[np.ndarray]' = None, domain_map: 'Optional[np.ndarray]' = None, technology: 'Optional[str]' = None, obs: 'pd.DataFrame' = <factory>, metadata: 'Dict[str, Any]' = <factory>)[source]
- class FEAST.de_novo.SimulationBlueprintBuilder(coordinates, coordinate_mode='generic', grid_type='generic', technology=None)[source]
- Parameters:
- class FEAST.de_novo.SimulationParameterBuilder(gene_names)[source]
- Parameters:
gene_names (Sequence[str])
- class FEAST.de_novo.SimulationPatternBuilder(gene_names)[source]
- Parameters:
gene_names (Sequence[str])
Alignment and deconvolution
- FEAST.alignment.rotate_spatial(adata, angle_degrees, *, center=None, plate_bounds=None, spatial_key='spatial', original_key='spatial_original')[source]
Rotate an AnnData slice, optionally cropping to a fixed plate.
The transformation is centered on the coordinate centroid unless an explicit center is supplied. By default it never changes spot support. Pass
plate_boundsas[[x_min, y_min], [x_max, y_max]]to retain only rotated spots inside that inclusive rectangle. It never snaps, deduplicates, or reorders spots. Transform and crop metadata are recorded in.uns.
- FEAST.alignment.apply_spatial_transform(coords, transform)[source]
Apply a 3x3 homogeneous transform to finite 2D coordinates.
- FEAST.alignment.simulate_alignment_rotation(adata, rotation_angle=30.0, data_type='imaging', fit_params=None, expression_params=None, filter_edge_spots=True, edge_margin_ratio=0.03, center_correction=0, keep_bounds=True, min_space=None)[source]
Quick function to generate rotated alignment dataset using simulate_single_slice.
- Parameters:
adata (AnnData) – Input spatial transcriptomics data
rotation_angle (float) – Rotation angle in degrees
data_type (str) – ‘imaging’ or ‘sequencing’
fit_params (Dict[str, Any] | None) – Parameters for model fitting (passed to simulate_single_slice)
expression_params (Dict[str, Any] | None) – Parameters for expression simulation (passed to simulate_single_slice)
center_correction (float | ndarray) – Center point for rotation
keep_bounds (bool) – Whether to keep only spots within original bounds for imaging data
min_space (float | None) – Minimal spacing for sequencing data
filter_edge_spots (bool)
edge_margin_ratio (float)
- Returns:
Tuple of (original_simulated, rotated_simulated) datasets
- Return type:
Tuple[AnnData, AnnData]
- FEAST.alignment.simulate_alignment_warp(adata, distort_level=100, fit_params=None, expression_params=None, filter_edge_spots=True, edge_margin_ratio=0.03, grid_size=3, alpha=1.0, apply_rotation=True)[source]
Quick function to generate TPS-warped alignment dataset using simulate_single_slice.
- Parameters:
adata (AnnData) – Input spatial transcriptomics data
distort_level (float) – Level of spatial distortion
fit_params (Dict[str, Any] | None) – Parameters for model fitting (passed to simulate_single_slice)
expression_params (Dict[str, Any] | None) – Parameters for expression simulation (passed to simulate_single_slice)
grid_size (int) – Grid size for control points
alpha (float) – TPS regularization parameter
apply_rotation (bool) – Whether to apply additional rotation/translation
filter_edge_spots (bool)
edge_margin_ratio (float)
- Returns:
Tuple of (original_simulated, warped_simulated) datasets
- Return type:
Tuple[AnnData, AnnData]
- FEAST.deconvolution.create_deconvolution_benchmark_data(adata, downsampling_factor=0.25, grid_type='hexagonal', cell_type_key=None, alpha=0.01)[source]
Create lower-resolution ST data for deconvolution benchmarking with ground truth proportions.
Parameters:
- adataAnnData
Original ST data
- downsampling_factorfloat
Factor to reduce resolution (0.25 = 4x fewer spots)
- grid_typestr
Grid type (‘hexagonal’, ‘square’, or ‘kmeans’)
- cell_type_keystr
Key in adata.obs containing cell type labels
- alphafloat
Alpha value for the alphashape algorithm
Returns:
- AnnData
Lower-resolution ST data with ground truth proportions
Batch simulation
Notebook 04 uses a BatchDeformation to store three scale coefficients
(D) and offsets (b). Supply them to simulate_batch_effect with
alpha=0 for a simulated baseline or alpha=1 for the full deformation.
Use characterize_batch to estimate coefficients from two measured slices.
- class FEAST.BatchDeformation(D, b, alpha=1.0, name='')[source]
Diagonal affine batch deformation in theta space.
theta’ = [(1-alpha)*I + alpha*diag(D)] @ theta + alpha*b
- D
- Type:
(3,) ndarray – diagonal scaling (d_mu, d_omega, d_pi0)
- b
- Type:
(3,) ndarray – shift vector (b_mu, b_omega, b_pi0)
- alpha
- Type:
float – interpolation strength (0=none, 1=full)
- name
- Type:
str – optional label
- FEAST.characterize_batch(adata_ref, adata_query, *, name='')[source]
Estimate batch deformation (D, b) from two real slices via OLS in theta space.
- For each dimension k in {log_mu, log_omega, logit_pi0}:
theta_query[:, k] = d_k * theta_ref[:, k] + b_k (+ epsilon)
This is the empirical-characterisation counterpart to simulate_batch_effect(). Once (D, b) are estimated, they can be fed to simulate_batch_effect() with alpha in [0, 1] to generate interpolated batch-effect ladder.
- Parameters:
adata_ref (AnnData -- reference (clean) slice)
adata_query (AnnData -- batch-affected slice)
name (str -- optional label for the deformation)
- Returns:
.r2 : (3,) ndarray — per-dimension R² .residual_std: (3,) ndarray — per-dimension residual std dev .n_genes : int — number of common genes used
- Return type:
BatchDeformation with additional diagnostic attributes
- FEAST.simulate_batch_effect(adata_ref, D, b, alpha=1.0, *, random_seed=None, boundary_multiplier=1.1)[source]
Simulate a batch-affected slice from a reference AnnData.
- Pipeline:
Extract per-gene stats from reference -> _gene_stats_from_matrix()
Convert stats to theta -> stats_to_theta()
Apply affine deformation -> apply_batch_deformation()
Convert back to stats -> theta_to_stats()
Convert stats to count-model params -> convert_params_for_new_simulator()
Decode counts from reference intensity -> decode_counts_by_spatial_intensity()
- Parameters:
- Returns:
adata_sim
- Return type:
AnnData – batch-affected slice with preserved spatial pattern
Parameter utilities
Compatibility
generate_from is a deprecated compatibility alias. Use
simulate(reference, target=blueprint, condition_on="domain",
marginal_model="empirical_reference", seed=42) for conditional generation.
Local multi-reference 3D generation
- FEAST.simulate_local_references(reference_slices, target_blueprint, *, label_key, n_references=5, reference_z=None, target_z=None, config=None, random_seed=0, parameter_seed=0, batch_seed=None, count_seed=None, cache_path=None, min_positions=50, batch_sd=0.005, batch_deformation=None, fit_cache=None)[source]
Generate one target with local labels, fixed reference tables and core counts.
With reference_z, selection is bracketed distance weighting (Study 06). Otherwise use the existing group geometry weights (Study 07). Donor slices remain distinct, and their OT/count contribution is limited to missing groups.
n_referencesdefaults to 5. Withoutreference_z, a finite count selects up to that many eligible references separately per modeling group, with existing geometry ranking, reference-name tie breaks, normalized weights and local merging.Noneuses all eligible references per group. Thusn_references=2may select more than two distinct references across the target slice. Changing this count changes the modeling policy.Every active target position, all shared genes, and the complete source support of each selected group are retained; source points are not sampled. Set
config=SimulationConfig(transport_dtype="float32")to opt into float32 solver arithmetic. Float64 remains the default; convergence requirements and precision diagnostics are preserved.
- FEAST.simulate_stack(reference_slices, reference_z_values, target_z_values, target_blueprints, *, label_key='domain', n_references=5, cache_path=None, config=None, random_seed=0)[source]
- Parameters:
- Return type:
- FEAST.calibrate_local_references(reference_slices, *, label_key, n_references=5, reference_z=None, config=None, random_seed=0, cache_path=None, min_positions=50, batch_sd=0.005)[source]
Three deterministic whole-reference holdouts; fit all genes, score 20.
Give each reference a unique uns["reference_name"], the same gene panel
and the label column named by label_key. For atlas transfer,
n_references defaults to five references per modeling region.
Use None to include all eligible references. Stack reconstruction
uses references on both sides of the target z position.