### Install glycowork from GitHub Source: https://bojarlab.github.io/glycowork Install the latest development version of glycowork directly from its GitHub repository. ```bash pip install git+https://github.com/BojarLab/glycowork.git import glycowork ``` -------------------------------- ### Example Usage of quantify_motifs Source: https://bojarlab.github.io/glycowork/motif.html An example demonstrating how to call the `quantify_motifs` function with sample data and specified feature sets. ```python quantify_motifs(test_df.iloc[:, 1:], test_df.iloc[:, 0].values.tolist(), ['known', 'exhaustive']) ``` -------------------------------- ### Install glycowork with optional extras Source: https://bojarlab.github.io/glycowork Install glycowork with optional dependencies for specialized use cases like machine learning or chemical property analysis. ```bash pip install glycowork[ml] ``` ```bash pip install glycowork[chem] ``` ```bash pip install glycowork[all] ``` -------------------------------- ### Install Glycowork with ML Dependencies Source: https://bojarlab.github.io/glycowork/core.html Install the glycowork package with optional dependencies for machine learning, which may require a GPU. ```bash !pip install "glycowork[ml]" ``` -------------------------------- ### Example Usage of annotate_dataset Source: https://bojarlab.github.io/glycowork/motif.html Demonstrates how to use the annotate_dataset function with a sample list of glycans. The output is printed to the console. ```python glycans = ['Man(a1-3)[Man(a1-6)][Xyl(b1-2)]Man(b1-4)GlcNAc(b1-4)[Fuc(a1-3)]GlcNAc', 'Man(a1-2)Man(a1-2)Man(a1-3)[Man(a1-3)Man(a1-6)]Man(b1-4)GlcNAc(b1-4)GlcNAc', 'GalNAc(a1-4)GlcNAcA(a1-4)[GlcN(b1-7)]Kdo(a2-5)[Kdo(a2-4)]Kdo(a2-6)GlcN4P(b1-6)GlcN4P'] print("Annotate Test") out = annotate_dataset(glycans) ``` -------------------------------- ### Install glycowork via pip Source: https://bojarlab.github.io/glycowork Install the glycowork package using pip. This is the standard method for installing Python packages. ```bash pip install glycowork import glycowork ``` -------------------------------- ### Example of a Random Glycan Output Source: https://bojarlab.github.io/glycowork/motif.html Shows an example of the string representation of a single random glycan that might be returned by the get_random_glycan function. ```text 'Man(b1-2)Man(b1-2)Man(a1-2)Man(a1-2)Man' ``` -------------------------------- ### PyTorch Neural Network Example Source: https://bojarlab.github.io/glycowork/ml.html Illustrates a basic PyTorch neural network structure using nn.Module. This example shows how to define convolutional layers and a forward pass. ```python import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) ``` -------------------------------- ### Install Fair-ESM and Train LectinOracle Source: https://bojarlab.github.io/glycowork/examples.html Install the fair-esm package and import necessary modules for LectinOracle. This snippet prepares a model using ESMC representations for protein sequences to predict glycan binding. ```python !pip install fair-esm from esm.models.esmc import ESMC from glycowork.ml.inference import get_esmc_representations, get_lectin_preds from glycowork.ml.models import prep_model model = ESMC.from_pretrained("esmc_300m") rep = get_esmc_representations(["QWERTFVCF"], model) leor = prep_model("LectinOracle", 1, trained = True) get_lectin_preds("QWERTFVCF", ['Neu5Ac(a2-6)GalNAc', 'Gal(b1-4)Glc'], leor, rep) ``` -------------------------------- ### Example Usage of get_lectin_array Source: https://bojarlab.github.io/glycowork/motif.html Demonstrates how to use the `get_lectin_array` function with sample data. Ensure the `lectin_array_data_loader` is accessible and the data is loaded correctly. ```python lectin_df = lectin_array_data_loader.A549_influenza_PMID33046650 get_lectin_array(lectin_df, [5,6,7], [8,9,10]) ``` -------------------------------- ### Example Usage of get_glycoshift_per_site Source: https://bojarlab.github.io/glycowork/motif.html Demonstrates how to use the `get_glycoshift_per_site` function with loaded human milk glycoproteomics data. It specifies the data source and the groups to compare. ```python df_milk = glycoproteomics_data_loader.human_milk_N_PMID34087070 get_glycoshift_per_site(df_milk, ['Colostrum1', 'Colostrum2', 'Colostrum3'], ['Mature1', 'Mature2', 'Mature3']) ``` -------------------------------- ### Install PyTorch and Torch-Geometric Source: https://bojarlab.github.io/glycowork/examples.html Install specific versions of PyTorch and Torch-Geometric for deep learning. It's recommended to keep these package versions consistent, especially when using pre-trained models. ```bash !pip install torch==2.5.1 !pip install torch-geometric==2.6.0 ``` -------------------------------- ### Example Usage of get_time_series Source: https://bojarlab.github.io/glycowork/motif.html Demonstrates how to create a sample DataFrame and use it with the get_time_series function. The DataFrame is structured with sample IDs and glycan abundances. ```python t_dic = {} t_dic["ID"] = ["D1_h5_r1", "D1_h5_r2", "D1_h5_r3", "D1_h10_r1", "D1_h10_r2", "D1_h10_r3", "D1_h15_r1", "D1_h15_r2", "D1_h15_r3"] t_dic["Neu5Ac(a2-3)Gal(b1-4)GlcNAc(b1-6)[Gal(b1-3)]GalNAc"] = [0.33, 0.31, 0.35, 1.51, 1.57, 1.66, 2.11, 2.04, 2.09] t_dic["Fuc(a1-2)Gal(b1-3)GalNAc"] = [0.78, 1.01, 0.98, 0.88, 1.11, 0.72, 1.22, 1.00, 0.54] t_dic["Neu5Ac(a2-6)GalNAc"] = [0.11, 0.09, 0.14, 0.02, 0.07, 0.10, 0.11, 0.09, 0.08] get_time_series(pd.DataFrame(t_dic).set_index("ID").T) ``` -------------------------------- ### Setup Optimizer, Scheduler, and Loss Criterion Source: https://bojarlab.github.io/glycowork/ml.html Prepares the optimizer, learning rate scheduler, and loss criterion for model training. Supports multiclass, binary, and regression tasks, with options for SAM/GSAM optimizers and learning rate warm-up. ```python def training_setup( model:Module, # graph neural network for analyzing glycans lr:float, # learning rate lr_patience:int=4, # epochs before reducing learning rate factor:float=0.2, # factor to multiply lr on reduction weight_decay:float=0.0001, # regularization parameter mode:str='multiclass', # type of prediction task num_classes:int=2, # number of classes for classification gsam_alpha:float=0.0, # if >0, uses GSAM instead of SAM optimizer warmup_epochs:int=5, # if >0, uses a learning rate warm-up schedule for training stability )->tuple: # optimizer, scheduler, criterion ``` -------------------------------- ### Example Usage of get_differential_expression Source: https://bojarlab.github.io/glycowork/motif.html Demonstrates how to call the `get_differential_expression` function with specific sample groups and motif analysis enabled. This example uses a loaded DataFrame and specifies column indices for two groups, setting `motifs` to True and `paired` to True. ```python test_df = glycomics_data_loader.human_skin_O_PMC5871710_BCC res = get_differential_expression(test_df, group1 = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39], group2 = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40], motifs = True, paired = True) res ``` -------------------------------- ### Example Usage of get_insight Source: https://bojarlab.github.io/glycowork/motif.html Demonstrates how to call the get_insight function with a specific glycan string to retrieve and display its meta-information, including species, phyla, motifs, and GlyTouCan ID. ```python print("Test get_insight with 'Man(a1-3)[Man(a1-6)]Man(b1-4)GlcNAc(b1-4)[Fuc(a1-6)]GlcNAc'") get_insight('Man(a1-3)[Man(a1-6)]Man(b1-4)GlcNAc(b1-4)[Fuc(a1-6)]GlcNAc') ``` -------------------------------- ### Example Usage of get_class Source: https://bojarlab.github.io/glycowork/motif.html Demonstrates how to use the get_class function with a complex glycan structure. The function returns the determined class of the glycan. ```python get_class("Gal(b1-4)GlcNAc(b1-2)Man(a1-3)[Gal(b1-4)GlcNAc(b1-2)Man(a1-6)]Man(b1-4)GlcNAc(b1-4)[Fuc(a1-6)]GlcNAc") ``` -------------------------------- ### Annotate a glycan sequence for motifs Source: https://bojarlab.github.io/glycowork/motif.html This example demonstrates how to call the `annotate_glycan` function with a specific IUPAC-condensed glycan sequence to count occurrences of known motifs. ```python annotate_glycan("Neu5Ac(a2-3)Gal(b1-4)[Fuc(a1-3)]GlcNAc(b1-2)Man(a1-3)[Gal(b1-4)GlcNAc(b1-2)Man(a1-6)]Man(b1-4)GlcNAc(b1-4)[Fuc(a1-6)]GlcNAc") ``` -------------------------------- ### Example of Mismatched Glycans and Scores Source: https://bojarlab.github.io/glycowork/examples.html This snippet displays a list of glycans that were misclassified by the model, along with their corresponding mismatch scores. It helps in understanding the model's limitations. ```python [ ('Gal(b1-4)GlcNAc(b1-3)Gal(b1-4)Glc-ol', 0.666021466255188), ('Gal(b1-4)GlcNAc(b1-2)Man(a1-6)[GlcNAc(b1-2)Man(a1-3)]Man(b1-4)GlcNAc(b1-4)[Fuc(a1-6)]GlcNAc', 0.8374393582344055), ('Gal(b1-3)[Fuc(a1-4)]GlcNAc(b1-3)Gal(b1-4)Glc-ol', 0.8031653165817261), ('Neu5Ac(a2-3)Gal(b1-3/4)GlcNAc(b1-2)Man(a1-3)[Man(a1-3)[Man(a1-6)]Man(a1-6)]Man(b1-4)GlcNAc(b1-4)[Fuc(a1-6)]GlcNAc', 0.9542927145957947), ('Gal(b1-3)[Neu5Ac(a2-6)]GlcNAc(b1-3)Gal(b1-4)Glc-ol', 0.7572895884513855), ('Fuc(a1-3/4)[Gal(b1-3/4)]GlcNAc(b1-3)Gal(b1-4)GlcNAc(b1-2)[Fuc(a1-3/4)[Gal(b1-3/4)]GlcNAc(b1-4)]Man(a1-3)[Fuc(a1-3/4)[Gal(b1-3/4)]GlcNAc(b1-2)[Fuc(a1-3/4)[Gal(b1-3/4)]GlcNAc(b1-6)]Man(a1-6)]Man(b1-4)GlcNAc(b1-4)[Fuc(a1-6)]GlcNAc', 0.7792727947235107), ('Gal(b1-3/4)GlcNAc(b1-2/4)[GlcNAc(b1-2/4)]Man(a1-3)[Man(a1-3)[Man(a1-6)]Man(a1-6)]Man(b1-4)GlcNAc(b1-4)[Fuc(a1-6)]GlcNAc', 0.889919102191925), ('{Gal(b1-3/4)GlcNAc(b1-3)}{Gal(b1-3/4)GlcNAc(b1-3)}{Gal(b1-3/4)GlcNAc(b1-3)}{Gal(b1-3/4)GlcNAc(b1-3)}{Fuc(a1-2/3/4)}Fuc(a1-3)[Gal(b1-4)]GlcNAc(b1-2)Man(a1-3)[Gal(b1-4)GlcNAc(b1-2)Man(a1-6)]Man(b1-4)GlcNAc(b1-4)[Fuc(a1-6)]GlcNAc', 0.3473208248615265), ('Gal(b1-4)Glc-ol', 0.6590997576713562), ('Gal(b1-4)GlcNAc(b1-2)Man(a1-3)[Man(a1-3)[Man(a1-6)]Man(a1-6)]Man(b1-4)GlcNAc(b1-4)GlcNAc', 0.8307253122329712)] ``` -------------------------------- ### Get glycoletter to index mapping Source: https://bojarlab.github.io/glycowork/motif.html Generates a dictionary that maps each unique glycoletter found in a list of glycans to a unique integer index. This is useful for numerical representation of glycans. ```python def get_lib( glycan_list:list, # List of IUPAC-condensed glycan sequences )->dict: # Dictionary of glycoletter:index mappings ``` ```python get_lib(['Man(a1-3)[Man(a1-6)]Man(b1-4)GlcNAc(b1-4)GlcNAc', 'Man(a1-2)Man(a1-3)[Man(a1-6)]Man(b1-4)GlcNAc(b1-4)GlcNAc']) ``` ```python {'GlcNAc': 0, 'Man': 1, 'a1-2': 2, 'a1-3': 3, 'a1-6': 4, 'b1-4': 5} ``` -------------------------------- ### Example Usage of get_roc Source: https://bojarlab.github.io/glycowork/motif.html Demonstrates how to call the get_roc function with specified groups, enabling motif analysis and paired sample comparison. This call aims to find discriminatory features between group1 and group2. ```python get_roc(test_df, group1 = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39], group2 = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40], motifs = True, paired = True) ``` -------------------------------- ### Model Preparation Wrapper Source: https://bojarlab.github.io/glycowork/ml.html A wrapper function to instantiate, initialize, and move a PyTorch model to the GPU. Supports different model types and pretrained options. ```python def prep_model( model_type:Literal, # type of model to create num_classes:int, # number of unique classes for classification libr:dict[str, int] | None=None, # dictionary of form glycoletter:index trained:bool=False, # whether to use pretrained model hidden_dim:int=128, # hidden dimension for the model (SweetNet only) )->Module: # initialized PyTorch model ``` -------------------------------- ### Get Reaction Flow Source: https://bojarlab.github.io/glycowork/network.html Extracts aggregated flow values for reactions within a biosynthetic network. Supports sum or mean aggregation. ```python def get_reaction_flow( network:DiGraph, # Biosynthetic network res:dict, # Flow results as returned by get_maximum_flow aggregate:str | None=None, # Aggregation: sum/mean/None )->dict[str, list[float]] | dict[str, float]: # Reaction flows (reaction: flow) ``` -------------------------------- ### Weight Initialization Function Source: https://bojarlab.github.io/glycowork/ml.html Initializes the linear layers of a PyTorch model using specified algorithms like 'sparse', 'kaiming', or 'xavier'. ```python def init_weights( model:Module, # neural network for analyzing glycans mode:str='sparse', # initialization algorithm: 'sparse', 'kaiming', 'xavier' sparsity:float=0.1, # proportion of sparsity after initialization )->None: ``` -------------------------------- ### Create a custom dataframe for tissue associations Source: https://bojarlab.github.io/glycowork/glycan_data.html Example of calling the build_custom_df function to create a dataframe specifically for tissue associations from the df_glycan dataframe. ```python build_custom_df(df_glycan, kind = 'df_tissue') ``` -------------------------------- ### Get Maximum Flow Path Source: https://bojarlab.github.io/glycowork/network.html Retrieves the path that yields the maximum flow value in a biosynthetic network. Requires a pre-calculated flow dictionary. ```python def get_max_flow_path( network:DiGraph, # Biosynthetic network flow_dict:dict, # Flow dictionary as returned by get_maximum_flow sink:str, # Target node source:str='Gal(b1-4)Glc-ol', # Source node )->list: # Path edge list ``` -------------------------------- ### Sample a Random Glycan Source: https://bojarlab.github.io/glycowork/motif.html Demonstrates how to call the get_random_glycan function to retrieve a single random glycan from the SugarBase database. ```python get_random_glycan() ``` -------------------------------- ### Train LectinOracle_flex Model Source: https://bojarlab.github.io/glycowork/examples.html Import necessary modules and prepare the LectinOracle_flex model. This model directly uses protein sequences as input without requiring ESMC conversion, utilizing knowledge distillation for performance. ```python from glycowork.ml.inference import get_lectin_preds from glycowork.ml.models import prep_model leor = prep_model("LectinOracle_flex", 1, trained = True) get_lectin_preds("QWERTFVCF", ['Neu5Ac(a2-6)GalNAc', 'Gal(b1-4)Glc'], leor, flex = True) ``` -------------------------------- ### Get Possible Linkages by Wildcard Source: https://bojarlab.github.io/glycowork/motif.html Retrieves all linkages from a provided list that match a given wildcard pattern. The wildcard character '?' can represent any character in the linkage string. ```python def get_possible_linkages( wildcard:str, # Pattern to match, ? can be wildcard linkage_list:list={'b2-4', 'b1-6', '?1-?', 'b2-7', 'a2-3', 'a1-1', 'b1-5', 'a2-11', 'b2-8', 'b1-4', 'a1-3', 'b2-2', 'b1-2', 'b1-3', 'a2-1', 'a1-5', '?2-6', 'a1-8', 'a1-11', '?1-3', '?1-6', 'a2-4', 'a1-2', 'a2-2', 'b2-6', 'b2-1', 'a2-8', 'b1-?', '?1-2', '?2-3', '?2-8', 'a2-6', 'a1-7', 'b1-7', '?2-?', 'a1-6', 'a2-9', 'a1-9', 'a2-?', 'b2-5', 'a1-4', 'b1-9', '1-6', 'a2-7', 'b1-1', 'a1-?', 'b1-8', 'b2-3', 'a2-5', '?1-4', '1-4'}, )->set: # Matching linkages ``` ```python get_possible_linkages("a1-?") ``` ```python {'a1-1', 'a1-2', 'a1-3', 'a1-4', 'a1-5', 'a1-6', 'a1-7', 'a1-8', 'a1-9', 'a1-?'} ``` -------------------------------- ### expand_lib Source: https://bojarlab.github.io/glycowork/motif.html Updates an existing dictionary of glycoletter:index mappings with newly introduced glycoletters from a list of IUPAC-condensed glycan sequences. ```APIDOC ## expand_lib ### Description Updates an existing dictionary of glycoletter:index mappings with newly introduced glycoletters from a list of IUPAC-condensed glycan sequences. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **libr_in**: (dict) - Existing dictionary of glycoletter:index. - **glycan_list**: (list) - List of IUPAC-condensed glycan sequences. ### Response #### Success Response - **dict**: Updated dictionary with new glycoletters. ### Request Example ```python lib1 = get_lib(['Man(a1-3)[Man(a1-6)]Man(b1-4)GlcNAc(b1-4)GlcNAc', 'Man(a1-2)Man(a1-3)[Man(a1-6)]Man(b1-4)GlcNAc(b1-4)GlcNAc']) lib2 = expand_lib(lib1, ['Man(a1-3)[Man(a1-6)]Man(b1-4)GlcNAc(b1-4)[Fuc(a1-6)]GlcNAc']) lib2 ``` ### Response Example ```json {'GlcNAc': 0, 'Man': 1, 'a1-2': 2, 'a1-3': 3, 'a1-6': 4, 'b1-4': 5, 'Fuc': 6} ``` ``` -------------------------------- ### get_lib Source: https://bojarlab.github.io/glycowork/motif.html Returns a dictionary mapping glycoletters to their corresponding indices from a list of IUPAC-condensed glycan sequences. ```APIDOC ## get_lib ### Description Returns a dictionary mapping glycoletters to their corresponding indices from a list of IUPAC-condensed glycan sequences. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **glycan_list**: (list) - List of IUPAC-condensed glycan sequences. ### Response #### Success Response - **dict**: Dictionary of glycoletter:index mappings. ### Request Example ```python get_lib(['Man(a1-3)[Man(a1-6)]Man(b1-4)GlcNAc(b1-4)GlcNAc', 'Man(a1-2)Man(a1-3)[Man(a1-6)]Man(b1-4)GlcNAc(b1-4)GlcNAc']) ``` ### Response Example ```json {'GlcNAc': 0, 'Man': 1, 'a1-2': 2, 'a1-3': 3, 'a1-6': 4, 'b1-4': 5} ``` ``` -------------------------------- ### Find Nth Occurrence from End with find_nth_reverse Source: https://bojarlab.github.io/glycowork/glycan_data.html Finds the starting index of the n-th occurrence of a substring from the end of a string. An option is available to ignore branches during the counting process. ```python def find_nth_reverse( string:str, # string to search substring:str, # substring to find n:int, # n-th occurrence from end ignore_branches:bool=False, # whether to ignore branches when counting )->int: # position of n-th occurrence from end ``` ```python find_nth_reverse("Gal(b1-4)GlcNAc(b1-6)[Gal(b1-3)]GalNAc", "Gal", 0) ``` ```python 38 ``` -------------------------------- ### Retrieve ESMC Protein Representations Source: https://bojarlab.github.io/glycowork/ml.html Retrieves ESMC-300M representations for a list of protein sequences. These representations can be used as input for models like LectinOracle. Requires installation of the 'fair-esm' package. ```python def get_esmc_representations( prots:list, # list of protein sequences to convert model:Module, # trained ESMC model )->dict: # dict of protein sequence:ESMC-300M representation ``` ```shell !pip install fair-esm from esm.models.esmc import ESMC model = ESMC.from_pretrained("esmc_300m").to(device) ``` -------------------------------- ### Create PyTorch Geometric DataLoader from Glycans Source: https://bojarlab.github.io/glycowork/ml.html Converts lists of glycans and labels into a PyTorch Geometric DataLoader. Useful for preparing data for graph neural network training. ```python def dataset_to_dataloader( glycan_list:list, # list of IUPAC-condensed glycans labels:list, # list of labels libr:dict[str, int] | None=None, # dictionary of glycoletter:index batch_size:int=32, # samples per batch shuffle:bool=True, # shuffle samples in dataloader drop_last:bool=False, # drop last batch extra_feature:list[float] | None=None, # additional input features label_type:dtype=torch.int64, # tensor type for label augment_prob:float=0.0, # probability of data augmentation generalization_prob:float=0.2, # probability of wildcarding )->DataLoader: # dataloader for training ``` ```python next(iter(dataset_to_dataloader(["Neu5Ac(a2-3)Gal(b1-4)Glc", "Fuc(a1-2)Gal(b1-3)GalNAc"], [1, 0]))) ``` ```python DataBatch(edge_index=[2, 8], labels=[10], string_labels=[2], num_nodes=10, y=[2], batch=[10], ptr=[3]) ``` -------------------------------- ### get_possible_topologies Source: https://bojarlab.github.io/glycowork/motif.html Generates possible glycan graphs or strings given a glycan with a floating substituent. It can perform an exhaustive search or consider only allowed disaccharides. ```APIDOC ## get_possible_topologies ### Description Generates possible glycan graphs or strings given a glycan with a floating substituent. It can perform an exhaustive search or consider only allowed disaccharides. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **glycan**: (str | networkx.classes.digraph.DiGraph) - Glycan with floating substituent. - **exhaustive**: (bool, optional) - Whether to allow additions at internal positions. Defaults to False. - **allowed_disaccharides**: (set[str] | None, optional) - Permitted disaccharides when creating possible glycans. Defaults to None. - **modification_map**: (dict, optional) - Maps modifications to valid attachments. Defaults to {{'6S': {{'Gal', 'GlcNAc'}}, '3S': {{'Gal'}}, '4S': {{'GalNAc'}}, 'OS': {{'Gal', 'GalNAc', 'GlcNAc'}}}} - **return_graphs**: (bool, optional) - Whether to return glycan graphs (otherwise return converted strings). Defaults to False. ### Response #### Success Response - **list**: List of possible topology strings or graphs. ### Request Example ```python # Example usage (conceptual, actual call depends on library context) get_possible_topologies(glycan='Neu5Ac(a2-3)Gal(b1-4)GlcNAc(b1-6)[Gal(b1-3)]GalNAc', exhaustive=True) ``` ### Response Example ```json ["string_or_graph_representation_1", "string_or_graph_representation_2"] ``` ``` -------------------------------- ### Find Nth Occurrence of Substring with find_nth Source: https://bojarlab.github.io/glycowork/glycan_data.html Finds the starting index of the n-th occurrence of a substring (needle) within a larger string (haystack). The occurrence count 'n' is 1-indexed. ```python def find_nth( haystack:str, # string to search for motif needle:str, # motif n:int, # n-th occurrence in string (not zero-indexed) )->int: # starting index of n-th occurrence ``` ```python find_nth('This is as good as it gets', 'as', 2) ``` ```python 16 ``` -------------------------------- ### Convert Occurrence Data to Presence Matrix Source: https://bojarlab.github.io/glycowork/motif.html Example of using the `presence_to_matrix` function to convert a filtered DataFrame into a presence/absence matrix. The data is filtered by 'Order' and the 'Family' column is used as the label. ```python out = presence_to_matrix(df_species[df_species.Order == 'Fabales'].reset_index(drop = True), label_col_name = 'Family') ``` -------------------------------- ### Sample Output Table Header Source: https://bojarlab.github.io/glycowork/motif.html Represents a portion of the output table from a site-specific glycosylation analysis, showing protein identifiers and associated statistical values. ```text sp|P47710|CASA1_69 | 0.353257 | 0.000000e+00 | True | 0.353257 | 0.000000e+00 | True | 0.000000 | 1.000000e+00 | False | 0.353257 | ... | True | 0.000000 | 1.000000 | False | 1.413027 | 0.000000e+00 | True | -1.563416 | 0.000000e+00 | True sp|P01024|CO3_85 | -13.530653 | 0.000000e+00 | True | 0.000000 | 1.000000e+00 | False | 0.000000 | 1.000000e+00 | False | -13.530653 | ... | False | -13.530653 | 0.000000 | True | -27.061306 | 0.000000e+00 | True | 12.636985 | 0.000000e+00 | True sp|P10909|CLUS_103 | -0.149909 | 0.000000e+00 | True | 4.306665 | 0.000000e+00 | True | 4.456574 | 0.000000e+00 | True | -4.606483 | ... | True | 0.000000 | 1.000000 | False | -0.599635 | 0.000000e+00 | True | -0.749544 | 0.000000e+00 | True sp|Q13410|BT1A1_55 | -13.100965 | 1.331366e-72 | True | -17.275380 | 3.955343e-111 | True | -4.174415 | 7.070812e-177 | True | -8.926549 | ... | False | 0.000000 | 1.000000 | False | 12.462657 | 2.362957e-76 | True | -0.638308 | 6.203369e-16 | True sp|P01011|AACT_106 | -0.027608 | 3.078766e-16 | True | -2.620928 | 0.000000e+00 | True | -2.593321 | 0.000000e+00 | True | 2.565713 | ... | True | 0.000000 | 1.000000 | False | -0.110431 | 3.078766e-16 | True | -0.138038 | 3.848458e-16 | True sp|P00709|LALBA_90 | -1.220055 | 1.372347e-07 | True | -1.773743 | 2.017993e-05 | True | -0.553687 | 6.915606e-01 | False | -0.666368 | ... | True | 0.000000 | 1.000000 | False | -4.880222 | 1.372347e-07 | True | 3.511094 | 9.427322e-06 | True sp|P08571|CD14_151 | 0.002309 | 3.336465e-04 | True | 0.000000 | 1.000000e+00 | False | 0.000000 | 1.000000e+00 | False | 0.002309 | ... | False | 0.002309 | 0.001437 | True | 0.004617 | 3.336465e-04 | True | 0.013851 | 3.336465e-04 | True sp|P07602|SAP_426 | 0.002851 | 6.752159e-03 | True | 0.000000 | 1.000000e+00 | False | 0.000000 | 1.000000e+00 | False | 0.002851 | ... | False | 0.000000 | 1.000000 | False | 0.005702 | 6.752159e-03 | True | 0.014255 | 6.752159e-03 | True sp|P07602|SAP_101 | -0.001653 | 1.856037e-01 | False | -0.001653 | 1.798929e-01 | False | 0.000000 | 1.000000e+00 | False | -0.001653 | ... | False | 0.000000 | 1.000000 | False | -0.006613 | 1.670434e-01 | False | -0.008267 | 1.856037e-01 | False sp|P07602|SAP_215 | -0.002911 | 2.018278e-01 | False | 0.000000 | 1.000000e+00 | False | 0.000000 | 1.000000e+00 | False | 0.000000 | ... | False | 0.000000 | 1.000000 | False | -0.005822 | 1.834798e-01 | False | -0.005822 | 2.018278e-01 | False sp|Q08431|MFGM_238 | 0.144987 | 3.025292e-01 | False | -0.252363 | 3.799644e-01 | False | 0.000000 | 1.000000e+00 | False | 0.144987 | ... | False | -0.254360 | 0.941176 | False | 0.037612 | 5.947780e-01 | False | -0.036146 | 3.833506e-01 | False sp|P25311|ZA2G_109 | 0.007570 | 3.250433e-01 | False | -0.227406 | 1.091050e-01 | False | -0.234976 | 1.699985e-01 | False | 0.242546 | ... | False | 0.000000 | 1.000000 | False | 0.030279 | 3.082506e-01 | False | 0.037849 | 2.863536e-01 | False sp|P10909|CLUS_291 | 0.001798 | 3.553860e-01 | False | 0.001798 | 3.799644e-01 | False | 0.000000 | 1.000000e+00 | False | 0.001798 | ... | False | 0.000000 | 1.000000 | False | 0.005395 | 3.300013e-01 | False | 0.008992 | 2.887511e-01 | False sp|P10909|CLUS_86 | -0.000590 | 4.353640e-01 | False | -0.000590 | 4.375966e-01 | False | 0.000000 | 1.000000e+00 | False | -0.000590 | ... | False | 0.000000 | 1.000000 | False | -0.002359 | 3.809435e-01 | False | -0.002949 | 3.585351e-01 | False ``` -------------------------------- ### Generate Glycan/Motif Heatmap Source: https://bojarlab.github.io/glycowork/motif.html Creates a hierarchically clustered heatmap visualization of glycan or motif abundances. Use this to explore patterns and relationships in glycan data. ```python import pandas import pathlib import typing from pandas import DataFrame from typing import Any def get_heatmap( df:pandas.DataFrame | str | pathlib.Path, # Input dataframe or filepath (.csv/.xlsx) motifs:bool=False, # Analyze motifs instead of sequences feature_set:list=['known'], # Feature sets to use; exhaustive, known, terminal1, terminal2, terminal3, chemical, graph, custom, size_branch transform:str='', # Transform data before plotting datatype:str='response', # Data type: 'response' for quantitative values or 'presence' for presence/absence rarity_filter:float=0.05, # Min proportion for non-zero values filepath:str | pathlib.Path='', # Path to save plot index_col:str='glycan', # Column to use as index custom_motifs:list=[], # Custom motifs if using 'custom' feature set return_plot:bool=False, # Return plot object show_all:bool=False, # Show all tick labels kwargs:Any )->tuple[typing.Any, list[str], pandas.DataFrame] | None: # None or (plot object, column names, transformed dataframe) if return_plot=True ``` ```python glycans = ['Man(a1-3)[Man(a1-6)][Xyl(b1-2)]Man(b1-4)GlcNAc(b1-4)[Fuc(a1-3)]GlcNAc', 'Man(a1-2)Man(a1-2)Man(a1-3)[Man(a1-3)Man(a1-6)]Man(b1-4)GlcNAc(b1-4)GlcNAc', 'GalNAc(a1-4)GlcNAcA(a1-4)[GlcN(b1-7)]Kdo(a2-5)[Kdo(a2-4)]Kdo(a2-6)GlcN4P(b1-6)GlcN4P', 'Man(a1-2)Man(a1-3)[Man(a1-6)]Man(b1-4)GlcNAc(b1-4)GlcNAc', 'Glc(b1-3)Glc(b1-3)Glc'] label = [3.234, 2.423, 0.733, 3.102, 0.108] label2 = [0.134, 0.345, 1.15, 0.233, 2.981] label3 = [0.334, 0.245, 1.55, 0.133, 2.581] test_df = pd.DataFrame([label, label2, label3], columns = glycans) get_heatmap(test_df, motifs = True, feature_set = ['known', 'exhaustive']) ``` -------------------------------- ### Get Unique Glycan Topologies from Composition Source: https://bojarlab.github.io/glycowork/motif.html Retrieves a list of all unique base topologies observed for a given glycan composition and type. Allows filtering by taxonomy and custom monosaccharide mappings. ```python def get_unique_topologies( composition:dict, # Composition dictionary of monosaccharide:count glycan_type:str, # Glycan class: N/O/lipid/free/repeat df_use:pandas.DataFrame | None=None, # Custom glycan database to use for mapping universal_replacers:dict[str, str] | None=None, # Base-to-specific monosaccharide mapping taxonomy_rank:str='Kingdom', # Taxonomic rank for filtering taxonomy_value:str='Animalia', # Value at taxonomy rank )->list: # List of unique base topologies ``` ```python get_unique_topologies({'HexNAc':2, 'Hex':1}, 'O', universal_replacers = {'dHex':'Fuc'}) ``` ```python ['Hex(?1-?)HexNAc(?1-?)HexNAc', 'HexNAc(?1-?)HexNAc(?1-?)Hex', 'HexNAc(?1-?)[HexNAc(?1-?)]Hex', 'Hex(?1-?)[HexNAc(?1-?)]HexNAc', 'HexNAc(?1-?)Hex(?1-?)HexNAc'] ``` -------------------------------- ### Construct and Plot Biosynthetic Network Source: https://bojarlab.github.io/glycowork/examples.html Constructs a biosynthetic network from a list of glycans and plots it. This is useful for visualizing glycan relationships and potential synthesis pathways. Default parameters are optimized for milk glycans. ```python glycans = ["Gal(b1-4)Glc-ol", "GlcNAc(b1-3)Gal(b1-4)Glc-ol", "GlcNAc6S(b1-3)Gal(b1-4)Glc-ol", "Gal(b1-4)GlcNAc(b1-3)Gal(b1-4)Glc-ol", "Fuc(a1-2)Gal(b1-4)Glc-ol", "Gal(b1-4)GlcNAc(b1-3)[Gal(b1-3)GlcNAc(b1-6)]Gal(b1-4)Glc-ol"] network = construct_network(glycans) plot_network(network) ``` -------------------------------- ### Get Possible Monosaccharides by Type Source: https://bojarlab.github.io/glycowork/motif.html Retrieves a set of common monosaccharides that match a specified type. Supported types include Hex, HexNAc, dHex, Sia, HexA, Pen, HexOS, and HexNAcOS. ```python def get_possible_monosaccharides( wildcard:str, # Monosaccharide type; options: Hex, HexNAc, dHex, Sia, HexA, Pen, HexOS, HexNAcOS )->set: # Matching monosaccharides ``` ```python get_possible_monosaccharides("HexNAc") ``` ```python {'GalNAc', 'GlcNAc', 'HexNAc', 'ManNAc'} ``` -------------------------------- ### Annotate Glycans for Classification Source: https://bojarlab.github.io/glycowork/examples.html Prepare a binary list indicating human (1) or non-human primate (0) glycans based on species data. This is the first step in preparing data for machine learning classification. ```python human = [1 if k == 'Homo_sapiens' else 0 for k in df_species[df_species.Order=='Primates'].Species.values.tolist()] ```