### Calculate ladderpath and print indices Source: https://github.com/yuernestliu/lppack/blob/main/README.md A minimal quickstart example demonstrating how to import the ladderpath library, define input strings, calculate the ladderpath using get_ladderpath, and print the resulting indices. The `info`, `fill_ladderons_STR`, `estimate_eta`, `save_file_name`, and `show_version` parameters are set for this specific calculation. ```python import ladderpath as lp strs = ['ABCDBCDBCDCDEFEF', 'AA', 'DBCDBCA', 'BCDCDAEF'] lpjson = lp.get_ladderpath( strs, info='V1.0.0.20240910_Alpha', fill_ladderons_STR=False, estimate_eta=False, save_file_name=None, show_version=True ) print(lpjson["ladderpath-index"], lpjson["order-index"], lpjson["size-index"]) ``` -------------------------------- ### Install lppack with pip directly Source: https://github.com/yuernestliu/lppack/blob/main/README.md Install the lppack package directly from the GitHub repository using pip. ```bash pip install git+https://github.com/yuernestliu/lppack.git ``` -------------------------------- ### Install lppack from GitHub Source: https://github.com/yuernestliu/lppack/blob/main/README.md Clone the lppack repository from GitHub and install it in editable mode using pip. This is recommended for the latest version and for local development. ```bash git clone https://github.com/yuernestliu/lppack.git cd lppack pip install -e . ``` -------------------------------- ### Install graphviz system package on Ubuntu/Debian Source: https://github.com/yuernestliu/lppack/blob/main/README.md Install the graphviz system package on Ubuntu or Debian-based systems using apt-get. ```bash sudo apt-get install graphviz ``` -------------------------------- ### Install graphviz system package on macOS Source: https://github.com/yuernestliu/lppack/blob/main/README.md Install the graphviz system package on macOS using Homebrew. ```bash brew install graphviz ``` -------------------------------- ### Install graphviz Python binding Source: https://github.com/yuernestliu/lppack/blob/main/README.md Install the graphviz Python binding using pip. This is required for visualization. ```bash pip install graphviz ``` -------------------------------- ### Example POM Dictionary Representation Source: https://github.com/yuernestliu/lppack/blob/main/README.md An example of the dictionary-based representation of a ladderpath's Partially Ordered Multiset (POM), showing counts of elements at different levels. ```json { 0: {'A': 3, 'D': 3, 'C': 2, 'B': 1, 'E': 1, 'F': 1}, # Level 0 1: {'EF': 2, 'BC': 2, 'DCD': 1}, # Level 1 2: {'DBC': 1}, # Level 2 3: {'DBCDBC': 1} } ``` -------------------------------- ### Initialize Ladderpath Calculation Source: https://github.com/yuernestliu/lppack/blob/main/README.md Imports the ladderpath library and initializes the 'strs' variable with example sequences for calculating ladderpaths. This is the main function for computing ladderpaths. ```python import ladderpath as lp # strs = ['ABCDBCDBCDCDEFEF'] strs = ['ABCDBCDBCDCDEFEF', 'AA', 'DBCDBCA', 'BCDCDAEF'] # strs = ['ABCDBCDBCDCDEFEF', 'AA', 'AA', 'DBCDBCA', 'BCDCDAEF','AA', 'DBCDBCA', 'AAAA'] ``` -------------------------------- ### Pairwise Comparison by String Source: https://context7.com/yuernestliu/lppack/llms.txt Performs pairwise comparison of strings using the `get` method. Ensure `lpjson` is properly initialized. ```python lambda_pair_str = lp1.get(['ABCDBCDBCDCDEFEF', 'DBCDBCA'], lpjson) print(f"pairwise lambda: {lambda_pair_str}") ``` -------------------------------- ### Define Input Sequences Source: https://github.com/yuernestliu/lppack/blob/main/lppack/demo_scripts/demo.ipynb Defines a list of input sequences for LadderPath processing. Several commented-out examples show alternative sequence sets. ```python # strs = ['acsccsaascascaaaacssscscscasasacssacssaaaacsccsaascascaaaacssscscscasasacssacssaaa'] strs = ['ABCDBCDBCDCDEFEF', 'AA', 'AA', 'DBCDBCA', 'BCDCDAEF','AA', 'DBCDBCA', 'AAAA'] # strs = ['ABCDBCDBCDCDEFEF', 'AA', 'DBCDBCA', 'BCDCDAEF', 'DBCDBCA', 'AAAA'] # strs = ['ABCDBCDBCDCDEFEF', 'AA', 'AA', 'DBCDBCA', 'BCDCDAEF','AA', 'AAAA'] # strs = ['ABCDBCDBCDCDEFEF', 'AA', 'DBCDBCA', 'BCDCDAEF'] # strs = ['DDDCC'] # with open('sequences.txt', 'r', encoding='utf-8') as file: # strs = [file.read()] ``` -------------------------------- ### Compute Partially Ordered Multiset (POM) Representation Source: https://context7.com/yuernestliu/lppack/llms.txt The `POM_from_JSON` function computes the hierarchically stratified POM of a ladderpath. It returns a dictionary where keys are levels and values map string content to its multiplicity. Use `display_str=True` to also get a formatted string representation. ```python import ladderpath as lp strs = ['ABCDBCDBCDCDEFEF', 'AA', 'DBCDBCA', 'BCDCDAEF'] lpjson = lp.get_ladderpath(strs, show_version=False) pom, pom_str = lp.POM_from_JSON(lpjson, display_str=True) # Prints: { A(3), D(3), C(2), B, E, F // EF(2), BC(2), DCD // DBC // DBCDBC } # pom dict: # { # 0: {'A': 3, 'D': 3, 'C': 2, 'B': 1, 'E': 1, 'F': 1}, # level 0: basic blocks # 1: {'EF': 2, 'BC': 2, 'DCD': 1}, # level 1 # 2: {'DBC': 1}, # level 2 # 3: {'DBCDBC': 1} # level 3 # } print(pom[1]) # {'EF': 2, 'BC': 2, 'DCD': 1} print(pom_str) # '{ A(3), D(3), C(2), B, E, F // EF(2), BC(2), DCD // DBC // DBCDBC }' ``` -------------------------------- ### Open demo notebook with JupyterLab Source: https://github.com/yuernestliu/lppack/blob/main/README.md Open the demo notebook using the JupyterLab interface. ```bash jupyter lab demo.ipynb ``` -------------------------------- ### Open demo notebook with Jupyter Notebook Source: https://github.com/yuernestliu/lppack/blob/main/README.md Open the demo notebook using the Jupyter Notebook interface. ```bash jupyter notebook demo.ipynb ``` -------------------------------- ### get Source: https://context7.com/yuernestliu/lppack/llms.txt Computes the ladderpath-index contribution for one or two specified target sequences by traversing the laddergraph. This is useful for pairwise structural comparisons without recomputing the full ladderpath. ```APIDOC ## get ### Description Computes the ladderpath-index contribution for one or two specified target sequences (identified by target ID or by string) by traversing the existing `lpjson` laddergraph bottom-up. This function is useful for pairwise structural comparisons without the need to recompute the full ladderpath. ### Parameters - **target_ids_or_sequences**: A list containing one or two target IDs (integers) or sequences (strings) for which to compute the ladderpath-index. - **lpjson**: The input data structure generated by `lp.get_ladderpath`. ### Returns The computed ladderpath-index value for the specified target(s). ### Example ```python import ladderpath as lp import ladderpath_tools.lambda_from_laddergraph as lp1 strs = ['ABCDBCDBCDCDEFEF', 'AA', 'DBCDBCA', 'BCDCDAEF'] lpjson = lp.get_ladderpath(strs, fill_ladderons_STR=True, show_version=False) # Ladderpath-index of a single target (by ID) lambda_single = lp1.get([-1], lpjson) print(f"lambda for target -1: {lambda_single}") # e.g. 15 # Ladderpath-index for two targets together (by ID) lambda_pair = lp1.get([-1, -3], lpjson) print(f"lambda for targets -1 and -3: {lambda_pair}") # e.g. 18 # Can also pass sequences directly instead of IDs lambda_by_str = lp1.get(['ABCDBCDBCDCDEFEF'], lpjson) print(f"lambda by string: {lambda_by_str}") # same as lambda_single ``` ``` -------------------------------- ### Load LadderPath JSON from File Source: https://github.com/yuernestliu/lppack/blob/main/lppack/demo_scripts/demo.ipynb Demonstrates how to load a LadderPath JSON object from a file. Note that dictionary keys might be converted to numbers. ```python # 读取JSON文件(会将dict的key转换成数字) # lpjson = lp.load_ladderpath_json('new_lpjson.json') # lpjson ``` -------------------------------- ### Import LadderPath and Dependencies Source: https://github.com/yuernestliu/lppack/blob/main/lppack/demo_scripts/demo.ipynb Imports the necessary LadderPath library and pandas for data manipulation. Ensure the library path is correctly set. ```python import sys sys.path.append("/Users/ernest/Documents/PythonPackageErnest/lppack2") import ladderpath as lp import pandas as pd ``` -------------------------------- ### Display Ladderpath Indices Source: https://github.com/yuernestliu/lppack/blob/main/README.md Displays three key metrics of the ladderpath: ladderpath-index, order-index, and size-index. ```python # Display three metrics: ladderpath-index, order-index, size-index index3 = lp.disp3index(lpjson) ``` -------------------------------- ### Display Core Indices with disp3index Source: https://context7.com/yuernestliu/lppack/llms.txt Formats and prints a summary of the ladderpath-index, order-index, and size-index from a ladderpath JSON object. Also returns these indices as a tuple. ```python import ladderpath as lp strs = ['ABCDBCDBCDCDEFEF', 'AA', 'DBCDBCA', 'BCDCDAEF'] lpjson = lp.get_ladderpath(strs, show_version=False) index3 = lp.disp3index(lpjson) # Prints: ( Ladderpath-index:20, Order-index:13, Size-index:33 ) # Returns: (20, 13, 33) lp_idx, order_idx, size_idx = index3 ``` -------------------------------- ### Calculate and Update ETA Source: https://github.com/yuernestliu/lppack/blob/main/lppack/demo_scripts/demo.ipynb Demonstrates the process of calculating and updating the 'eta' value within the LadderPath JSON. Includes handling warnings related to `duplications_info` and prerequisites for `update_eta`. ```python # 设置计算eta时的参数 estimate_eta_para={'n': 10, 'max_method': 'AllIdentical', \ 'min_method': 'EvenDist', \ 'min_method_nBase': 26} # 如果eta存在,则取出;如果不存在,则计算 lp.get_eta(lpjson, estimate_eta_para=estimate_eta_para) ``` ```python # 更新eta值,即多增加N_omega_min次计算omega_min lp.update_eta(lpjson, estimate_eta_para=estimate_eta_para) lp.get_eta(lpjson, estimate_eta_para=estimate_eta_para) ``` -------------------------------- ### Compute Ladderpath with LPPack Source: https://github.com/yuernestliu/lppack/blob/main/README.md Computes the ladderpath for a given set of strings. Accepts various parameters to control output and computation. The input can be a list of strings or a dictionary of strings with frequencies. The output is a JSON object. ```python lpjson = lp.get_ladderpath(strs, info='V1.0.0.20240910_Alpha', fill_ladderons_STR = False, estimate_eta = False, save_file_name=None, show_version=True) # Output is in the standard JSON format for ladderpaths ``` -------------------------------- ### Compute Ladderpath-Index from Laddergraph (Two Targets) Source: https://github.com/yuernestliu/lppack/blob/main/README.md Computes the ladderpath-index for two target sequences together from an existing laddergraph. The input `leaves1or2` should contain one or two target sequences or their IDs. `lpjson` must be a ladderpath JSON that includes these targets. ```Python leaves1or2 = [-1, -3] # leaves1or2 = ['ABCDBCDBCDCDEFEF', 'DBCDBCA'] lambda2 = lp1.get(leaves1or2, lpjson) ``` -------------------------------- ### V1.0.1 Alpha Version Data Structure Update Source: https://github.com/yuernestliu/lppack/blob/main/README.md Details the changes in V1.0.1, removing omega_max and omega_min_list, and introducing eta_info for consolidated eta-related data. ```yaml { "eta": 0.67, # Order-rate (η), representing an approximate value. Detailed information is stored in `eta_info` "eta_info": { "omega_max_AllIdentical": 20, # Equivalent to generating a sequence of the same length as the original, consisting entirely of 'A's (no longer segmented by target lengths). "omega_max_Sorted": 15, # Calculated omega from the fully concatenated and sorted version of the original sequence (also not segmented by target lengths). This is often the maximum omega among all permutations. "omega_min_Shuffle_list": [3,5,5,9,3], # Omega values obtained by random shuffling of the target sequence. The minimum of these is used in computing eta. "omega_min_LocalDist_list": [3,5,8] # Omega values from randomly generated sequences that follow the original letter distribution. These sequences have the same length as the target. "omega_min_EvenDist_list": [5,9,2,6] # Omega values from sequences of the same length as the original, with all characters evenly distributed. } } ``` -------------------------------- ### Extract POM and Display Index Information Source: https://github.com/yuernestliu/lppack/blob/main/lppack/demo_scripts/demo.ipynb Extracts the 'Point of Mutation' (POM) and its string representation, along with displaying key index information from the LadderPath JSON. ```python index3 = lp.disp3index(lpjson) pom, pom_str = lp.POM_from_JSON(lpjson, display_str=True) ``` -------------------------------- ### disp3index Source: https://context7.com/yuernestliu/lppack/llms.txt Displays and returns the three core indices (ladderpath-index, order-index, size-index) from a Ladderpath JSON dictionary in a formatted string and as a tuple. ```APIDOC ## disp3index ### Description Displays a formatted summary of the three core indices (ladderpath-index, order-index, size-index) and returns them as a tuple. ### Method Signature ```python ladderpath.disp3index(lpjson: dict) -> tuple ``` ### Parameters - **lpjson** (dict) - Required - The Ladderpath JSON dictionary obtained from `get_ladderpath`. ### Returns - **tuple** - A tuple containing the ladderpath-index, order-index, and size-index (e.g., (20, 13, 33)). ### Request Example ```python import ladderpath as lp strs = ['ABCDBCDBCDCDEFEF', 'AA', 'DBCDBCA', 'BCDCDAEF'] lpjson = lp.get_ladderpath(strs, show_version=False) index3 = lp.disp3index(lpjson) # Prints: ( Ladderpath-index:20, Order-index:13, Size-index:33 ) # Returns: (20, 13, 33) lp_idx, order_idx, size_idx = index3 ``` ``` -------------------------------- ### Compute Ladderpath-Index from Laddergraph (Single Target) Source: https://github.com/yuernestliu/lppack/blob/main/README.md Computes the ladderpath-index for a single target sequence from an existing laddergraph. The input `leaves1or2` should contain a single target sequence or its ID. `lpjson` must be a ladderpath JSON that includes this target. ```Python import ladderpath_tools.lambda_from_laddergraph as lp1 ``` ```Python leaves1or2 = [-1] # leaves1or2 = ['DBCDBCA'] lambda1 = lp1.get(leaves1or2, lpjson) ``` -------------------------------- ### Compute Order-Rate Eta (η) in Lppack Source: https://github.com/yuernestliu/lppack/blob/main/README.md Computes the order-rate eta (η) value. If an eta value already exists in lpjson and was computed using the same parameters, it will be returned directly. Otherwise, it is computed anew. ```Python estimate_eta_para={'n': 10, 'max_method': 'AllIdentical', 'min_method': 'EvenDist', 'min_method_nBase': 26} eta = lp.get_eta(lpjson, estimate_eta_para=estimate_eta_para) ``` -------------------------------- ### Populate and Clear STR String Cache Source: https://context7.com/yuernestliu/lppack/llms.txt Use `fill_lpjson_STR` to recursively build and cache explicit strings for ladderons and targets. Use `clear_lpjson_STR` to reset these caches to save memory. Both operate in-place on the `lpjson` object. ```python import ladderpath as lp strs = ['ABCDBCDBCDCDEFEF', 'AA', 'DBCDBCA', 'BCDCDAEF'] lpjson = lp.get_ladderpath(strs, fill_ladderons_STR=False, show_version=False) # Before fill: STR fields are empty strings print(lpjson['ladderons'][0][2]) # '' lp.fill_lpjson_STR(lpjson) # After fill: each ladderon has its explicit string content for ldID, info in lpjson['ladderons'].items(): print(f"Ladderon {ldID}: '{info[2]}'") # Ladderon 0: 'DBCDBC' # Ladderon 1: 'DBC' # ... # Clear the cache to free memory lp.clear_lpjson_STR(lpjson) print(lpjson['ladderons'][0][2]) # '' ``` -------------------------------- ### Count Basic Building Blocks Source: https://github.com/yuernestliu/lppack/blob/main/README.md Counts the occurrences of each basic building block (e.g., 'A', 'C', 'B') within the target sequences in lpjson. ```Python bbb_dict = bbb_multiplicity(lpjson) -> Dict[str:int] ``` -------------------------------- ### V1.0.0 Alpha Version Data Structure Source: https://github.com/yuernestliu/lppack/blob/main/README.md Defines the data structure for version V1.0.0, including info, indices, eta, ladderons, and targets. Note the structure of COMP and POS within ladderons. ```yaml { "info": "V1.0.0.20240910_Alpha" "ladderpath-index": 23, "order-index": 10, # order-index Ω "size-index": 33, "eta": 0.67, # order-rate (η) "omega_max": 15, # Ω of the most ordered sequenece with the same size-index, used to compute η "omega_min_list": [3,5,5,9,3], # List of Ω's from randomized sequences; all outcomes are recorded here. The minimum is used to compute η. "ladderons": { # Dictionary in the format ID (int): List[COMP (List), LEN (int), STR (str), POS (Dict)] 0: [ # ID 0, 1, 2, ... ["ACE", 1, "C", 5, 6, 6, 3, "EE"], # COMP: Basic building blocks + ladderon IDs arranged by the target sequence; uniquely reconstructible 23, # LEN: Length of the ladderon "", # STR: Placeholder string, used to store the reconstructed ladderon {-1: [1, 20, 35], 1: [0, 6]} # POS: {int: [int]}, indicates which higher-level ladderons (by ID) use this ladderon, and the positions (indexes) at which it appears in their COMP lists. ], 1: [ [6, 2], 13, "", {3: [21, 30]} ], ... } "basic_building_blocks": List(str) "targets": { # Dictionary in format ID (int): [COMP (List), LEN (int), STR (str), REP (int)] -1: [ # Target identifiers: -1, -2, -3, ... ["ACE", 1, "C", 5, 6, 6, 3, "EE"], 98, "", 1 # REP: Number of times this target appears in the original targets ], -2: [ [1, 3, "A", 6], 50, "", 2 ], ... } "duplications_info": Dict(int:[int]) # Stores information about duplicated sequences in targets. Key: target ID; Value: list of its positions in the original targets (0-based indexing) } ``` -------------------------------- ### Compute and Refine Order-Rate Eta Source: https://context7.com/yuernestliu/lppack/llms.txt Use `get_eta` to compute the normalized order-rate η, comparing actual order-index against theoretical maximum and minimum. `update_eta` can be used to refine the estimate by adding more randomization trials. Both functions update `lpjson` in-place. ```python import ladderpath as lp # eta requires no duplications_info in lpjson strs = ['ABCDBCDBCDCDEFEF', 'DBCDBCA'] lpjson = lp.get_ladderpath(strs, show_version=False) eta_para = { 'n': 10, 'max_method': 'AllIdentical', # theoretical max: all-same-char sequence 'min_method': 'EvenDist', # theoretical min: uniform random sequences 'min_method_nBase': 26 # 26-letter uniform alphabet } eta = lp.get_eta(lpjson, estimate_eta_para=eta_para) print(f"eta = {eta:.4f}") # e.g. eta = 0.7241 print(lpjson['eta']) # same value, stored in-place # Refine by adding 10 more randomization trials lp.update_eta(lpjson, estimate_eta_para=eta_para) eta_refined = lp.get_eta(lpjson, estimate_eta_para=eta_para) print(f"refined eta = {eta_refined:.4f}") # Inspect the underlying distributions used print(lpjson['eta_info']['omega_max_AllIdentical']) # e.g. 18 print(lpjson['eta_info']['omega_min_EvenDist_list']) # e.g. [3, 4, 5, 2, ...] ``` -------------------------------- ### get_eta / update_eta Source: https://context7.com/yuernestliu/lppack/llms.txt Computes and refines the normalized order-rate η. `get_eta` calculates η and returns it, while `update_eta` adds more trials to improve the estimate. Both functions update the `lpjson` structure in-place. ```APIDOC ## `get_eta` / `update_eta` — Compute and refine the order-rate η `get_eta` computes the normalized order-rate η = (Ω − Ω_min) / (Ω_max − Ω_min), comparing the actual order-index against theoretical maximum (most ordered) and minimum (random baseline). `update_eta` appends additional randomization trials to improve the estimate. Both update `lpjson` in-place; `get_eta` also returns the η value. ```python import ladderpath as lp # eta requires no duplications_info in lpjson strs = ['ABCDBCDBCDCDEFEF', 'DBCDBCA'] lpjson = lp.get_ladderpath(strs, show_version=False) eta_para = { 'n': 10, 'max_method': 'AllIdentical', # theoretical max: all-same-char sequence 'min_method': 'EvenDist', # theoretical min: uniform random sequences 'min_method_nBase': 26 # 26-letter uniform alphabet } eta = lp.get_eta(lpjson, estimate_eta_para=eta_para) print(f"eta = {eta:.4f}") # e.g. eta = 0.7241 print(lpjson['eta']) # same value, stored in-place # Refine by adding 10 more randomization trials lp.update_eta(lpjson, estimate_eta_para=eta_para) eta_refined = lp.get_eta(lpjson, estimate_eta_para=eta_para) print(f"refined eta = {eta_refined:.4f}") # Inspect the underlying distributions used print(lpjson['eta_info']['omega_max_AllIdentical']) # e.g. 18 print(lpjson['eta_info']['omega_min_EvenDist_list']) # e.g. [3, 4, 5, 2, ...] ``` ``` -------------------------------- ### V1.0.2 Alpha Version Input Type Specification Source: https://github.com/yuernestliu/lppack/blob/main/README.md Introduces the 'input_type' field to specify whether targets are provided as a list or a dictionary. ```yaml { "input_type": "list" # or "dict" } ``` -------------------------------- ### Obtain Partially Ordered Multiset (POM) from JSON Source: https://github.com/yuernestliu/lppack/blob/main/README.md Obtains the Partially Ordered Multiset (POM) representation of the ladderpath from a JSON object. The `display_str` parameter controls whether to return a dictionary or string representation. ```python # Obtain the partially ordered multiset (POM) representation of the ladderpath pom, pom_str = lp.POM_from_JSON(lpjson, display_str=False) ``` -------------------------------- ### Draw Laddergraph in Lppack Source: https://github.com/yuernestliu/lppack/blob/main/README.md Draws a laddergraph visualization from lpjson. Various parameters control the display, including sequence length filtering, node styling, target name mapping, and figure saving options. ```Python g = lp.draw_laddergraph(lpjson, show_longer_than = 0, style = "ellipse", TargetNames_UserDefined = {-1:'species1', -2:'new2', -3:'species3'}, warning_n_ladderons_to_show = 500, rankdir = "BT", color = "grey", figsize = "8,8", save_fig_name = None, figformat = "pdf", cleanGVfile = True) ``` -------------------------------- ### POM_from_JSON Source: https://context7.com/yuernestliu/lppack/llms.txt Computes the hierarchically stratified Partially Ordered Multiset (POM) representation of the ladderpath. The result is a dictionary where keys are levels and values map string content to their multiplicity. ```APIDOC ## `POM_from_JSON` — Partially Ordered Multiset (POM) representation Computes the hierarchically stratified POM of the ladderpath: a dict where each integer key is a level (0 = basic building blocks, 1 = first-level ladderons, etc.) and each value maps the string content to its multiplicity (number of reuses). ```python import ladderpath as lp strs = ['ABCDBCDBCDCDEFEF', 'AA', 'DBCDBCA', 'BCDCDAEF'] lpjson = lp.get_ladderpath(strs, show_version=False) pom, pom_str = lp.POM_from_JSON(lpjson, display_str=True) # Prints: { A(3), D(3), C(2), B, E, F // EF(2), BC(2), DCD // DBC // DBCDBC } # pom dict: # { # 0: {'A': 3, 'D': 3, 'C': 2, 'B': 1, 'E': 1, 'F': 1}, # level 0: basic blocks # 1: {'EF': 2, 'BC': 2, 'DCD': 1}, # level 1 # 2: {'DBC': 1}, # level 2 # 3: {'DBCDBC': 1} # level 3 # } print(pom[1]) # {'EF': 2, 'BC': 2, 'DCD': 1} print(pom_str) # '{ A(3), D(3), C(2), B, E, F // EF(2), BC(2), DCD // DBC // DBCDBC }' ``` ``` -------------------------------- ### Load Ladderpath JSON File Source: https://github.com/yuernestliu/lppack/blob/main/README.md Loads a standard ladderpath JSON file. This function automatically converts all dictionary keys in the JSON file to integers. ```python lpjson = lp.load_ladderpath_json(save_file_name) ``` -------------------------------- ### Save and Load Ladderpath JSON with save_ladderpath_json/load_ladderpath_json Source: https://context7.com/yuernestliu/lppack/llms.txt Persist computed ladderpath results to a JSON file and reload them. `load_ladderpath_json` automatically converts string-keyed integer keys back to Python integers. ```python import ladderpath as lp strs = ['ABCDBCDBCDCDEFEF', 'AA', 'DBCDBCA', 'BCDCDAEF'] lpjson = lp.get_ladderpath(strs, save_file_name='results/my_lp', show_version=False) # -> saves to results/my_lp.json automatically # Reload from disk — all dict keys are restored as integers lpjson_loaded = lp.load_ladderpath_json('results/my_lp.json') print(type(list(lpjson_loaded['ladderons'].keys())[0])) # print(lpjson_loaded['ladderpath-index']) # same value as before ``` -------------------------------- ### Compress and Decompress Sequences Source: https://github.com/yuernestliu/lppack/blob/main/lppack/demo_scripts/demo.ipynb Utilizes `ladderpath_tools.compress` to compress the LadderPath JSON object into a compact list format and then decompress it back to the original sequences. ```python import ladderpath_tools.compress as lp_c compressed_list = lp_c.compress(lpjson, display=True, SEP='@') ``` ```python decompressed_strs = lp_c.decompressed(compressed_list, display=True) ``` -------------------------------- ### Draw Laddergraph with Custom Target Names Source: https://context7.com/yuernestliu/lppack/llms.txt Draws a laddergraph visualization. Custom target names can be provided for better readability. Adjust parameters like style, rankdir, and colors for customization. The graph can be saved to a file or displayed inline. ```python target_names = {-1: 'seq_A', -2: 'seq_B', -3: 'seq_C', -4: 'seq_D'} g = lp.draw_laddergraph( lpjson, show_longer_than=0, # 0 = show all, including basic blocks style='box', # 'ellipse', 'ellipse-OnlyShowTargetID', # 'box', or 'box-OnlyShowTargetID' TargetNames_UserDefined=target_names, warning_n_ladderons_to_show=500, # warn if graph is very large rankdir='BT', # BT=bottom-to-top, TB, LR, RL color='grey', # node fill color (name or hex) figsize='8,8', # figure dimensions in inches save_fig_name='figs/my_laddergraph', # saves my_laddergraph.pdf figformat='pdf', # 'pdf', 'png', 'svg', etc. cleanGVfile=True # remove intermediate .gv file ) # Display inline in Jupyter g ``` ```python # Ellipse style (size reflects sequence length, cleaner for large graphs) g2 = lp.draw_laddergraph(lpjson, style='ellipse', show_longer_than=1, rankdir='TB', save_fig_name=None) ``` -------------------------------- ### get_ladderpath Source: https://context7.com/yuernestliu/lppack/llms.txt Computes the Ladderpath JSON for a given set of sequences. This is the primary entry point for the library, returning a dictionary containing structural information and indices. ```APIDOC ## get_ladderpath ### Description Computes the ladderpath JSON for a set of sequences. Accepts a list or dict of sequences, runs the full Ladderpath algorithm, and returns a structured dictionary in the Ladderpath JSON standard format containing the three indices, all discovered ladderons, basic building blocks, target decompositions, duplication info, and optional η (eta) estimate. ### Method Signature ```python ladderpath.get_ladderpath( sequences: list | dict, info: str = None, fill_ladderons_STR: bool = False, estimate_eta: bool = False, estimate_eta_para: dict = None, save_file_name: str = None, show_version: bool = True ) ``` ### Parameters - **sequences** (list | dict) - Required - A list or dictionary of input sequences. - **info** (str) - Optional - Metadata tag stored in the output JSON. - **fill_ladderons_STR** (bool) - Optional - If True, populates the STR cache for each ladderon. Defaults to False. - **estimate_eta** (bool) - Optional - If True, estimates the eta value. Requires `estimate_eta_para`. Defaults to False. - **estimate_eta_para** (dict) - Optional - Parameters for eta estimation. See source for details on keys like 'n', 'max_method', 'min_method', 'min_method_nBase'. - **save_file_name** (str) - Optional - If provided, the output JSON will be saved to this file path (e.g., 'output/my_result'). - **show_version** (bool) - Optional - If True, prints the format version string. Defaults to True. ### Returns - **dict** - A dictionary representing the Ladderpath JSON structure, containing keys like 'ladderpath-index', 'order-index', 'size-index', 'eta', 'ladderons', 'basic_building_blocks', 'targets', 'duplications_info', 'eta_info', and 'input_type'. ### Request Example ```python import ladderpath as lp strs = ['ABCDBCDBCDCDEFEF', 'AA', 'DBCDBCA', 'BCDCDAEF'] lpjson = lp.get_ladderpath( strs, info='V1.0.2.20250404_Alpha', fill_ladderons_STR=False, estimate_eta=False, save_file_name=None, show_version=True ) print(lpjson['ladderpath-index']) print(lpjson['order-index']) print(lpjson['size-index']) strs_dict = {'ABCDBCDBCDCDEFEF': 1, 'AA': 3, 'DBCDBCA': 2, 'BCDCDAEF': 1} lpjson2 = lp.get_ladderpath(strs_dict, show_version=False) eta_para = { 'n': 10, 'max_method': 'AllIdentical', 'min_method': 'EvenDist', 'min_method_nBase': 26 } lpjson3 = lp.get_ladderpath( ['ABCDBCDBCDCDEFEF', 'DBCDBCA'], estimate_eta=True, estimate_eta_para=eta_para, show_version=False ) print(lpjson3['eta']) ``` ### Response Example (Structure) ```json { "info": "V1.0.2.20250404_Alpha", "ladderpath-index": 20, "order-index": 13, "size-index": 33, "eta": null, "ladderons": {}, "basic_building_blocks": ["A", "D", "C", "E", "F", "B"], "targets": {}, "duplications_info": {}, "eta_info": {}, "input_type": "list" } ``` ``` -------------------------------- ### fill_lpjson_STR / clear_lpjson_STR Source: https://context7.com/yuernestliu/lppack/llms.txt Populates or clears the STR string cache within the lpjson structure. `fill_lpjson_STR` recursively builds and caches strings, while `clear_lpjson_STR` resets them to save memory. Both operate in-place. ```APIDOC ## `fill_lpjson_STR` / `clear_lpjson_STR` — Populate or clear the STR string cache Each ladderon and target entry has a `STR` field (index 2) that caches the explicit reconstructed string. `fill_lpjson_STR` recursively builds and caches all strings; `clear_lpjson_STR` resets them to `''` to save memory. Both operate in-place. ```python import ladderpath as lp strs = ['ABCDBCDBCDCDEFEF', 'AA', 'DBCDBCA', 'BCDCDAEF'] lpjson = lp.get_ladderpath(strs, fill_ladderons_STR=False, show_version=False) # Before fill: STR fields are empty strings print(lpjson['ladderons'][0][2]) # '' lp.fill_lpjson_STR(lpjson) # After fill: each ladderon has its explicit string content for ldID, info in lpjson['ladderons'].items(): print(f"Ladderon {ldID}: '{info[2]}'") # Ladderon 0: 'DBCDBC' # Ladderon 1: 'DBC' # ... # Clear the cache to free memory lp.clear_lpjson_STR(lpjson) print(lpjson['ladderons'][0][2]) # '' ``` ``` -------------------------------- ### Populate Ladderon String Cache Source: https://github.com/yuernestliu/lppack/blob/main/README.md Fills in the explicit string representation (STR) of each ladderon in the JSON object. This populates the cache and modifies the lpjson object in place. ```python lp.fill_lpjson_STR(lpjson) # Fills in the explicit string representation (STR) of each ladderon in the JSON (populates the cache) ``` -------------------------------- ### Compute Ladderpath-Index from Laddergraph Source: https://context7.com/yuernestliu/lppack/llms.txt Calculates the ladderpath-index contribution for one or two target sequences by traversing an existing laddergraph. This is useful for pairwise structural comparisons without recomputing the full ladderpath. Targets can be specified by ID or by their string representation. ```python import ladderpath as lp import ladderpath_tools.lambda_from_laddergraph as lp1 strs = ['ABCDBCDBCDCDEFEF', 'AA', 'DBCDBCA', 'BCDCDAEF'] lpjson = lp.get_ladderpath(strs, fill_ladderons_STR=True, show_version=False) # Ladderpath-index of a single target (by ID) lambda_single = lp1.get([-1], lpjson) print(f"lambda for target -1: {lambda_single}") # e.g. 15 # Ladderpath-index for two targets together (by ID) lambda_pair = lp1.get([-1, -3], lpjson) print(f"lambda for targets -1 and -3: {lambda_pair}") # e.g. 18 # Can also pass sequences directly instead of IDs lambda_by_str = lp1.get(['ABCDBCDBCDCDEFEF'], lpjson) print(f"lambda by string: {lambda_by_str}") # same as lambda_single ``` -------------------------------- ### compress / decompressed Source: https://context7.com/yuernestliu/lppack/llms.txt Provides functions for compact encoding and lossless reconstruction of sequence data. `compress` encodes the full target set into a compact list, and `decompressed` reconstructs the original sequence list from this compressed format. ```APIDOC ## compress / decompressed ### Description These functions provide compact encoding and lossless reconstruction of sequence data. `compress` encodes the full target set into a compact flat list using the discovered ladderon structure, storing each reused sub-sequence only once. `decompressed` reconstructs the original sequence list from the compressed format. This functionality only works when `input_type == 'list'`. ### Parameters - **compress**: - **lpjson**: The input data structure generated by `lp.get_ladderpath`. - **display** (bool): Whether to display the compressed output. - **SEP** (str): The separator character used in the compressed format. - **decompressed**: - **compressed**: The compressed data list generated by `compress`. - **display** (bool): Whether to display the decompressed output. ### Returns - **compress**: A compact list representing the encoded sequence data and ladderon structure. - **decompressed**: The reconstructed original list of sequences. ### Example ```python import ladderpath as lp import ladderpath_tools.compress as lp_c strs = ['ABCDBCDBCDCDEFEF', 'AA', 'AA', 'DBCDBCA', 'BCDCDAEF', 'AA', 'DBCDBCA', 'AAAA'] lpjson = lp.get_ladderpath(strs, show_version=False) # Compress: encodes targets + ladderon structure into a single flat list compressed = lp_c.compress(lpjson, display=True, SEP='@') # Prints: [8, '@', 'A', 1, 5, 3, 0, 0, '@', 2, '@', 2, '@', 5, 'A', ...] # Format: [nTargets, SEP, , SEP, , ..., SEP, , SEP, , ...] # Decompress: losslessly reconstructs original string list restored = lp_c.decompressed(compressed, display=True) # Prints: ['ABCDBCDBCDCDEFEF', 'AA', 'AA', 'DBCDBCA', 'BCDCDAEF', 'AA', 'DBCDBCA', 'AAAA'] assert restored == strs # True — perfect reconstruction ``` ``` -------------------------------- ### Draw Laddergraph Source: https://github.com/yuernestliu/lppack/blob/main/README.md Generates and optionally saves a laddergraph visualization based on the provided `lpjson` data. Various parameters control the display style, content filtering, and output format. ```APIDOC ## Draw Laddergraph ### Description Generates and optionally saves a laddergraph visualization based on the provided `lpjson` data. Various parameters control the display style, content filtering, and output format. ### Method `lp.draw_laddergraph(lpjson, show_longer_than=0, style='ellipse', TargetNames_UserDefined=None, warning_n_ladderons_to_show=500, rankdir='BT', color='grey', figsize=None, save_fig_name=None, figformat='pdf', cleanGVfile=True)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **lpjson** (dict) - The input JSON object containing sequence data. - **show_longer_than** (int) - Display only ladderons whose sequence length exceeds this value. If 0, all ladderons are displayed. - **style** (str) - Determines the visual style of the laddergraph. Options: `"ellipse"`, `"ellipse-OnlyShowTargetID"`, `"box"`, `"box-OnlyShowTargetID"`. - **TargetNames_UserDefined** (dict) - A user-defined mapping of target IDs to human-readable names. - **warning_n_ladderons_to_show** (int) - Maximum number of ladderons allowed in the visual output. - **rankdir** (str) - Node layout direction. Acceptable values: `"BT"`, `"TB"`, `"LR"`, `"RL"`. - **color** (str) - Color for the graph elements (e.g., color name or hex code). - **figsize** (str) - Size of the output figure (e.g., `"8,8"`). Default is auto-adjusted. - **save_fig_name** (str) - File name (with path) for saving the figure (e.g., `"figs/New_Laddergraph"`). - **figformat** (str) - File format for the saved figure (e.g., `"pdf"`, `"png"`). - **cleanGVfile** (bool) - Whether to delete the intermediate `.gv` file generated during rendering. ### Request Example ```python g = lp.draw_laddergraph(lpjson, show_longer_than = 0, style = "ellipse", TargetNames_UserDefined = {-1:'species1', -2:'new2', -3:'species3'}, warning_n_ladderons_to_show = 500, rankdir = "BT", color = "grey", figsize = "8,8", save_fig_name = None, figformat = "pdf", cleanGVfile = True) ``` ### Response #### Success Response (200) - **g** (object) - The generated graph object (specific type depends on the underlying graph library). #### Response Example ```json { "g": "" } ``` ``` -------------------------------- ### Reconstruct Target Sequence List Source: https://github.com/yuernestliu/lppack/blob/main/README.md Reconstructs the target sequence list. This is useful when duplicate sequences exist among targets, as it ensures correct ordering. ```Python reconstruct_targets_list(lpjson) -> List[int] ``` -------------------------------- ### save_ladderpath_json / load_ladderpath_json Source: https://context7.com/yuernestliu/lppack/llms.txt Functions to persist and reload Ladderpath JSON results to and from files. `save_ladderpath_json` writes the dictionary to a JSON file, and `load_ladderpath_json` reads it back, restoring integer keys. ```APIDOC ## save_ladderpath_json / load_ladderpath_json ### Description Persist and reload ladderpath results. `save_ladderpath_json` writes the ladderpath dict to a UTF-8 JSON file. `load_ladderpath_json` reads it back, automatically converting all string-keyed integer keys (including negative target IDs) back to Python `int` so the in-memory structure is identical to the original computed dict. ### Method Signatures ```python ladderpath.save_ladderpath_json(lpjson: dict, file_name: str) ladderpath.load_ladderpath_json(file_name: str) -> dict ``` ### Parameters - **lpjson** (dict) - Required (for `save_ladderpath_json`) - The ladderpath dictionary to save. - **file_name** (str) - Required - The path to the file for saving or loading. ### Returns - **None** (for `save_ladderpath_json`) - **dict** (for `load_ladderpath_json`) - The loaded ladderpath dictionary. ### Request Example ```python import ladderpath as lp strs = ['ABCDBCDBCDCDEFEF', 'AA', 'DBCDBCA', 'BCDCDAEF'] lpjson = lp.get_ladderpath(strs, save_file_name='results/my_lp', show_version=False) # -> saves to results/my_lp.json automatically # Reload from disk — all dict keys are restored as integers lpjson_loaded = lp.load_ladderpath_json('results/my_lp.json') print(type(list(lpjson_loaded['ladderons'].keys())[0])) print(lpjson_loaded['ladderpath-index']) ``` ``` -------------------------------- ### Generate LadderPath JSON Source: https://github.com/yuernestliu/lppack/blob/main/lppack/demo_scripts/demo.ipynb Calls the `get_ladderpath` function to generate the LadderPath JSON object from the input sequences. `fill_ladderons_STR` is set to `False`. ```python # estimate_eta_para={'n': 10, 'max_method': 'AllIdentical', \ # 'min_method': 'Shuffle', \ # 'min_method_nBase': None} # lpjson = lp.get_ladderpath(strs, estimate_eta = True, estimate_eta_para = estimate_eta_para, # save_file_name=None, show_version=False) # lpjson = lp.get_ladderpath(strs, save_file_name='Data/new_lpjson', show_version=False) lpjson = lp.get_ladderpath(strs, fill_ladderons_STR=False, save_file_name=None, show_version=False) lpjson ```