> ## Documentation Index
> Fetch the complete documentation index at: https://demo.agenticlabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# utilities.py

## High-level description

This file contains utility functions for plotting phylogenetic trees locally using libraries like Matplotlib and Plotly. It provides functions for placing tree nodes and branches on a coordinate system, generating color strips for annotations, and creating indel heatmaps.

## Code Structure

The code consists of several independent utility functions that can be used for plotting phylogenetic trees. These functions include: `degrees_to_radians`, `polar_to_cartesian`, `polars_to_cartesians`, `place_tree`, `place_colorstrip`, `generate_random_color`, `get_random_indel_colors`, `get_indel_colors`, `hex_to_rgb`, `rgb_to_hex`, and `prepare_alleletable`.

## References

This file references the `CassiopeiaTree` class from `cassiopeia.data` and the `convert_alleletable_to_lineage_profile` function from `cassiopeia.preprocess.utilities`.

## Symbols

### `degrees_to_radians`

#### Description

Converts an angle from degrees to radians.

#### Inputs

| Name    | Type  | Description       |
| :------ | :---- | :---------------- |
| degrees | float | Angle in degrees. |

#### Outputs

| Name  | Type  | Description       |
| :---- | :---- | :---------------- |
| float | float | Angle in radians. |

### `polar_to_cartesian`

#### Description

Converts polar coordinates (angle and radius) to Cartesian coordinates (x and y).

#### Inputs

| Name    | Type  | Description       |
| :------ | :---- | :---------------- |
| degrees | float | Angle in degrees. |
| r       | float | Radius.           |

#### Outputs

| Name                 | Type                 | Description                                 |
| :------------------- | :------------------- | :------------------------------------------ |
| Tuple\[float, float] | Tuple\[float, float] | A tuple containing the x and y coordinates. |

### `polars_to_cartesians`

#### Description

Converts a list of polar coordinates to a list of Cartesian coordinates.

#### Inputs

| Name    | Type         | Description                |
| :------ | :----------- | :------------------------- |
| degrees | List\[float] | List of angles in degrees. |
| rs      | List\[float] | List of radii.             |

#### Outputs

| Name                               | Type                               | Description                                                 |
| :--------------------------------- | :--------------------------------- | :---------------------------------------------------------- |
| Tuple\[List\[float], List\[float]] | Tuple\[List\[float], List\[float]] | Two lists, containing the x and y coordinates respectively. |

### `place_tree`

#### Description

Computes the coordinates of nodes and branches in a `CassiopeiaTree` for visualization. It supports both rectangular and polar coordinate systems and offers options for customizing the tree layout.

#### Inputs

| Name                            | Type                                                   | Description                                                                                                           |
| :------------------------------ | :----------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------- |
| tree                            | CassiopeiaTree                                         | The tree to place on the coordinate grid.                                                                             |
| depth\_key                      | Optional\[str]                                         | The node attribute to use as the depth of the nodes. If not provided, the distances from the root are used.           |
| orient                          | Union\[Literal\["down", "up", "left", "right"], float] | The orientation of the tree. Can be "down", "up", "left", "right" for rectangular plots, or a number for polar plots. |
| depth\_scale                    | float                                                  | Scale the depth of the tree by this amount.                                                                           |
| width\_scale                    | float                                                  | Scale the width of the tree by this amount.                                                                           |
| extend\_branches                | bool                                                   | Extend branch lengths to equalize distances from the root to all nodes.                                               |
| angled\_branches                | bool                                                   | Display branches as angled lines instead of straight lines.                                                           |
| polar\_interpolation\_threshold | float                                                  | Threshold for adding interpolation points in polar plots to smooth out large angles.                                  |
| polar\_interpolation\_step      | float                                                  | Interpolation step for polar plots.                                                                                   |
| add\_root                       | bool                                                   | Add a synthetic root node to the tree.                                                                                |

#### Outputs

| Name                                                                                                  | Type                                                                                                  | Description                                                                                        |
| :---------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------- |
| Tuple\[Dict\[str, Tuple\[float, float]], Dict\[Tuple\[str, str], Tuple\[List\[float], List\[float]]]] | Tuple\[Dict\[str, Tuple\[float, float]], Dict\[Tuple\[str, str], Tuple\[List\[float], List\[float]]]] | Two dictionaries: the first contains node coordinates, and the second contains branch coordinates. |

#### Internal Logic

The function first places the leaves of the tree, then iteratively places internal nodes based on the positions of their children. It supports both rectangular and polar coordinate systems and offers options for customizing the tree layout, such as extending branches, angling branches, and adding a synthetic root node.

### `place_colorstrip`

#### Description

Computes the coordinates of boxes for a color strip annotation, which can be used to visualize categorical or continuous data alongside the tree.

#### Inputs

| Name           | Type                                             | Description                                                 |
| :------------- | :----------------------------------------------- | :---------------------------------------------------------- |
| anchor\_coords | Dict\[str, Tuple\[float, float]]                 | Dictionary of anchor coordinates for the color strip boxes. |
| width          | float                                            | Width of the box.                                           |
| height         | float                                            | Height of the box.                                          |
| spacing        | float                                            | Space between consecutive color strips.                     |
| loc            | Literal\["left", "right", "up", "down", "polar"] | Location of the boxes relative to the anchors.              |

#### Outputs

| Name                                                                                     | Type                                                                                     | Description                                                                 |
| :--------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------- |
| Tuple\[Dict\[str, Tuple\[List\[float], List\[float]]], Dict\[str, Tuple\[float, float]]] | Tuple\[Dict\[str, Tuple\[List\[float], List\[float]]], Dict\[str, Tuple\[float, float]]] | A dictionary of box coordinates and a dictionary of new anchor coordinates. |

### `generate_random_color`

#### Description

Generates a random RGB color within specified ranges for each color channel.

#### Inputs

| Name          | Type                             | Description                            |
| :------------ | :------------------------------- | :------------------------------------- |
| r\_range      | Tuple\[float, float]             | Range of values for the red channel.   |
| g\_range      | Tuple\[float, float]             | Range of values for the green channel. |
| b\_range      | Tuple\[float, float]             | Range of values for the blue channel.  |
| random\_state | Optional\[np.random.RandomState] | Random state for reproducibility.      |

#### Outputs

| Name                  | Type                  | Description                                                 |
| :-------------------- | :-------------------- | :---------------------------------------------------------- |
| Tuple\[int, int, int] | Tuple\[int, int, int] | A tuple containing the randomly generated RGB color values. |

### `get_random_indel_colors`

#### Description

Assigns random HSV colors to each unique indel in a lineage profile.

#### Inputs

| Name             | Type                             | Description                                    |
| :--------------- | :------------------------------- | :--------------------------------------------- |
| lineage\_profile | pd.DataFrame                     | Lineage profile containing indel observations. |
| random\_state    | Optional\[np.random.RandomState] | Random state for reproducibility.              |

#### Outputs

| Name         | Type         | Description                               |
| :----------- | :----------- | :---------------------------------------- |
| pd.DataFrame | pd.DataFrame | A DataFrame mapping indels to HSV colors. |

### `get_indel_colors`

#### Description

Maps indels to HSV colors based on their prior probabilities, with rarer indels receiving brighter colors.

#### Inputs

| Name          | Type                             | Description                                |
| :------------ | :------------------------------- | :----------------------------------------- |
| indel\_priors | pd.DataFrame                     | DataFrame mapping indels to probabilities. |
| random\_state | Optional\[np.random.RandomState] | Random state for reproducibility.          |

#### Outputs

| Name         | Type         | Description                               |
| :----------- | :----------- | :---------------------------------------- |
| pd.DataFrame | pd.DataFrame | A DataFrame mapping indels to HSV colors. |

### `hex_to_rgb`

#### Description

Converts a hexadecimal color code to an RGB tuple.

#### Inputs

| Name  | Type | Description                               |
| :---- | :--- | :---------------------------------------- |
| value | str  | Hexadecimal color code (e.g., "#FF0000"). |

#### Outputs

| Name                  | Type                  | Description                              |
| :-------------------- | :-------------------- | :--------------------------------------- |
| Tuple\[int, int, int] | Tuple\[int, int, int] | A tuple containing the RGB color values. |

### `rgb_to_hex`

#### Description

Converts an RGB tuple to a hexadecimal color code.

#### Inputs

| Name | Type                  | Description                              |
| :--- | :-------------------- | :--------------------------------------- |
| rgb  | Tuple\[int, int, int] | A tuple containing the RGB color values. |

#### Outputs

| Name | Type | Description                               |
| :--- | :--- | :---------------------------------------- |
| str  | str  | Hexadecimal color code (e.g., "#FF0000"). |

### `prepare_alleletable`

#### Description

Prepares an allele table for plotting by generating indel colors and creating a lineage profile.

#### Inputs

| Name          | Type                             | Description                                 |
| :------------ | :------------------------------- | :------------------------------------------ |
| allele\_table | pd.DataFrame                     | Allele table containing indel observations. |
| leaves        | List\[str]                       | List of leaf node names in the tree.        |
| indel\_priors | Optional\[pd.DataFrame]          | DataFrame mapping indels to probabilities.  |
| random\_state | Optional\[np.random.RandomState] | Random state for reproducibility.           |

#### Outputs

| Name                               | Type                               | Description                                                            |
| :--------------------------------- | :--------------------------------- | :--------------------------------------------------------------------- |
| Tuple\[pd.DataFrame, pd.DataFrame] | Tuple\[pd.DataFrame, pd.DataFrame] | A tuple containing the lineage profile and indel colors as DataFrames. |

#### Internal Logic

The function first converts the allele table to a lineage profile using the `convert_alleletable_to_lineage_profile` function. Then, it generates indel colors either randomly or based on prior probabilities, depending on whether `indel_priors` is provided.
