methylseg.MethylStateAssigner
- class methylseg.MethylStateAssigner(window_specs=[(40000, '40kb'), (450000, '450kb')], n_states=4, int_low_cutoff=0.2, int_high_cutoff=0.7, high_cutoff=0.7, out_dir='.', random_state=42, cluster_space='pca', n_pca=5)[source]
Bases:
objectCreate per-CpG window summaries and assign coarse methylation states.
- Parameters:
window_specs (List[Tuple[int, str]])
n_states (int)
int_low_cutoff (float)
int_high_cutoff (float)
high_cutoff (float)
random_state (int | None)
cluster_space (str)
n_pca (int | None)
- __init__(window_specs=[(40000, '40kb'), (450000, '450kb')], n_states=4, int_low_cutoff=0.2, int_high_cutoff=0.7, high_cutoff=0.7, out_dir='.', random_state=42, cluster_space='pca', n_pca=5)[source]
- Parameters:
window_specs (List[Tuple[int, str]]) – List of
(window_size_bp, label)tuples used to summarize local methylation context around each CpG.n_states (int) – Number of coarse methylation states to learn during clustering.
int_low_cutoff (float) – Lower cutoff for intermediate methylation state.
int_high_cutoff (float) – Upper cutoff for intermediate methylation state.
high_cutoff (float) – Cutoff for high methylation state.
out_dir – Directory to save output files.
random_state (int | None) – Random state for reproducibility.
cluster_space (str) – Space in which to perform k-means clustering (‘pca’ or ‘raw’).
n_pca (int | None) – Number of principal components to use if cluster_space is ‘pca’.
Methods
__init__([window_specs, n_states, ...])apply_kmeans_to_emissions(emission_df)Apply a previously trained KMeansMethylationModel to a new emission_df.
apply_kmeans_to_sample(sample_info[, chrom, ...])Apply an already-trained KMeans model to a prepared sample.
build_emission_matrix(positions, betas, ...)Build emission features for one ordered probe sequence.
Calculate clustering-quality metrics in the same feature space used for KMeans.
fit_kmeans_on_emissions(emission_df[, ...])Fit KMeans on emission features using the assigner's configured cluster space.
Return a DataFrame of PCA loadings for the features used in the model.
plot_embedding(emission_df, labels[, ...])Plot PCA or UMAP embeddings for an emission table and state labels.
Plot training-emission histograms stratified by KMeans state.
plot_kmeans_clusters(meth_data, labels[, ...])Plot genomic beta values colored by KMeans-derived state labels.
plot_labels([sample_info, chrom, ...])Plot learned KMeans labels across genomic methylation measurements.
plot_pca_clusters(emission_df, labels[, ...])PCA embedding + loadings, using consistent colors per state.
plot_pca_clusters_with_region(meth_data, ...)Plot PCA clusters while highlighting CpGs overlapping a genomic region.
plot_train_pca_clusters([n_pca_plot, ...])Convenience wrapper to plot the PCA embedding saved from k-means training.
plot_training_embedding(*[, method, ...])Plot embeddings for the cached training sample and labels.
plot_umap_clusters(emission_df, labels[, ...])Plot a 2-D UMAP embedding colored by state labels.
prepare_sample_for_clustering(sample_info[, ...])Prepare probe-level and emission-feature tables for clustering.
preprocess_emission_features(emission_df, ...)Impute and scale emission features for clustering or inference.
resolve_feature_cols(emission_df[, feature_cols])Resolve the emission columns to use for clustering features.
train_kmeans_for_sample(sample_info[, ...])Train a KMeans model on one prepared sample.
- build_emission_matrix(positions, betas, window_specs, int_low_cutoff, int_high_cutoff, high_cutoff)[source]
Build emission features for one ordered probe sequence.
- Parameters:
positions – Genomic positions for each CpG.
betas – Beta values aligned to
positions.window_specs –
(window_size_bp, label)pairs describing the local summary windows to compute.int_low_cutoff – Thresholds used to derive low/intermediate/high proportions inside each window.
int_high_cutoff – Thresholds used to derive low/intermediate/high proportions inside each window.
high_cutoff – Thresholds used to derive low/intermediate/high proportions inside each window.
- Returns:
(X, feature_names)whereXis the numeric emission matrix andfeature_namesare the corresponding column labels.- Return type:
tuple
- preprocess_emission_features(emission_df, feature_cols, fit=False)[source]
Impute and scale emission features for clustering or inference.
- Parameters:
emission_df (DataFrame) – Emission-feature table.
feature_cols (List[str]) – Ordered columns to extract and preprocess.
fit (bool) – If
True, fit a new imputer/scaler pair and return them alongside the transformed matrix. Otherwise, reuse the trained model’s preprocessing objects.
- Returns:
Scaled feature matrix, or
(scaled_values, imputer, scaler)whenfit=True.- Return type:
numpy.ndarray or tuple
- Raises:
ValueError – If preprocessing cannot produce a finite feature matrix or a required trained preprocessing component is missing.
- resolve_feature_cols(emission_df, feature_cols=None)[source]
Resolve the emission columns to use for clustering features.
- Parameters:
emission_df (DataFrame) – Emission-feature table whose columns should be filtered.
feature_cols (List[str] | None) – Optional explicit column list. When omitted, uses all non-count features.
- Returns:
Ordered feature-column names passed to preprocessing and clustering.
- Return type:
list of str
- fit_kmeans_on_emissions(emission_df, feature_cols=None)[source]
Fit KMeans on emission features using the assigner’s configured cluster space.
- Parameters:
emission_df (DataFrame) – Emission-feature table used for clustering.
feature_cols (List[str] | None) – Optional explicit feature-column list. When omitted, uses
resolve_feature_cols.
- Returns:
(model, pca_scores, relabeled_labels)wherepca_scoresisNonewhen clustering in raw feature space.- Return type:
tuple
- apply_kmeans_to_emissions(emission_df)[source]
Apply a previously trained KMeansMethylationModel to a new emission_df.
- Parameters:
emission_df (DataFrame) – Emission-feature table to score with the trained model.
- Returns:
(pca_scores, raw_distances, raw_labels, relabeled_labels)for the supplied emission rows.- Return type:
tuple
- calculate_kmeans_cluster_metrics(emission_df, labels)[source]
Calculate clustering-quality metrics in the same feature space used for KMeans.
- Parameters:
emission_df (DataFrame) – Emission-feature table aligned to
labels.labels (ndarray) – Cluster labels to evaluate in the trained feature space.
- Returns:
Clustering metric values keyed by metric name. Metrics that cannot be computed are returned as
None.- Return type:
dict of str to float or None
- plot_embedding(emission_df, labels, meth_data=None, *, method='pca', sample_info=None, chrom=None, n_components=2, top_n_loadings=5, hexbin=False, hexbin_gridsize=60, hexbin_bins='log', hexbin_mincnt=1, hexbin_alpha=None, hexbin_linewidths=None, interactive=False, include_metrics=True, include_biplot=False, label_title='State', region_start=None, region_end=None, region_chrom=None, use_pca_features=False, use_parallel=True, show_plot=True, state_colors=None)[source]
Plot PCA or UMAP embeddings for an emission table and state labels.
- Parameters:
emission_df (DataFrame) – Emission-feature table to embed.
labels (ndarray) – Cluster or biological state labels aligned to
emission_df.meth_data (DataFrame | None) – Optional probe-level methylation table used for region-aware PCA highlighting.
method (str) – Embedding method, either
"pca"or"umap".sample_info (SampleInfo | None) – Optional sample metadata used for plot titles.
chrom (str | None) – Optional chromosome label used for plot titles and region-aware views.
n_components (int) – Number of embedding dimensions to render.
top_n_loadings (int) – Number of PCA loading features to show in tables and biplots.
hexbin (bool) – If
True, render 2-D PCA as hexbins instead of points.hexbin_gridsize (int) – Hexbin grid resolution for 2-D PCA hexbin plots.
hexbin_bins (str | int | list[float] | ndarray | None) – Hexbin binning strategy for 2-D PCA hexbin plots, for example
"log", an integer bin count, explicit bin edges, orNone.hexbin_mincnt (int | None) – Minimum points required to draw a hexbin in 2-D PCA hexbin plots. Use
Noneto let matplotlib draw all bins.hexbin_alpha (float | None) – Optional global transparency multiplier for 2-D PCA hexbin plots.
hexbin_linewidths (float | None) – Optional hexagon border width for 2-D PCA hexbin plots.
interactive (bool) – If
True, use interactive rendering when supported by the chosen method.include_metrics (bool) – Include clustering-quality metrics where available.
include_biplot (bool) – Overlay top PCA loading vectors on 2-D PCA plots.
label_title (str) – Legend or colorbar title.
region_start (int | None) – Optional genomic interval used to highlight overlapping CpGs in PCA space.
region_end (int | None) – Optional genomic interval used to highlight overlapping CpGs in PCA space.
region_chrom (str | None) – Optional genomic interval used to highlight overlapping CpGs in PCA space.
use_pca_features (bool) – For UMAP, project the trained PCA features instead of scaled raw features.
use_parallel (bool) – Whether to allow UMAP’s parallel execution mode.
show_plot (bool) – If
True, display the figure immediately.state_colors (dict | None) – Optional biological-state color overrides.
- Returns:
Matplotlib or Plotly figure object, depending on the selected rendering path.
- Return type:
object
- plot_training_embedding(*, method='pca', n_components=2, top_n_loadings=5, hexbin=False, hexbin_gridsize=60, hexbin_bins='log', hexbin_mincnt=1, hexbin_alpha=None, hexbin_linewidths=None, interactive=False, include_metrics=True, include_biplot=False, label_title='State', region_start=None, region_end=None, region_chrom=None, use_pca_features=False, use_parallel=True, show_plot=True, state_colors=None)[source]
Plot embeddings for the cached training sample and labels.
- Parameters:
method (str) – Embedding method, either
"pca"or"umap".n_components (int) – Number of embedding dimensions to render.
top_n_loadings (int) – Number of PCA loading features to show in tables and biplots.
hexbin (bool) – If
True, render 2-D PCA as hexbins instead of points.hexbin_gridsize (int) – Hexbin grid resolution for 2-D PCA hexbin plots.
hexbin_bins (str | int | list[float] | ndarray | None) – Hexbin binning strategy for 2-D PCA hexbin plots, for example
"log", an integer bin count, explicit bin edges, orNone.hexbin_mincnt (int | None) – Minimum points required to draw a hexbin in 2-D PCA hexbin plots. Use
Noneto let matplotlib draw all bins.hexbin_alpha (float | None) – Optional global transparency multiplier for 2-D PCA hexbin plots.
hexbin_linewidths (float | None) – Optional hexagon border width for 2-D PCA hexbin plots.
interactive (bool) – If
True, use interactive rendering when supported.include_metrics (bool) – Include clustering-quality metrics where available.
include_biplot (bool) – Overlay top PCA loading vectors on 2-D PCA plots.
label_title (str) – Legend or colorbar title.
region_start (int | None) – Optional genomic interval used to highlight overlapping training CpGs in PCA space.
region_end (int | None) – Optional genomic interval used to highlight overlapping training CpGs in PCA space.
region_chrom (str | None) – Optional genomic interval used to highlight overlapping training CpGs in PCA space.
use_pca_features (bool) – For UMAP, project the trained PCA features instead of scaled raw features.
use_parallel (bool) – Whether to allow UMAP’s parallel execution mode.
show_plot (bool) – If
True, display the figure immediately.state_colors (dict | None) – Optional biological-state color overrides.
- Returns:
Matplotlib or Plotly figure object.
- Return type:
object
- plot_umap_clusters(emission_df, labels, chrom=None, sample_name=None, use_pca=False, use_parallel=True, show_plot=True)[source]
Plot a 2-D UMAP embedding colored by state labels.
- Parameters:
emission_df (DataFrame) – Emission-feature table to embed.
labels (ndarray) – State labels aligned to
emission_df.chrom (str | None) – Optional chromosome label used in the plot title.
sample_name (str | None) – Optional sample identifier used in the plot title.
use_pca (bool) – If
True, run UMAP on the trained PCA features instead of scaled raw features.use_parallel (bool) – If
True, allow UMAP to disable a fixed random seed for parallel execution.show_plot (bool) – If
True, display the figure immediately.
- Returns:
Scatter plot of the UMAP embedding.
- Return type:
matplotlib.figure.Figure
- plot_kmeans_clusters(meth_data, labels, chrom=None, sample_name=None, feature_cols_for_table=None, interactive=False)[source]
Plot genomic beta values colored by KMeans-derived state labels.
- Parameters:
meth_data (DataFrame) – Probe-level methylation table containing genomic positions and beta values.
labels (ndarray) – Cluster or biological state labels aligned to
meth_data.chrom (str | None) – Optional chromosome label used in the plot title.
sample_name (str | None) – Optional sample identifier used in the plot title.
feature_cols_for_table (List[str] | None) – Optional feature list to display alongside the static scatter plot.
interactive (bool) – If
True, render the Plotly version instead of the static matplotlib figure.
- Returns:
Matplotlib or Plotly figure object.
- Return type:
object
- plot_pca_clusters(emission_df, labels, n_pca_plot=2, top_n_loadings=5, pca_hexbin=False, hexbin_gridsize=60, hexbin_bins='log', hexbin_mincnt=1, hexbin_alpha=None, hexbin_linewidths=None, interactive=False, include_kmeans_metrics=True, include_biplot=False, label_title='State', sample_name=None, chrom=None, show_plot=True, state_colors=None)[source]
PCA embedding + loadings, using consistent colors per state.
- Parameters:
emission_df (DataFrame) – Emission-feature table to embed with PCA.
labels (ndarray) – Cluster or biological state labels aligned to
emission_df.n_pca_plot (int) – Number of PCA dimensions to render, usually
2or3.top_n_loadings (int) – Number of loading features to show in the summary table.
pca_hexbin (bool) – If
True, render 2-D PCA with hexbins instead of points.hexbin_gridsize (int) – Hexbin grid resolution for 2-D PCA hexbin plots.
hexbin_bins (str | int | list[float] | ndarray | None) – Hexbin binning strategy for 2-D PCA hexbin plots.
hexbin_mincnt (int | None) – Minimum points required to draw a hexbin in 2-D PCA hexbin plots.
hexbin_alpha (float | None) – Optional transparency multiplier for 2-D PCA hexbin plots.
hexbin_linewidths (float | None) – Optional border width for 2-D PCA hexbin plots.
interactive (bool) – If
True, use interactive rendering when supported.include_kmeans_metrics (bool) – Include clustering-quality metrics in the plotted annotation.
include_biplot (bool) – Overlay top PCA loading vectors on 2-D PCA plots.
label_title (str) – Legend or colorbar title.
sample_name (str | None) – Optional sample identifier used in the plot title.
chrom (str | None) – Optional chromosome label used in the plot title.
show_plot (bool) – If
True, display the figure immediately.state_colors (dict | None) – Optional biological-state color overrides.
- Returns:
object – Matplotlib or Plotly figure object from the PCA plotting backend.
Set
include_kmeans_metrics=Falseto skip the expensive clusteringquality metric calculation and annotation.
In hexbin mode,
hexbin_mincntis evaluated separately for eachstate and hexagon. The default of one keeps sparse chromosome-level
plots visible; use a larger value to show only dense bins.
- plot_pca_clusters_with_region(meth_data, emission_df, labels, region_start, region_end, region_chrom=None, n_pca_plot=2, top_n_loadings=5, pca_hexbin=False, hexbin_gridsize=60, hexbin_bins='log', hexbin_mincnt=1, hexbin_alpha=None, hexbin_linewidths=None, interactive=False, include_kmeans_metrics=True, include_biplot=False, label_title='State', sample_name=None, chrom=None, show_plot=True, state_colors=None)[source]
Plot PCA clusters while highlighting CpGs overlapping a genomic region.
- Parameters:
meth_data (DataFrame) – Probe-level methylation table containing genomic coordinates.
emission_df (DataFrame) – Emission-feature table aligned to
meth_data.labels (ndarray) – Cluster or biological state labels aligned to both tables.
region_start (int) – Inclusive genomic interval used for highlighting.
region_end (int) – Inclusive genomic interval used for highlighting.
region_chrom (str | None) – Chromosome of the highlighted interval. Required when
meth_dataspans multiple chromosomes.n_pca_plot (int) – Number of PCA dimensions to render.
top_n_loadings (int) – Number of PCA loading features to show in the side table.
pca_hexbin (bool) – If
True, render 2-D PCA as hexbins instead of points.hexbin_gridsize (int) – Hexbin grid resolution for 2-D PCA hexbin plots.
hexbin_bins (str | int | list[float] | ndarray | None) – Hexbin binning strategy for 2-D PCA hexbin plots, for example
"log", an integer bin count, explicit bin edges, orNone.hexbin_mincnt (int | None) – Minimum points required to draw a hexbin in 2-D PCA hexbin plots. Use
Noneto let matplotlib draw all bins.hexbin_alpha (float | None) – Optional global transparency multiplier for 2-D PCA hexbin plots.
hexbin_linewidths (float | None) – Optional hexagon border width for 2-D PCA hexbin plots.
interactive (bool) – If
True, use interactive rendering when supported.include_kmeans_metrics (bool) – Include clustering-quality metrics in the plot.
include_biplot (bool) – Overlay top PCA loading vectors on 2-D PCA plots.
label_title (str) – Legend or colorbar title.
sample_name (str | None) – Optional sample identifier used in the plot title.
chrom (str | None) – Optional chromosome label used in the plot title.
show_plot (bool) – If
True, display the figure immediately.state_colors (dict | None) – Optional biological-state color overrides.
- Returns:
Matplotlib or Plotly figure object from the PCA plotting backend.
- Return type:
object
- plot_train_pca_clusters(n_pca_plot=2, top_n_loadings=5, pca_hexbin=False, hexbin_gridsize=60, hexbin_bins='log', hexbin_mincnt=1, hexbin_alpha=None, hexbin_linewidths=None, interactive=False, include_kmeans_metrics=True, include_biplot=False, region_start=None, region_end=None, region_chrom=None, show_plot=True)[source]
Convenience wrapper to plot the PCA embedding saved from k-means training.
- Parameters:
n_pca_plot (int) – Number of PCA dimensions to render, usually
2or3.top_n_loadings (int) – Number of loading features to show in the summary table.
pca_hexbin (bool) – If
True, render 2-D PCA with hexbins instead of points.hexbin_gridsize (int) – Hexbin grid resolution for 2-D PCA hexbin plots.
hexbin_bins (str | int | list[float] | ndarray | None) – Hexbin binning strategy for 2-D PCA hexbin plots.
hexbin_mincnt (int | None) – Minimum points required to draw a hexbin in 2-D PCA hexbin plots.
hexbin_alpha (float | None) – Optional transparency multiplier for 2-D PCA hexbin plots.
hexbin_linewidths (float | None) – Optional border width for 2-D PCA hexbin plots.
interactive (bool) – If
True, use interactive rendering when supported.include_kmeans_metrics (bool) – Include clustering-quality metrics in the plotted annotation.
include_biplot (bool) – Overlay top PCA loading vectors on 2-D PCA plots.
region_start (int | None) – Optional genomic start coordinate for region highlighting.
region_end (int | None) – Optional genomic end coordinate for region highlighting.
region_chrom (str | None) – Optional chromosome for region highlighting.
show_plot (bool) – If
True, display the figure immediately.
- Returns:
Matplotlib or Plotly figure object from the PCA plotting backend.
- Return type:
object
- prepare_sample_for_clustering(sample_info, chrom=None, windows_to_use=None)[source]
Prepare probe-level and emission-feature tables for clustering.
- Parameters:
sample_info (SampleInfo) – Prepared sample whose methylation rows should be summarized.
chrom (str | None) – Optional chromosome restriction for per-chromosome preparation.
windows_to_use (List[str] | None) – Optional subset of configured window labels to retain in the emission matrix.
- Returns:
(meth_data, emission_df)aligned for downstream clustering or plotting.- Return type:
tuple
- train_kmeans_for_sample(sample_info, train_chroms=None, windows_to_use=None, feature_cols=None, max_cpg_per_chrom=50000, sampling_random_state=None)[source]
Train a KMeans model on one prepared sample.
- Parameters:
sample_info (SampleInfo) – Prepared sample used to build the training emission matrix.
train_chroms (List[str] | None) – Optional chromosome list to use for training. When omitted, uses the canonical autosomes present in the sample.
windows_to_use (List[str] | None) – Optional subset of configured window labels to retain in the emission matrix.
feature_cols (List[str] | None) – Optional explicit feature-column list passed to clustering.
max_cpg_per_chrom (int | None) – Optional maximum CpGs to sample per chromosome before fitting.
sampling_random_state (int | None) – Optional random seed controlling per-chromosome subsampling.
- Returns:
(model, meth_data, emission_df, pca_scores, labels)for the fitted training sample.- Return type:
tuple
- apply_kmeans_to_sample(sample_info, chrom=None, windows_to_use=None, sample_meth_data=None)[source]
Apply an already-trained KMeans model to a prepared sample.
- Parameters:
sample_info (SampleInfo) – Prepared sample to score with the trained model.
chrom (str | None) – Optional chromosome restriction for per-chromosome scoring.
windows_to_use (List[str] | None) – Optional subset of configured window labels to retain in the emission matrix.
sample_meth_data (DataFrame | None) – Reserved compatibility argument for prefiltered methylation rows.
- Returns:
(meth_data, emission_df, pca_scores, raw_distances, raw_labels, relabeled_labels)for the supplied sample.- Return type:
tuple
- get_pca_loadings()[source]
Return a DataFrame of PCA loadings for the features used in the model.
- Return type:
DataFrame
- plot_labels(sample_info=None, chrom=None, sample_info_removed=None, overlay_regions_df=None, overlay_style='state', region_start=None, region_end=None, x_col='CpG_beg', y_col='beta', label_title=None, show_plot=True, max_points=120000, state_colors=None)[source]
Plot learned KMeans labels across genomic methylation measurements.
Use this method when only a fitted assigner is available. It prepares KMeans labels for cached training data or a supplied sample, then uses the shared state-label renderer for overlays and viewport controls.
- Parameters:
sample_info (SampleInfo | None)
chrom (str | None)
sample_info_removed (DataFrame | None)
overlay_regions_df (DataFrame | None)
overlay_style (str)
region_start (int | None)
region_end (int | None)
x_col (str)
y_col (str)
label_title (str | None)
show_plot (bool)
max_points (int)
state_colors (dict | None)
- Return type:
object | None
- plot_feature_distributions_by_kmeans_state(show_plots=True, state_colors=None, state_cutoffs=None)[source]
Plot training-emission histograms stratified by KMeans state.
state_cutoffsoptionally controls the biological-state display labels; it does not change the KMeans assignments.- Parameters:
show_plots (bool)
state_colors (dict | None)
state_cutoffs (dict | None)