onehot

One-hot encoding and clustering helpers for aligned protein sequence windows.

Example Data

df = pd.DataFrame(
    {
        "site_seq": [
            "AASTYGVAKR",
            "GGSTYGVAKR",
            "AASTFGVAKR",
            "PPSTYGVAKK",
            "VVSTYGIARR",
        ]
    }
)
df.shape
df.head()

Encoding


source

onehot_encode


def onehot_encode(
    sequences:Sequence, # aligned protein sequence windows
    transform_colname:bool=True, # shift feature names around the center residue
    n:int=20, # center position used for transformed column labels
)->DataFrame:

One-hot encode aligned protein sequence windows.

onehot_encode(df["site_seq"]).head()

source

onehot_encode_df


def onehot_encode_df(
    df:DataFrame, # dataframe containing aligned sequences
    seq_col:str='site_seq', # column containing the sequence strings
    kwargs:object
)->DataFrame: # forwarded to onehot_encode

One-hot encode a sequence column from a dataframe.

onehot = onehot_encode_df(df, seq_col="site_seq")
onehot.head()

Clustering


source

run_kmeans


def run_kmeans(
    onehot:DataFrame, # one-hot encoded sequence matrix
    n:int=2, # number of clusters to fit
    seed:int=42, # random seed for KMeans
)->object:

Fit KMeans to one-hot encoded features and return the assigned labels.

run_kmeans(onehot, n=2)

source

filter_range_columns


def filter_range_columns(
    df:DataFrame, # one-hot encoded dataframe with position-prefixed column names
    low:int=-10, # lower bound for retained positions
    high:int=10, # upper bound for retained positions
)->DataFrame:

Filter one-hot columns to a position window around the center residue.

onehot_10 = filter_range_columns(onehot, low=-10, high=10)
onehot_10.head()

Elbow Method


source

get_clusters_elbow


def get_clusters_elbow(
    encoded_data:DataFrame, # one-hot encoded feature matrix
    max_cluster:int=400, # largest cluster count to evaluate
    interval:int=50, # step size between tested cluster counts
)->None:

Plot the elbow curve for a range of KMeans cluster counts.

get_clusters_elbow(onehot, max_cluster=5, interval=2)