lionz 0.19.6
A toolkit for precise segmentation of tumors in PET/CT scans.
Requires Python: >=3.10
Keywords: lesion segmentation, tumors, PET/CT, medical imaging

![Lion-logo.png](/Images/lion.png)
## LION (Lesion segmentatION): Loud. Proud. Unbounded. 🦁
[![PyPI Downloads](https://static.pepy.tech/personalized-badge/lionz?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=MAGENTA&left_text=Total+Downloads)](https://pepy.tech/projects/lionz)
[![DOI](https://zenodo.org/badge/685935027.svg)](https://zenodo.org/badge/latestdoi/685935027)<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-red.svg?style=flat-square&logo=gnu&color=FF0000)](https://www.gnu.org/licenses/gpl-3.0)
[![Commercial License](https://img.shields.io/badge/Commercial%20Use-Contact%20Zenta-orange?style=flat-square&logo=data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iOTIiIGhlaWdodD0iOTIiIHZpZXdCb3g9IjAgMCA5MiA5MiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iNDUuODk2NiIgY3k9IjcuOTEyOTYiIHI9IjYuMjkxNzEiIHRyYW5zZm9ybT0icm90YXRlKDkwIDQ1Ljg5NjYgNy45MTI5NikiIGZpbGw9IiNFNkU0REUiIHN0cm9rZT0iI0U2RTRERSIgc3Ryb2tlLXdpZHRoPSIzLjI0MjUxIi8+CjxjaXJjbGUgY3g9IjgzLjg3ODEiIGN5PSIyNi45MDQyIiByPSI2LjI5MTcxIiB0cmFuc2Zvcm09InJvdGF0ZSg5MCA4My44NzgxIDI2LjkwNDIpIiBmaWxsPSIjRTZFNERFIiBzdHJva2U9IiNFNkU0REUiIHN0cm9rZS13aWR0aD0iMy4yNDI1MSIvPgo8Y2lyY2xlIGN4PSI3LjkxMzIxIiBjeT0iMjYuOTA0MiIgcj0iNi4yOTE3MSIg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NDUiIGhlaWdodD0iMTIuNTgzNCIgcng9IjYuMjkxNzEiIHRyYW5zZm9ybT0icm90YXRlKDkwIDE0LjIwNDkgMzkuNjA0NykiIGZpbGw9IiNFNkU0REUiIHN0cm9rZT0iI0U2RTRERSIgc3Ryb2tlLXdpZHRoPSIzLjI0MjUxIi8+Cjwvc3ZnPgo=)](mailto:lalith@zenta.solutions)




LION has roared onto the scene, revolutionizing the way we view lesion segmentation. Born from the same lineage as lion 3.0, LION is laser-focused on tumor segmentation. Our curated models, each crafted with precision, cater to various tracers, setting the gold standard in lesion detection.

✨ **Exclusive Engineering Paradigm**: With LION, segmentation is not just a task; it's an orchestrated dance of models. Define workflows for each model, mix and match channels as some models thrive on PET/CT while others are optimized for just PET or CT. Run them in a sequence that maximizes output and efficiency. This unique trait of LION lets you tailor the process to your exact needs, making lesion segmentation an art of precision.


🔔 **Flexibility Unleashed**: Whether you're looking for a command-line tool for batch processing or a library package for your Python projects, LION has you covered. Seamlessly integrate it into your work environment and watch it shine.

Dive into the exciting world of PET tumor segmentation with LION and experience the future today!

🔔 **Important Notification:** As of now, the LION tool is optimized and validated for FDG imaging. Development for PSMA imaging is ongoing and will be available soon. We appreciate your patience and understanding. Stay tuned for updates! 🔔

---

## **Requirements** ✅

For an optimal experience with LION, ensure the following:

- **Operating System**: LION runs smoothly on Windows, Mac, or Linux.
- **Memory**: At least 32GB of RAM ensures LION operates without a hitch.
- **GPU**: For blazing-fast results, an NVIDIA GPU or an Apple MPS chip is highly recommended. But if you don't have one, fret not! LION will still get the job done, just at a more leisurely pace.
- **Python**: Version 3.10!

---

## **Installation Guide** 🛠️

Navigating the installation process is a breeze. Just follow the steps below:

**For Linux and MacOS** 🐧🍏
1. Create a Python environment, for example, 'lion-env'.
```bash
python3.10 -m venv lion-env
```
2. Activate your environment.
```bash
source lion-env/bin/activate  # for Linux
source lion-env/bin/activate  # for MacOS
```
3. Install LION.
```bash
pip install lionz
```

**From source using uv** 🧑‍💻

If you are working from a clone of this repository, the project is now managed with [uv](https://github.com/astral-sh/uv).

```bash
# inside the cloned repository
uv sync
uv run lionz -h
```

The `uv sync` command creates a virtual environment, resolves dependencies using `pyproject.toml`, and produces a `uv.lock` so builds stay reproducible.
## For Macs powered by Apple Silicon (M series chips with MPS) 🍏

> Yes, it works. But you'll need to follow these steps carefully. Grab a ☕ or 🍺 — this may take a few minutes.
> Note: Please make sure you have the right version of `cmake`, as well as `ninja` installed.
> Also you need `git`, `xcode command line tools` installed. Using `brew` is the safest option. 

1. Create and activate a virtual environment (We recommend Python 3.10 for stability)

   ```bash
    python3.10 -m venv lion-env
    source lion-env/bin/activate
   ```

2. Install lion and the MPS-compatible PyTorch fork

   You’ll need a special PyTorch build tailored for Apple’s Metal backend (MPS), which doesn’t use CUDA.

   ```bash
    pip install lionz
    pip uninstall torch  # ensures clean install; avoids conflicts with lion-installed version
    git clone https://github.com/LalithShiyam/pytorch-mps.git
    cd pytorch-mps
   ```

4. Fix your CMake version (IMPORTANT ⚠️)

   **Do not use CMake 4.x** — it will break the build due to compatibility issues with `protobuf`.

   Check your version:

   ```bash
    cmake --version
   ```

   If it's **4.0 or higher**, downgrade to a compatible version (e.g., 3.29.2):

   ```bash
   pip uninstall cmake -y
   pip install cmake==3.29.2
   ```

4. Build the custom PyTorch fork for MPS

   This will build PyTorch without CUDA (which Apple Silicon doesn’t support anyway):
  
   ```bash
   USE_CUDA=0 python setup.py develop --verbose 2>&1 | tee build.log
   ```

> ✅ This may take some time. If it completes without errors, you’re good to go.

5. Patch `nnUNetTrainer.py` (one-time fix)

   Due to differences in PyTorch exports, `nnUNet` may crash with:

   ```
   ImportError: cannot import name 'GradScaler' from 'torch'
   ```

To fix it:

1. Open the following file inside your lion-env folder:

   ```
   ~/lion-env/lib/python3.10/site-packages/nnunetv2/training/nnUNetTrainer/nnUNetTrainer.py
   ```

2. Replace this line 43:

   ```python
   from torch import GradScaler
   ```

   with:

   ```python
   from torch.cuda.amp import GradScaler
   ```
✅ That’s it!

Now you’re ready to use **LION on Apple Silicon** with MPS acceleration. 🏎⚡
If anything crashes, blame the silicon gods… or just open an issue. We're here to help.



**For Windows** 🪟
1. Set up a Python environment, say 'lion-env'.
```bash
python -m venv lion-env
```
2. Get your environment up and running.
```bash
.\lion-env\Scripts\activate
```
3. Hop over to the PyTorch website and fetch the right version for your system. This step is crucial!
4. Finish up by installing LION.
```bash
pip install lionz
```

---

## 🧬 Supported Models by Tracer Type

| Tracer | Model Name |        Status         |     Training Dataset Size     |                Cancer Type                 |
|:------:|:----------:|:---------------------:|:------------------------------:|:------------------------------------------:|
|  FDG   |   `fdg`    | ✅ Stable & validated  |  5,341 patients (multicenter)  | `breast` `melanoma` `lung` `lymphoma` `colorectal` |
| PSMA   |  `psma`    |  🔧 In development     | ~1,200 patients (in progress)  |                `prostate`                  |

---

## **Usage Guide** 📚

**Command-line Tool for Batch Processing** 💻

Starting with LION is as intuitive as it gets. Here's how:

```bash
lionz -d <path_to_image_dir> -m <model_name>
```
Replace `<path_to_image_dir>` with your image directory and `<model_name>` with your chosen segmentation model's name.

**Real-Life Usage Example 🌟**

To run LION using the 'fdg' model on a batch of images located in `/path/to/dummy/image/directory`, you'd simply execute:

```bash
lionz -d /path/to/dummy/image/directory -m fdg
```
**Thresholding Feature ✂️** 

LION is also equipped with a thresholding feature to refine your segmentations. Just add -t and the value you want to use for thresholding. 

**Important:** Thresholding is only supported with DICOM or SUV NIfTI inputs! If you don't require thresholding, feel free to use any LION-compliant input.

Here's how you can apply thresholding for SUV 2.5:
```bash
lionz -d /path/to/dummy/image/directory -m fdg -t 2.5
```
**Generating a MIP with overalayed segmentation**

If you want to have a quick glance at the segmentation by having a rotation MIP with the obtained segmentations overlayed all you need is to add the -gen-mip flag to your command.

```bash
lionz -d /path/to/dummy/image/directory -m fdg -gen-mip
```
And, if you ever find yourself needing some guidance:
```bash
lionz -h
```
This trusty command will spill all the beans about available models and their specialties.

### Using LION as a Library 📦🐍

LION isn't just a command-line powerhouse; it’s also a flexible library for Python projects. Here’s how to make the most of it:

First, import the `lion` function from the `lionz` package in your Python script:

 ```python
from lionz import lion
 ```

#### *Calling the `lion` Function* 🦌

The `lion` function is versatile and accepts various input types. It takes five main arguments:

1. `input`: The data to process, which can be:
   - A path to an input file or directory (NIfTI, either `.nii` or `.nii.gz`).
   - A tuple containing a NumPy array and its spacing (e.g., `numpy_array`, `(spacing_x, spacing_y, spacing_z)`).
   - A `SimpleITK` image object.
2. `model_name`: The model name to use for segmentation.
3. `output_dir`: The directory where the results will be saved.
4. `accelerator`: The type of accelerator to use (`"cpu"`, `"cuda"`, or `"mps"` for Mac).
5. `threshold`: The value to use for thresholding. Optional

#### Examples 📂✂️💻

Here are some examples to illustrate different ways to use the `lion` function:

1. **Using a file path and multiple models:**
    ```python
    lion('/path/to/input/file', 'fdg', '/path/to/save/output', 'cuda', 2.5)
    ```

2. **Using a NumPy array with spacing:**
    ```python
    lion((numpy_array, (1.5, 1.5, 1.5)), 'psma', '/path/to/save/output', 'cuda', 2.5)
    ```

3. **Using a SimpleITK image:**
    ```python
    lion(simple_itk_image, 'fdg', '/path/to/save/output', 'cuda', 2.5)
    ```
    
#### Usage of `lion()` in your code
To use the `lion()` function, ensure that you wrap the function call within a main guard to prevent recursive process creation errors:
```python
from lionz import lion

if __name__ == '__main__':
    input_file = '/path/to/input/file'
    model = 'fdg'
    output_directory = '/path/to/save/output'
    accelerator = 'cuda'
    threshold = 2.5
    lion(input_file, models, output_directory, accelerator, threshold)
```

---

## **Directory Conventions for LION** 📂🏷️

For batch mode users ⚠️, ensure your data structure and naming conventions align with the provided guidelines. LION is compatible with both DICOM and NIFTI formats. For DICOM, LION discerns the modality from tags. For NIFTI, file naming is key. Allowed modality tags: `PT` for PET, `CT` for CT as of now.

**Directory Structure** 🌳

Organize your dataset as follows:

```
📂 LION_data/
│
├── 📁 Subject1
│   ├── 📁 Modality1
│   │   └── 📄 File1.dcm
│   └── 📁 Modality2
│       └── 📄 File2.dcm
├── 📁 Subject2
│   └── 📄 Modality1_Subject2.nii
│   └── 📄 Modality2_Subject2.nii
└── 📁 Subject3
    └── 📄 Modality1_Subject3.nii
    └── 📄 Modality2_Subject3.nii

```
## **Naming Conventions for NIFTI** 📝

Ensure you attach the correct modality as a prefix in the file name.




---

### Dataset Organization for FDG Model

For the FDG model, your dataset must be organized strictly according to the guidelines below, considering PT (Positron Emission Tomography) and CT (Computed Tomography) as the primary modalities:

```
📂 FDG_data/
│
├── 📁 Patient1
│   └── 📁 AnyFolderNameForPT
│       ├── 📄 DICOM_File1.dcm
│       ├── 📄 DICOM_File2.dcm
│       └── ...
├── 📁 Patient2
│   └── 📄 PT_Patient2.nii
└── 📁 Patient3
    └── 📄 PT_Patient3.nii.gz
```

**Important Guidelines:**

- Each patient's data must be stored in a dedicated folder.
- For DICOM format:
  - Patient1's example demonstrates the DICOM structure. Inside each patient's main folder, the inner folders can have any name for PT modality. Multiple DICOM files can be stored in these folders. The modality (PT) will be inferred from the DICOM's modality tag.
- For NIFTI format:
  - Patient2 and Patient3 examples demonstrate the NIFTI structure. For these, PT modality is directly within the patient's folder with the `.nii` extension. Adjust the naming structure as per the specifics of your dataset if required.
  
- Only DICOM and NIFTI formats are supported. No other imaging formats are allowed.
- Adhering to these guidelines is non-negotiable for both FDG and PSMA models.



---

# 📁 LIONz Output Folder Structure for FDG Model

When you run the FDG model, an output folder named `lionz-fdg-<timestamp>` will be generated in the respective subject directory. Here's a breakdown of the folder structure:

```
📂 lionz-fdg-2023-09-18-10-07-25/
│
│
├── 📂 PT
│   └── 📄 PT_0147.nii.gz
│
├── 📂 segmentations
│   ├── 📄 0147_no_tumor_seg.nii.gz
│   └── 📽 0147_rotational_mip.gif (optional)
│
└── 📂 stats
    └── 📄 0147_metrics.csv
```

## 📌 Breakdown:
- 📂 **segmentations**: Houses all segmentation-related files.
  - 📄 NIFTI files showing segmentations.
  - 📽 GIF files representing various views. Only when requested by the user.
- 📂 **stats**: Contains `.csv` files with metrics related to the analysis.

---

Harness the power of LION and elevate your PET tumor segmentation game! 🚀🦁

Remember, the LION team is here to support you every step of the way. Should you need any assistance or if you'd like to provide feedback, don't hesitate to reach out to our dedicated support team in discord.

With LION by your side, your lesion segmentation adventures will be unstoppable! 😺🌟

Dive in now and make PET tumor segmentation a seamless experience!

---

Thank you for trusting LION with your PET tumor segmentation needs. We're committed to providing you with top-notch tools and services that make your work easier and more efficient.



---

## **A Note on QIMP Python Packages: The 'Z' Factor 📚🚀**

Every Python package at QIMP carries a unique mark – a distinctive 'Z' at the end of their names. This isn't just a quirk or a random choice. The 'Z' is emblematic, an insignia of our forward-leaning vision and unwavering dedication to continuous innovation.

Take, for instance, our LION package, dubbed 'lionz', pronounced "lion-zee". Now, one might wonder, why append a 'Z'?

In the expansive realm of science and mathematics, 'Z' is frequently invoked as a representation of the unexplored, the variables that are shrouded in mystery, or the ultimate point in a sequence. This mirrors our ethos at QIMP perfectly. We're inveterate boundary-pushers, ever eager to trek into the uncharted, always aligning ourselves with the vanguard of technological advancement. The 'Z' is a testament to this ethos. It symbolizes our ceaseless endeavor to transcend the conventional, to journey into the untouched, and to be the torchbearers of the future in medical imaging.

So, the next time you stumble upon a 'Z' in any of our package names, let it serve as a reminder of the zest for exploration and the spirit of discovery that fuels us. With QIMP, you're not merely downloading a tool; you're aligning yourself with a movement that aims to redefine the landscape of medical image processing. Let's soar into the realms of the 'Z' dimension, side by side! 🚀

---

## Contributors ✨

Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):

<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
  <tbody>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/LalithShiyam"><img src="https://avatars.githubusercontent.com/u/48599863?v=4?s=100" width="100px;" alt="Lalith Kumar Shiyam Sundar"/><br /><sub><b>Lalith Kumar Shiyam Sundar</b></sub></a><br /><a href="https://github.com/LalithShiyam/LION/commits?author=LalithShiyam" title="Code">💻</a></td>  
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/mprires"><img src="https://avatars.githubusercontent.com/u/48754309?v=4?s=100" width="100px;" alt="Manuel Pires"/><br /><sub><b>Manuel Pires</b></sub></a><br /><a href="https://github.com/LalithShiyam/LION/commits?author=mprires" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/Keyn34"><img src="https://avatars.githubusercontent.com/u/87951050?v=4?s=100" width="100px;" alt="Sebastian Gutschmayer"/><br /><sub><b>Sebastian Gutschmayer</b></sub></a><br /><a href="https://github.com/LalithShiyam/LION/commits?author=Keyn34" title="Code">💻</a></td>
    </tr>
  </tbody>
</table>

<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->

<!-- ALL-CONTRIBUTORS-LIST:END -->

This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!