### Complete Workflow Example Source: https://context7.com/mossjacob/pyslingshot/llms.txt A comprehensive example demonstrating the full PySlingshot workflow from data loading to visualization and saving results. ```APIDOC ## Complete Workflow Example ### Description This example demonstrates a complete PySlingshot workflow from data loading through trajectory inference and visualization. ### Steps 1. **Load or prepare single-cell data**: Ensure data is dimensionality-reduced (e.g., UMAP, PCA). 2. **Create AnnData object**: Format data into the standard AnnData structure. 3. **Initialize and fit Slingshot**: Instantiate the `Slingshot` class and run the `fit` method. 4. **Extract pseudotime**: Obtain the unified pseudotime values for downstream analysis. 5. **Visualize results**: Plot clusters with trajectories and pseudotime ordering. 6. **Save results**: Persist the fitted model parameters. ### Request Example ```python import numpy as np from matplotlib import pyplot as plt from anndata import AnnData from pyslingshot import Slingshot # 1. Load or prepare single-cell data # Data should be dimensionality-reduced (e.g., UMAP, PCA) data = np.load("fakedata-2branch.npy", allow_pickle=True).item() cluster_labels = data["cluster_labels"] coordinates = data["data"] # 2. Create AnnData object (standard single-cell format) num_cells = coordinates.shape[0] adata = AnnData(np.zeros((num_cells, 500))) # Gene expression placeholder adata.obsm["X_umap"] = coordinates adata.obs["celltype"] = cluster_labels # 3. Initialize and fit Slingshot slingshot = Slingshot( data=adata, celltype_key="celltype", obsm_key="X_umap", start_node=5, # Root cluster (e.g., stem cells) is_debugging=False ) slingshot.fit(num_epochs=10) # 4. Extract pseudotime for downstream analysis pseudotime = slingshot.unified_pseudotime adata.obs["pseudotime"] = pseudotime # 5. Visualize results fig, axes = plt.subplots(ncols=2, figsize=(14, 5)) # Cluster visualization with trajectories axes[0].set_title("Clusters with Trajectories") slingshot.plotter.clusters(axes[0], s=4, alpha=0.5) slingshot.plotter.curves(axes[0], slingshot.curves) # Pseudotime visualization axes[1].set_title("Pseudotime Ordering") slingshot.plotter.clusters(axes[1], color_mode="pseudotime", s=5) plt.tight_layout() plt.savefig("trajectory_analysis.png", dpi=150) plt.show() # 6. Save results for later use slingshot.save_params("fitted_slingshot.npy") ``` ### Response #### Success Response (200) - **Files**: The analysis results are visualized, saved to `trajectory_analysis.png`, and model parameters are saved to `fitted_slingshot.npy`. #### Response Example (The output includes generated plots and saved files.) ``` -------------------------------- ### Install project requirements Source: https://github.com/mossjacob/pyslingshot/blob/master/README.md Use poetry to install dependencies when contributing to the source code. ```bash poetry install ``` -------------------------------- ### Install pyslingshot Source: https://github.com/mossjacob/pyslingshot/blob/master/README.md Use pip to install the package from the Python Package Index. ```bash pip install pyslingshot ``` -------------------------------- ### Setup and Fit Slingshot Source: https://context7.com/mossjacob/pyslingshot/llms.txt Initializes and fits the Slingshot model to AnnData. Requires cell type information and a starting node. The fit method trains the model over a specified number of epochs. ```python import numpy as np from anndata import AnnData from pyslingshot import Slingshot import matplotlib.pyplot as plt # Setup and fit slingshot ada = AnnData(np.zeros((1000, 500))) ada.obsm["X_umap"] = np.random.randn(1000, 2) ada.obs["celltype"] = np.random.randint(0, 10, 1000) slingshot = Slingshot(adata, celltype_key="celltype", start_node=5) slingshot.fit(num_epochs=5) # Create combined visualization fig, ax = plt.subplots(figsize=(8, 8)) # First plot clusters as background slingshot.plotter.clusters(ax, s=4, alpha=0.5) # Overlay fitted curves slingshot.plotter.curves(ax, slingshot.curves) ax.set_title("Cell Trajectories with Fitted Curves") plt.tight_layout() plt.show() ``` -------------------------------- ### Complete PySlingshot Workflow Source: https://context7.com/mossjacob/pyslingshot/llms.txt An end-to-end example demonstrating data loading, AnnData preparation, Slingshot initialization and fitting, pseudotime extraction, visualization of clusters and pseudotime, and saving model parameters. ```python import numpy as np from matplotlib import pyplot as plt from anndata import AnnData from pyslingshot import Slingshot # 1. Load or prepare single-cell data # Data should be dimensionality-reduced (e.g., UMAP, PCA) data = np.load("fakedata-2branch.npy", allow_pickle=True).item() cluster_labels = data["cluster_labels"] coordinates = data["data"] # 2. Create AnnData object (standard single-cell format) num_cells = coordinates.shape[0] ada = AnnData(np.zeros((num_cells, 500))) # Gene expression placeholder ada.obsm["X_umap"] = coordinates ada.obs["celltype"] = cluster_labels # 3. Initialize and fit Slingshot slingshot = Slingshot( data=adata, celltype_key="celltype", obsm_key="X_umap", start_node=5, # Root cluster (e.g., stem cells) is_debugging=False ) slingshot.fit(num_epochs=10) # 4. Extract pseudotime for downstream analysis pseudotime = slingshot.unified_pseudotime ada.obs["pseudotime"] = pseudotime # 5. Visualize results fig, axes = plt.subplots(ncols=2, figsize=(14, 5)) # Cluster visualization with trajectories axes[0].set_title("Clusters with Trajectories") slingshot.plotter.clusters(axes[0], s=4, alpha=0.5) slingshot.plotter.curves(axes[0], slingshot.curves) # Pseudotime visualization axes[1].set_title("Pseudotime Ordering") slingshot.plotter.clusters(axes[1], color_mode="pseudotime", s=5) plt.tight_layout() plt.savefig("trajectory_analysis.png", dpi=150) plt.show() # 6. Save results for later use slingshot.save_params("fitted_slingshot.npy") ``` -------------------------------- ### Slingshot.get_lineages() Source: https://context7.com/mossjacob/pyslingshot/llms.txt Constructs the minimum spanning tree and identifies all lineage paths from the start node to terminal nodes. ```APIDOC ## Slingshot.get_lineages() ### Description Constructs the minimum spanning tree and identifies all lineage paths from the start node to terminal nodes. After calling this method, the `lineages` attribute contains a list of `Lineage` objects representing each trajectory path through the cluster tree. ``` -------------------------------- ### Get Slingshot Lineages Source: https://context7.com/mossjacob/pyslingshot/llms.txt Constructs the minimum spanning tree and identifies all lineage paths from the start node to terminal nodes. The `lineages` attribute contains a list of `Lineage` objects. ```python import numpy as np from anndata import AnnData from pyslingshot import Slingshot # Setup slingshot adata = AnnData(np.zeros((1000, 500))) adata.obsm["X_umap"] = np.random.randn(1000, 2) adata.obs["celltype"] = np.random.randint(0, 10, 1000) slingshot = Slingshot(adata, celltype_key="celltype", start_node=5) # Explicitly get lineages (also called automatically by fit()) slingshot.get_lineages() # Access discovered lineages print(f"Number of lineages: {len(slingshot.lineages)}") for i, lineage in enumerate(slingshot.lineages): print(f"Lineage {i}: clusters {lineage.clusters}") # Access the MST structure tree = slingshot.tree # Dict mapping cluster -> list of child clusters print(f"Tree structure: {tree}") ``` -------------------------------- ### Get Unified Pseudotime Source: https://context7.com/mossjacob/pyslingshot/llms.txt Access the `unified_pseudotime` property to retrieve a NumPy array of pseudotime values for each cell. This property provides a continuous ordering of cells along their developmental trajectory based on projection onto principal curves. The values can be added to an AnnData object for further analysis. ```python import numpy as np from anndata import AnnData from pyslingshot import Slingshot # Setup and fit slingshot adata = AnnData(np.zeros((1000, 500))) adata.obsm["X_umap"] = np.random.randn(1000, 2) adata.obs["celltype"] = np.random.randint(0, 10, 1000) slingshot = Slingshot(adata, celltype_key="celltype", start_node=5) slingshot.fit(num_epochs=5) # Get pseudotime values for all cells pseudotime = slingshot.unified_pseudotime # Shape: (num_cells,) # Use pseudotime for downstream analysis print(f"Pseudotime range: {pseudotime.min():.2f} to {pseudotime.max():.2f}") print(f"Mean pseudotime: {pseudotime.mean():.2f}") # Add pseudotime to AnnData for integration with scanpy adata.obs["pseudotime"] = pseudotime ``` -------------------------------- ### Slingshot Initialization and Fitting Source: https://context7.com/mossjacob/pyslingshot/llms.txt Demonstrates how to initialize the Slingshot object with an AnnData object and fit the model to infer cell trajectories. ```APIDOC ## Slingshot Initialization and Fitting ### Description Initializes the Slingshot model with single-cell data and fits the trajectory inference model. ### Method `Slingshot(data, celltype_key, obsm_key='X_umap', start_node, is_debugging=False)` `fit(num_epochs)` ### Parameters #### Initialization Parameters - **data** (AnnData) - The AnnData object containing single-cell data. - **celltype_key** (str) - The key in `adata.obs` that stores cell type labels. - **obsm_key** (str, optional) - The key in `adata.obsm` for dimensionality reduction coordinates. Defaults to 'X_umap'. - **start_node** (int) - The cluster ID representing the starting point of the trajectories (e.g., stem cells). - **is_debugging** (bool, optional) - If True, enables debugging mode. Defaults to False. #### Fit Parameters - **num_epochs** (int) - The number of training epochs for the model. ### Request Example ```python import numpy as np from anndata import AnnData from pyslingshot import Slingshot # Setup and fit slingshot adata = AnnData(np.zeros((1000, 500))) adata.obsm["X_umap"] = np.random.randn(1000, 2) adata.obs["celltype"] = np.random.randint(0, 5, 1000) slingshot = Slingshot(adata, celltype_key="celltype", start_node=2) slingshot.fit(num_epochs=5) ``` ### Response #### Success Response (200) - **Slingshot object**: The fitted Slingshot object is returned, containing inferred trajectories and other analysis results. #### Response Example (No direct response object, the `slingshot` object is modified in place.) ``` -------------------------------- ### Initialize and Fit Slingshot Source: https://github.com/mossjacob/pyslingshot/blob/master/slingshot.ipynb Initializes the Slingshot object with the AnnData object and relevant keys, then fits the model to the data. Debugging options are available. ```python fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 10)) custom_xlim = (-12, 12) custom_ylim = (-12, 12) # plt.setp(axes, xlim=custom_xlim, ylim=custom_ylim) slingshot = Slingshot(ad, celltype_key="celltype", obsm_key="X_umap", start_node=start_node, is_debugging="verbose") slingshot.fit(num_epochs=1, debug_axes=axes) ``` -------------------------------- ### Initialize Slingshot with NumPy Arrays Source: https://context7.com/mossjacob/pyslingshot/llms.txt Initialize the Slingshot class using NumPy arrays for reduced coordinates and one-hot encoded cluster labels. The start_node defines the root cluster. ```python import numpy as np from anndata import AnnData from pyslingshot import Slingshot # Create sample single-cell data with cluster assignments num_cells = 1000 num_genes = 500 data = np.random.randn(num_cells, 2) # 2D reduced coordinates cluster_labels = np.random.randint(0, 10, num_cells) # Option 2: Using NumPy arrays directly cluster_labels_onehot = np.zeros((num_cells, 10)) cluster_labels_onehot[np.arange(num_cells), cluster_labels] = 1 slingshot = Slingshot( data=data, cluster_labels_onehot=cluster_labels_onehot, # One-hot encoded cluster assignments start_node=5 ) ``` -------------------------------- ### Lineage Class Usage Source: https://context7.com/mossjacob/pyslingshot/llms.txt Demonstrates the usage of the Lineage class, which represents a single trajectory path. It stores an ordered list of cluster indices and supports iteration and length retrieval. ```python from pyslingshot.lineage import Lineage # Lineage is typically created internally by Slingshot # but can be instantiated directly for testing lineage = Lineage(clusters=[5, 3, 1, 0]) # Access cluster list print(f"Clusters in lineage: {lineage.clusters}") # [5, 3, 1, 0] # Get lineage length print(f"Lineage length: {len(lineage)}") # 4 # Iterate over clusters for cluster_id in lineage: print(f"Cluster: {cluster_id}") # String representation print(lineage) # Lineage[5, 3, 1, 0] ``` -------------------------------- ### Initialize Slingshot with AnnData Source: https://context7.com/mossjacob/pyslingshot/llms.txt Initialize the Slingshot class using an AnnData object. Specify keys for cell type observations and reduced dimensions. The start_node defines the root cluster for trajectory inference. ```python import numpy as np from anndata import AnnData from pyslingshot import Slingshot # Create sample single-cell data with cluster assignments num_cells = 1000 num_genes = 500 data = np.random.randn(num_cells, 2) # 2D reduced coordinates cluster_labels = np.random.randint(0, 10, num_cells) # Option 1: Using AnnData object (recommended) adata = AnnData(np.zeros((num_cells, num_genes))) adata.obsm["X_umap"] = data adata.obs["celltype"] = cluster_labels slingshot = Slingshot( data=adata, celltype_key="celltype", # Key in adata.obs for cluster labels obsm_key="X_umap", # Key in adata.obsm for reduced coordinates start_node=5, # Starting cluster index (root of trajectory) end_nodes=[0, 9], # Optional terminal cluster indices is_debugging=False, # Enable verbose output approx_points=None # Number of approximation points for curves ) ``` -------------------------------- ### Lineage Class Source: https://context7.com/mossjacob/pyslingshot/llms.txt Represents a single trajectory path and supports iteration and length calculation. ```APIDOC ## Lineage Class ### Description The `Lineage` class represents a single trajectory path through the minimum spanning tree. Each lineage contains a list of cluster indices representing the ordered path from the start node to a terminal node. The class supports iteration and provides the length of the path. ### Method `Lineage(clusters)` ### Parameters - **clusters** (list) - A list of cluster indices defining the path of the lineage. ### Request Example ```python from pyslingshot.lineage import Lineage # Lineage is typically created internally by Slingshot # but can be instantiated directly for testing lineage = Lineage(clusters=[5, 3, 1, 0]) # Access cluster list print(f"Clusters in lineage: {lineage.clusters}") # [5, 3, 1, 0] # Get lineage length print(f"Lineage length: {len(lineage)}") # 4 # Iterate over clusters for cluster_id in lineage: print(f"Cluster: {cluster_id}") # String representation print(lineage) # Lineage[5, 3, 1, 0] ``` ### Response #### Success Response (200) - **Lineage object**: An instance of the Lineage class. #### Response Example ``` Clusters in lineage: [5, 3, 1, 0] Lineage length: 4 Cluster: 5 Cluster: 3 Cluster: 1 Cluster: 0 Lineage[5, 3, 1, 0] ``` ``` -------------------------------- ### Slingshot.list_lineages() Source: https://context7.com/mossjacob/pyslingshot/llms.txt Prints human-readable lineage paths using a provided mapping from cluster indices to label names. ```APIDOC ## Slingshot.list_lineages() ### Description Prints human-readable lineage paths using a provided mapping from cluster indices to label names. This is useful for interpreting trajectories in terms of biological cell types rather than numeric cluster IDs. ### Parameters - **cluster_to_label** (dict) - Required - A mapping from cluster indices to label names. ``` -------------------------------- ### Import Libraries Source: https://github.com/mossjacob/pyslingshot/blob/master/slingshot.ipynb Imports necessary libraries for data manipulation and visualization, including numpy, matplotlib, and pyslingshot. ```python %load_ext autoreload %autoreload 2 import numpy as np from matplotlib import pyplot as plt from pyslingshot import Slingshot ``` -------------------------------- ### Plot Lineage Network Diagram Source: https://context7.com/mossjacob/pyslingshot/llms.txt Generates a hierarchical network diagram of cell lineages using NetworkX and Graphviz. Requires a mapping from cluster IDs to human-readable labels for visualization. ```python import numpy as np from anndata import AnnData from pyslingshot import Slingshot # Setup and fit slingshot ada = AnnData(np.zeros((1000, 500))) ada.obsm["X_umap"] = np.random.randn(1000, 2) ada.obs["celltype"] = np.random.randint(0, 5, 1000) slingshot = Slingshot(adata, celltype_key="celltype", start_node=2) slingshot.fit(num_epochs=5) # Define cluster-to-label mapping for visualization cluster_to_label = { 0: "Stem Cell", 1: "Progenitor A", 2: "Progenitor B", 3: "Differentiated A", 4: "Differentiated B" } # Plot lineage network diagram slingshot.plotter.network( cluster_to_label=cluster_to_label, figsize=(8, 10) ) ``` -------------------------------- ### Slingshot.fit() Source: https://context7.com/mossjacob/pyslingshot/llms.txt Executes the Slingshot algorithm to fit principal curves and calculate lineage weights over a specified number of epochs. ```APIDOC ## Slingshot.fit() ### Description Runs the iterative fitting process to update principal curves and compute cell-to-lineage weights. ### Parameters #### Request Body - **num_epochs** (int) - Required - Number of iterations for curve fitting. - **debug_axes** (matplotlib.axes) - Optional - Axes for visualization during fitting. ``` -------------------------------- ### List Slingshot Lineages with Labels Source: https://context7.com/mossjacob/pyslingshot/llms.txt Prints human-readable lineage paths using a provided mapping from cluster indices to label names. Useful for interpreting trajectories in terms of biological cell types. ```python import numpy as np from anndata import AnnData from pyslingshot import Slingshot # Setup and fit slingshot adata = AnnData(np.zeros((1000, 500))) adata.obsm["X_umap"] = np.random.randn(1000, 2) adata.obs["celltype"] = np.random.randint(0, 5, 1000) slingshot = Slingshot(adata, celltype_key="celltype", start_node=2) slingshot.fit(num_epochs=5) # Define cluster-to-label mapping cluster_to_label = { 0: "Stem Cell", 1: "Progenitor A", 2: "Progenitor B", 3: "Differentiated A", 4: "Differentiated B" } # Print lineages with human-readable labels slingshot.list_lineages(cluster_to_label) # Output example: # Progenitor B, Stem Cell, Progenitor A, Differentiated A # Progenitor B, Stem Cell, Differentiated B ``` -------------------------------- ### Load or Generate Data Source: https://github.com/mossjacob/pyslingshot/blob/master/slingshot.ipynb Loads pre-generated data from a .npy file or generates synthetic data for analysis. Configures parameters like number of cells, dimensions, and branches. ```python load = True num_cells = 1000 num_dims_reduced = 2 num_branches = 2 K = 10 # cluster labels if num_branches == 2: filename = "fakedata-2branch.npy" start_node = 5 else: filename = "fakedata-1branch.npy" start_node = 4 if load: data = np.load(filename, allow_pickle=True).item() cluster_labels = data["cluster_labels"] data = data["data"] else: cluster_labels = np.zeros([num_cells], dtype=int) data = list() for k in range(K): cells = num_cells // K offset = np.random.randint(20, 2) - 10 print(offset.shape) data.append(offset + np.random.randn(num_cells // K, num_dims_reduced)) cluster_labels[k * cells : (k + 1) * cells] = k data = np.concatenate(data) np.save(filename, dict(data=data, cluster_labels=cluster_labels)) plt.scatter(data[:, 0], data[:, 1], c=cluster_labels) ``` -------------------------------- ### Save and Load Slingshot Parameters Source: https://context7.com/mossjacob/pyslingshot/llms.txt Allows saving and restoring fitted Slingshot parameters including principal curves, cell weights, and distances. Enables persisting fitted models for later use without re-running the fitting procedure. ```python import numpy as np from anndata import AnnData from pyslingshot import Slingshot # Setup and fit slingshot adata = AnnData(np.zeros((1000, 500))) adata.obsm["X_umap"] = np.random.randn(1000, 2) adata.obs["celltype"] = np.random.randint(0, 10, 1000) slingshot = Slingshot(adata, celltype_key="celltype", start_node=5) slingshot.fit(num_epochs=10) # Save fitted parameters slingshot.save_params("slingshot_params.npy") # Later: load parameters into a new Slingshot instance slingshot_loaded = Slingshot(adata, celltype_key="celltype", start_node=5) slingshot_loaded.load_params("slingshot_params.npy") # Access loaded curves and weights print(f"Loaded {len(slingshot_loaded.curves)} curves") print(f"Cell weights shape: {slingshot_loaded.cell_weights.shape}") ``` -------------------------------- ### Slingshot Class Constructor Source: https://context7.com/mossjacob/pyslingshot/llms.txt Initializes the Slingshot object with either an AnnData object or raw NumPy coordinates and cluster assignments. ```APIDOC ## Slingshot Class Constructor ### Description Initializes the Slingshot trajectory inference model. Supports input via AnnData objects or direct NumPy arrays. ### Parameters #### Request Body - **data** (AnnData/ndarray) - Required - The input data containing dimensionality-reduced coordinates. - **celltype_key** (str) - Optional - Key in adata.obs for cluster labels (required if data is AnnData). - **obsm_key** (str) - Optional - Key in adata.obsm for reduced coordinates (required if data is AnnData). - **cluster_labels_onehot** (ndarray) - Optional - One-hot encoded cluster assignments (required if data is ndarray). - **start_node** (int) - Required - The root cluster index for trajectory inference. - **end_nodes** (list) - Optional - List of terminal cluster indices. - **is_debugging** (bool) - Optional - Enable verbose output. - **approx_points** (int) - Optional - Number of approximation points for curves. ``` -------------------------------- ### SlingshotPlotter.network() Source: https://context7.com/mossjacob/pyslingshot/llms.txt Generates a hierarchical network diagram visualizing the lineage tree structure. ```APIDOC ## SlingshotPlotter.network() ### Description The `SlingshotPlotter.network()` method creates a hierarchical network diagram showing the lineage tree structure using NetworkX and Graphviz. This provides a clear visualization of branching relationships between cell types. ### Method `plotter.network(cluster_to_label=None, figsize=(8, 10))` ### Parameters - **cluster_to_label** (dict, optional) - A dictionary mapping cluster IDs to human-readable labels for display in the network. If None, cluster IDs are used. - **figsize** (tuple, optional) - The size of the figure for the network diagram. Defaults to (8, 10). ### Request Example ```python import numpy as np from anndata import AnnData from pyslingshot import Slingshot # Setup and fit slingshot adata = AnnData(np.zeros((1000, 500))) adata.obsm["X_umap"] = np.random.randn(1000, 2) adata.obs["celltype"] = np.random.randint(0, 5, 1000) slingshot = Slingshot(adata, celltype_key="celltype", start_node=2) slingshot.fit(num_epochs=5) # Define cluster-to-label mapping for visualization cluster_to_label = { 0: "Stem Cell", 1: "Progenitor A", 2: "Progenitor B", 3: "Differentiated A", 4: "Differentiated B" } # Plot lineage network diagram slingshot.plotter.network( cluster_to_label=cluster_to_label, figsize=(8, 10) ) ``` ### Response #### Success Response (200) - **matplotlib.figure.Figure**: The figure object containing the network diagram. #### Response Example (The network diagram is displayed or can be saved from the returned figure object.) ``` -------------------------------- ### SlingshotPlotter.curves() Source: https://context7.com/mossjacob/pyslingshot/llms.txt Draws the fitted principal curves representing each lineage trajectory. ```APIDOC ## SlingshotPlotter.curves() ### Description Draws the fitted principal curves representing each lineage trajectory. Curves are labeled by lineage index and can be overlaid on cluster scatter plots for comprehensive trajectory visualization. ``` -------------------------------- ### SlingshotPlotter.clusters() Source: https://context7.com/mossjacob/pyslingshot/llms.txt Visualizes cells colored by cluster assignment or pseudotime. ```APIDOC ## SlingshotPlotter.clusters() ### Description Visualizes cells colored by cluster assignment or pseudotime. The plotter is accessible via `slingshot.plotter` and supports multiple color modes including cluster-based coloring and continuous pseudotime coloring with colorbar. ### Parameters - **ax** (matplotlib.axes.Axes) - Optional - The axes to plot on. - **labels** (array-like) - Optional - Custom cluster labels. - **s** (float) - Optional - Point size. - **alpha** (float) - Optional - Transparency. - **color_mode** (str) - Optional - Mode for coloring, either 'clusters' or 'pseudotime'. ``` -------------------------------- ### Slingshot.save_params() and Slingshot.load_params() Source: https://context7.com/mossjacob/pyslingshot/llms.txt Methods for saving and restoring fitted Slingshot parameters to persist models. ```APIDOC ## Slingshot.save_params() / Slingshot.load_params() ### Description These methods allow saving and restoring fitted Slingshot parameters including principal curves, cell weights, and distances. This enables persisting fitted models for later use without re-running the computationally intensive fitting procedure. ### Parameters - **path** (str) - Required - The file path for the .npy file containing the parameters. ``` -------------------------------- ### Fit Slingshot Model Source: https://context7.com/mossjacob/pyslingshot/llms.txt Run the Slingshot algorithm for a specified number of epochs. This method updates principal curves, calculates cell-to-lineage weights, and shrinks lineage curves. Debug visualization can be enabled using matplotlib axes. ```python import numpy as np from matplotlib import pyplot as plt from anndata import AnnData from pyslingshot import Slingshot # Load or create data data = np.load("fakedata-2branch.npy", allow_pickle=True).item() cluster_labels = data["cluster_labels"] coordinates = data["data"] # Create AnnData object adata = AnnData(np.zeros((1000, 500))) adata.obsm["X_umap"] = coordinates adata.obs["celltype"] = cluster_labels # Initialize Slingshot slingshot = Slingshot( adata, celltype_key="celltype", obsm_key="X_umap", start_node=5, is_debugging=True ) # Option 1: Fit without debug visualization slingshot.fit(num_epochs=10) # Option 2: Fit with debug visualization (requires 2x2 axes grid) fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 10)) slingshot.fit(num_epochs=10, debug_axes=axes) plt.tight_layout() plt.show() ``` -------------------------------- ### Visualize Slingshot Results Source: https://github.com/mossjacob/pyslingshot/blob/master/slingshot.ipynb Visualizes the fitted slingshot curves and clusters on a plot. Allows for coloring by cluster or pseudotime. ```python fig, axes = plt.subplots(ncols=2, figsize=(12, 4)) axes[0].set_title("Clusters") axes[1].set_title("Pseudotime") slingshot.plotter.curves(axes[0], slingshot.curves) slingshot.plotter.clusters(axes[0], labels=np.arange(slingshot.num_clusters), s=4, alpha=0.5) slingshot.plotter.clusters(axes[1], color_mode="pseudotime", s=5) ``` -------------------------------- ### Plot Slingshot Clusters Source: https://context7.com/mossjacob/pyslingshot/llms.txt Visualizes cells colored by cluster assignment or pseudotime. Supports multiple color modes including cluster-based coloring and continuous pseudotime coloring with colorbar. ```python import numpy as np from matplotlib import pyplot as plt from anndata import AnnData from pyslingshot import Slingshot # Setup and fit slingshot adata = AnnData(np.zeros((1000, 500))) adata.obsm["X_umap"] = np.random.randn(1000, 2) adata.obs["celltype"] = np.random.randint(0, 10, 1000) slingshot = Slingshot(adata, celltype_key="celltype", start_node=5) slingshot.fit(num_epochs=5) # Create visualization fig, axes = plt.subplots(ncols=2, figsize=(12, 4)) # Plot clusters with custom labels axes[0].set_title("Clusters") slingshot.plotter.clusters( ax=axes[0], labels=np.arange(slingshot.num_clusters), # Custom cluster labels s=4, # Point size alpha=0.5, # Transparency color_mode="clusters" # Color by cluster ) # Plot pseudotime coloring axes[1].set_title("Pseudotime") slingshot.plotter.clusters( ax=axes[1], color_mode="pseudotime", # Color by pseudotime values s=5, alpha=0.8 ) plt.tight_layout() plt.show() ``` -------------------------------- ### Access Pseudotime Data Source: https://github.com/mossjacob/pyslingshot/blob/master/slingshot.ipynb Retrieves the unified pseudotime values calculated by the Slingshot model. This data can be used for further analysis or visualization. ```python # NOTE: the Slingshot class has a property which has the pseudotime that is used to # color the plot above pseudotime = slingshot.unified_pseudotime ``` -------------------------------- ### SlingshotPlotter.clusters() and SlingshotPlotter.curves() Source: https://context7.com/mossjacob/pyslingshot/llms.txt Visualizes cell clusters and the inferred trajectory curves on a given matplotlib axes. ```APIDOC ## SlingshotPlotter.clusters() and SlingshotPlotter.curves() ### Description These methods are used to visualize cell clusters and the inferred trajectory curves on a matplotlib axes object. ### Method `plotter.clusters(ax, s=4, alpha=0.5, color_mode='celltype')` `plotter.curves(ax, curves)` ### Parameters #### `clusters` Parameters - **ax** (matplotlib.axes.Axes) - The axes object to plot on. - **s** (float, optional) - Marker size for the cells. Defaults to 4. - **alpha** (float, optional) - Alpha transparency for the cell markers. Defaults to 0.5. - **color_mode** (str, optional) - How to color the cells. Options include 'celltype' or 'pseudotime'. Defaults to 'celltype'. #### `curves` Parameters - **ax** (matplotlib.axes.Axes) - The axes object to plot on. - **curves** (list) - A list of Lineage objects representing the inferred trajectories. ### Request Example ```python import matplotlib.pyplot as plt import numpy as np from anndata import AnnData from pyslingshot import Slingshot # Setup and fit slingshot adata = AnnData(np.zeros((1000, 500))) adata.obsm["X_umap"] = np.random.randn(1000, 2) adata.obs["celltype"] = np.random.randint(0, 10, 1000) slingshot = Slingshot(adata, celltype_key="celltype", start_node=5) slingshot.fit(num_epochs=5) # Create combined visualization fig, ax = plt.subplots(figsize=(8, 8)) # First plot clusters as background slingshot.plotter.clusters(ax, s=4, alpha=0.5) # Overlay fitted curves slingshot.plotter.curves(ax, slingshot.curves) ax.set_title("Cell Trajectories with Fitted Curves") plt.tight_layout() plt.show() ``` ### Response #### Success Response (200) - **matplotlib.axes.Axes**: The axes object with the plots rendered. #### Response Example (Plots are rendered directly to the provided axes object.) ``` -------------------------------- ### Convert Data to AnnData Object Source: https://github.com/mossjacob/pyslingshot/blob/master/slingshot.ipynb Converts the processed data into an AnnData object, which is a standard format for single-cell data analysis in Python. This step is optional but recommended for compatibility with other tools. ```python from anndata import AnnData num_cells = 1000 num_genes = 500 ad = AnnData(np.zeros((num_cells, num_genes))) ad.obsm["X_umap"] = data ad.obs["celltype"] = cluster_labels ad ``` -------------------------------- ### Plot Slingshot Curves Source: https://context7.com/mossjacob/pyslingshot/llms.txt Draws the fitted principal curves representing each lineage trajectory. Curves are labeled by lineage index and can be overlaid on cluster scatter plots for comprehensive trajectory visualization. ```python import numpy as np from matplotlib import pyplot as plt from anndata import AnnData from pyslingshot import Slingshot ``` -------------------------------- ### Slingshot.unified_pseudotime Source: https://context7.com/mossjacob/pyslingshot/llms.txt Retrieves the calculated pseudotime values for each cell after the fitting process is complete. ```APIDOC ## Slingshot.unified_pseudotime ### Description Returns a NumPy array containing the continuous pseudotime value for each cell based on its projection onto the principal curve. ### Response #### Success Response (200) - **pseudotime** (ndarray) - Array of shape (num_cells,) containing pseudotime values. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.