methylseg.MethylStateAnalyzer
- class methylseg.MethylStateAnalyzer(assigner, out_dir='.')[source]
Bases:
objectAnalyze learned state separation and define rule-based CpG states.
Uses KMeans assignments as a reference for inspecting state separation and evaluating rule concordance. It also defines, tunes, and applies interpretable cutoff rules that characterize each CpG as a biological methylation state.
- Parameters:
assigner (MethylStateAssigner)
- __init__(assigner, out_dir='.')[source]
Initialize rule-based state analysis around a fitted state assigner.
- Parameters:
assigner (MethylStateAssigner) – State assigner that provides training emissions, KMeans labels, and feature configuration.
out_dir – Directory for analysis artifacts and figures.
Methods
__init__(assigner[, out_dir])Initialize rule-based state analysis around a fitted state assigner.
define_states_by_rules(sample_info[, chrom, ...])Apply the current rule-based cutoff set to a sample or emission table.
define_states_by_rules_param(meth_emissions, ...)Apply rule-based state labels with tunable per-window PMD cutoffs.
Evaluate rule-based labels against KMeans cluster labels as ground truth.
evaluate_rules_against_kmeans(meth_emissions)Apply rule-based states and compare to KMeans labels.
optimize_rule_params_random([n_iter, ...])Tune rule-based cutoffs with random search against KMeans labels.
plot_labels([sample_info, chrom, ...])Plot KMeans or rule-based labels to analyze state relationships.
Print the active rule-based state definitions in a compact form.
set_state_cutoffs([beta_low_max, ...])Simple manual state cutoff setter with clean pythonic defaults.
set_state_cutoffs_from_yaml(yaml_file)Load rule cutoffs from a YAML file written by
MethylSegConfig.- define_states_by_rules_param(meth_emissions, beta_low_max, beta_high_min, pmd_cutoffs)[source]
Apply rule-based state labels with tunable per-window PMD cutoffs.
- Parameters:
meth_emissions (DataFrame) – Emission table containing
betaand the per-window summary columns used by the PMD rules.beta_low_max (float) – Upper beta threshold for the low-methylation regime.
beta_high_min (float) – Lower beta threshold for the high-methylation regime.
pmd_cutoffs (Dict[str, Dict[str, float]]) – Mapping of window label to rule cutoffs with
int_min,std_max,high_max, andlow_maxentries.
- Returns:
Array of
MethylationStatesvalues for each input row.- Return type:
numpy.ndarray
- evaluate_rules_against_kmeans(meth_emissions, kmeans_labels=None, **rule_params)[source]
Apply rule-based states and compare to KMeans labels.
- Parameters:
meth_emissions (DataFrame) – Emission table to label with the supplied rule parameters.
kmeans_labels (ndarray) – Reference KMeans labels aligned to
meth_emissions.rule_params – Keyword arguments forwarded to
define_states_by_rules_param. Expected keys arebeta_low_max,beta_high_min, andpmd_cutoffs.
- Returns:
(metrics_dict, rule_labels_array)comparing the supplied KMeans labels against the derived rule-based labels.- Return type:
tuple
- optimize_rule_params_random(n_iter=500, score_key='F1_macro', random_state=42, param_distributions=None)[source]
Tune rule-based cutoffs with random search against KMeans labels.
- Parameters:
n_iter (int) – Number of random parameter draws to evaluate.
score_key (str) – Metric name from
evaluate_rules_against_kmeans()used to pick the best rule set.random_state (int) – Seed for reproducible sampling.
param_distributions (dict | None) – Optional nested dictionary describing the search ranges. When omitted, defaults are created for each window label in
assigner.window_specs.
- define_states_by_rules(sample_info, chrom=None, sample_emissions=None)[source]
Apply the current rule-based cutoff set to a sample or emission table.
- Parameters:
sample_info (SampleInfo) – Prepared methylation sample used when
sample_emissionsis not supplied.chrom – Optional chromosome restriction passed through to emission preparation.
sample_emissions (DataFrame) – Precomputed emission table to label directly.
- Returns:
Rule-based
MethylationStatesassignments for each emission row.- Return type:
numpy.ndarray
- Raises:
ValueError – If rule cutoffs have not been defined.
- set_state_cutoffs_from_yaml(yaml_file)[source]
Load rule cutoffs from a YAML file written by
MethylSegConfig.- Parameters:
yaml_file (str) – Path to a serialized methylseg YAML config file.
- Returns:
Updates
state_cutoffsand the manual-cutoff flag from the YAML contents.- Return type:
None
- set_state_cutoffs(beta_low_max=None, beta_high_min=None, pmd_cutoffs=None)[source]
Simple manual state cutoff setter with clean pythonic defaults.
- Parameters:
beta_low_max (float | None) – Upper beta threshold for the low-methylation state. Uses the package default when omitted.
beta_high_min (float | None) – Lower beta threshold for the high-methylation state. Uses the package default when omitted.
pmd_cutoffs (dict | None) – Optional per-window PMD cutoff mapping. Missing values fall back to the package defaults for every configured window.
- Returns:
Stores the resolved cutoff dictionary on the analyzer.
- Return type:
None
- evaluate_clustering_concordance(use_train_data=True, sample_info=None, chrom=None)[source]
Evaluate rule-based labels against KMeans cluster labels as ground truth.
- Parameters:
use_train_data (bool) – If
True, compare cached training labels. Otherwise, generate labels forsample_info.sample_info (SampleInfo | None) – Sample to evaluate when
use_train_dataisFalse.chrom (str | None) – Optional chromosome restriction for non-training evaluation.
- Returns:
Confusion matrix comparing KMeans labels to rule-based labels.
- Return type:
pandas.DataFrame
- plot_labels(sample_info=None, chrom=None, sample_info_removed=None, label_source='kmeans', 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 KMeans or rule-based labels to analyze state relationships.
This shared analysis helper renders learned KMeans clusters alongside rule-derived clusters so their separation, agreement, and rule-based CpG characterization can be inspected with the same plot controls.
- Parameters:
sample_info (SampleInfo | None) – Sample to analyze. When omitted, uses the cached training data.
chrom (str | None) – Optional chromosome restriction for sample-level plotting.
sample_info_removed (DataFrame | None) – Optional table of CpGs removed during preprocessing to show as a background layer.
label_source (str) – Label family to plot, either
"kmeans"or"rule_based".overlay_regions_df (DataFrame | None) – Optional region table used to recolor points by overlapping intervals.
overlay_style (str) – Overlay mode, either
"state"or"highlight".region_start (int | None) – Optional genomic start coordinate for x-axis zooming.
region_end (int | None) – Optional genomic end coordinate for x-axis zooming.
x_col (str) – Probe-level column used for the x-axis.
y_col (str) – Probe-level column used for the y-axis.
label_title (str | None) – Optional legend title override.
show_plot (bool) – If
True, display the Plotly figure immediately.max_points (int) – Maximum number of plotted points before downsampling.
state_colors (dict | None) – Optional biological-state color overrides.
- Returns:
plotly.graph_objects.Figure – Interactive beta scatter plot for the requested labels.
Region args only zoom the x-axis viewport; they do not create a
highlight overlay unless one is passed explicitly.