Metadata-Version: 2.4
Name: behavython
Version: 0.9.9rc13
Summary: Automated behavioral analysis software and pipeline for neuroscience.
Author-email: Matheus Costa <matheuscosta3004@gmail.com>, João Pedro <mcjpedro@gmail.com>
License-Expression: GPL-3.0-only
Project-URL: Homepage, https://github.com/mrdrzit/Behavython
Project-URL: Bug Tracker, https://github.com/mrdrzit/Behavython/issues
Keywords: neuroscience,behavior,deeplabcut,plusmaze,openfield
Requires-Python: <3.11,>=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: CITATION.cff
Requires-Dist: numpy<2.0
Requires-Dist: matplotlib<4.0,>=3.8.3
Requires-Dist: seaborn
Requires-Dist: pandas
Requires-Dist: scipy
Requires-Dist: openpyxl
Requires-Dist: scikit-image
Requires-Dist: tables
Requires-Dist: opencv-python
Requires-Dist: PyYAML
Requires-Dist: tqdm
Requires-Dist: debugpy
Requires-Dist: natsort
Requires-Dist: pyarrow
Requires-Dist: flask
Requires-Dist: shapely
Requires-Dist: requests
Requires-Dist: PySide6>=6.7.0
Provides-Extra: tf
Requires-Dist: deeplabcut[gui]==2.3.10; extra == "tf"
Requires-Dist: tensorflow<2.11; extra == "tf"
Requires-Dist: tensorpack; extra == "tf"
Requires-Dist: tf_slim; extra == "tf"
Provides-Extra: torch
Requires-Dist: deeplabcut[gui]>=3.0.2; extra == "torch"
Dynamic: license-file

[![Issues](https://img.shields.io/github/issues/mrdrzit/Behavython)](https://github.com/mrdrzit/Behavython/issues)
[![Closed Issues](https://img.shields.io/github/issues-closed/mrdrzit/Behavython?color=21e00b)](https://github.com/mrdrzit/Behavython/issues?q=is%3Aissue+is%3Aclosed)
[![License](https://img.shields.io/github/license/mrdrzit/Behavython)](https://github.com/mrdrzit/Behavython/blob/main/LICENSE)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.23044777.svg)](https://doi.org/10.5281/zenodo.23044777)

<br/>

<div align="center">
  <img src="https://raw.githubusercontent.com/mrdrzit/behavython/refs/heads/main/src/behavython/gui/assets/images/logo.png" width="300" alt="Behavython logo"/>

  <p>
    <strong>Automated Behavioral Analysis Interface</strong><br/>
    Currently built to integrate seamlessly with <a href="https://deeplabcut.github.io/DeepLabCut/README.html">DeepLabCut</a><br/>
    Other tools coming soon!
  </p>

  <p>
    <a href="https://github.com/mrdrzit/Behavython/issues">Report Bug</a>
    ·
    <a href="https://github.com/mrdrzit/Behavython/issues">Request Feature</a>
  </p>
</div>

---

## Table of Contents
- [About](#about)
- [Getting Started](#getting-started)
  - [Standalone Offline Installer (Windows)](#standalone-offline-installer-windows)
  - [Automated Installation (Windows)](#automated-installation-windows)
  - [Step-by-Step Installation (Manual)](#step-by-step-installation-manual)
  - [Launching Behavython](#launching-behavython)
- [Using the GUI](#using-the-gui)
- [CLI Usage](#cli-usage)
- [Pretrained Models](#pretrained-models)
- [Video Pre-processing](#video-pre-processing-experimental)
- [Workflow & Configuration](#workflow--configuration)
- [Outputs & Metrics](#outputs--metrics)
- [Contributing](#contributing)
- [Citation](#citation)
- [License](#license)
- [Contact](#contact)
- [Acknowledgments](#acknowledgments)

---

## About

Behavython is an automated, high-throughput behavioral analysis interface. It features a modular architecture that converts raw tracking data (CSV/H5) into structured, biologically relevant behavioral metrics.

It natively supports:
- **Geometry-based paradigms:** Open Field, Elevated Plus Maze (EPM)
- **Interaction-based paradigms:** Social Recognition, Social Discrimination

The software enforces strict scientific reproducibility through automated environment management, robust data validation, and granular metric exports.

---

## Getting Started

### Standalone Offline Installer (Windows)

For machines without Conda, Python, or administrative permissions to download packages at runtime, we provide a self-contained offline installer bundling Python 3.10, PyTorch, DeepLabCut 3.0+, and the complete CUDA runtime:

* **Download on Zenodo:** [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.23044777.svg)](https://zenodo.org/)
* Simply download `Behavython-Setup-0.9.9rc11.exe`, run the setup wizard, and launch Behavython from your Desktop or Start Menu.

---

### Automated Installation (Windows)

For a streamlined setup, we provide a batch script that automates the entire process: creating the Conda environment, installing the required `pip` dependencies, and configuring the CUDA environment.

**How to use the installer:**

1.  **Download the script:** [**Download behavython_installer.bat**](https://github.com/mrdrzit/behavython/raw/main/installation_script/behavython_installer.bat)<br>
    *_Right-click the link and select **"Save Link As..."** to download it as a `.bat` file_*<br>
    *_In the windows explorer dowload prompt make sure to select "Save as type: All Files" and not "Text Documents" to avoid saving it as a `.txt` file_*
2.  **Run the Installer:** Double-click the downloaded file and follow the on-screen instructions.
3.  **Detailed Instructions:** For a full walkthrough of the automated process, refer to our [**Installation Guide**](https://github.com/mrdrzit/behavython/tree/main/installation_script).

### Step-by-Step Installation (Manual)

We recommend using mamba (or conda) to manage isolated Python environments. DeepLabCut 2.3.x (TensorFlow) and DeepLabCut 3.0+ (PyTorch) require distinct CUDA runtimes and package versions, so they should be installed into separate environments.

#### Option A: TensorFlow Environment (DLC < 3.0)
Use this environment for models trained on TensorFlow or created before DeepLabCut 3.0.

```bash
mamba create -n behavython-tf python=3.10
mamba activate behavython-tf
mamba install -c conda-forge cudatoolkit=11.2 cudnn=8.1.0
pip install "behavython[tf]"
```

#### Option B: PyTorch Environment (DLC 3.0+)
Use this environment for models trained on PyTorch with DeepLabCut 3.0+.

> **Note:** DeepLabCut 3.0+ is incompatible with networks trained in DeepLabCut 2.3.

```bash
mamba create -n behavython-torch python=3.10
mamba activate behavython-torch
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu126
pip install "behavython[torch]"
```

#### DeepLabCut Engine Detection & Backend Validation
Behavython checks backend availability before starting video analysis or assisted labeling:
- **Explicit setting:** Reads `config.yaml` for `engine: pytorch` (or `torch`) and `engine: tensorflow` (or `tf`).
- **Automatic detection:** When `engine` is omitted (standard for networks trained before DLC 3.0), Behavython inspects the model folder structure: `dlc-models-pytorch/` resolves to PyTorch, and `dlc-models/` resolves to TensorFlow.
- **Dependency checks:** If the required backend (`torch` or `tensorflow`/`tf_slim`) is missing from the active environment, Behavython halts early with `MissingBackendError` and names the missing packages.

### Launching Behavython

- **Standalone offline installer:** open Behavython from the Desktop or Start Menu shortcut.
- **Automated or manual installation:** activate the environment you installed Behavython into, then run `behavython`:

```bash
mamba activate behavython-torch   # or behavython-tf
behavython
```

The main window opens with two tabs: **DEEPLABCUT** (track the videos) and **ANALYSIS** (compute the metrics). For batch runs without the window, see [CLI Usage](#cli-usage).

-----

## Using the GUI

A typical session goes from raw videos to metrics in two steps: track the videos in the **DEEPLABCUT** tab, then analyze the tracking in the **ANALYSIS** tab. Keep each experiment in its own folder, with every video next to its tracking, image and ROI files.

### 1. Track the videos (DEEPLABCUT tab)

1. **Choose the network.** Check **Use default network (overhead view)** and pick `C57` or `CD1` to use one of our [pretrained models](#pretrained-models) (downloaded the first time you use it). To use your own network, click **GET FILE** and select its `config.yaml`. **SNAPSHOT** is optional: it picks a specific snapshot instead of the one set in `config.yaml` (right-click to reset).
2. **Choose the videos.** Click **GET FOLDER** and select the folder with the videos. To analyze a list of videos from different folders, use **ANALYZE FROM FILE** with a `.txt` file that has one video path per line.
3. **Click ANALYZE.** Behavython lists the videos, asks for confirmation, then runs DeepLabCut and filters the predictions. The tracking files (`<video>DLC..._filtered.csv` and `<video>DLC..._filtered_skeleton.csv`) are saved next to each video. Videos that are already tracked are skipped.
4. **Click GET FRAME.** This saves one frame from the middle of each video as `<video>.jpg`, next to the video. The analysis uses it as the background of the plots.
5. **Create the ROIs** (interaction tasks only). For Social Recognition, **CREATE ROIS** draws the cup ROI for each video (see [Automatic ROIs](#roi-configuration-interaction-tasks)). For the other interaction tasks, draw them in ImageJ as described in [ROI Configuration](#roi-configuration-interaction-tasks). For Open Field and EPM, prepare the arena `.json` described in [Arena Configuration](#arena-configuration-geometry-tasks).
6. **Optional: click CLEANUP FOLDER.** This moves files that the selected experiment type does not need into an `unwanted_files` subfolder, so they cannot be matched to the wrong animal. Nothing is deleted.

The **GENERATE PLOTS** button saves likelihood plots for the tracked videos, to check tracking quality before the analysis.

### 2. Compute the metrics (ANALYSIS tab)

1. **Set the parameters** in the SETTINGS panel: experiment type, experimental animal (mouse or rat), arena width and height in cm, frames per second, and task duration in seconds. Check **Trim Video Start** and set the seconds to skip if the first part of the video must be ignored (for example, while the animal is placed in the arena). **LOAD CONFIGURATION** fills the arena size, frame rate, duration and trim from a `.json` file, and **RESET** restores the defaults.
2. **Choose the outputs.** **Plot data?** saves the per-animal plots at the **Desired figure size**. **Generate validation video** also saves an annotated video for each animal (slow).
3. **Click ANALYZE.** Select all the files of all animals at once (tracking CSVs, `.jpg` frames, ROI CSVs and arena `.json` files; `Ctrl+A` in the folder works). Behavython groups them by video name.
4. **Select the output folder.** For Open Field and EPM, if any animal has no arena `.json` of its own, Behavython asks for one arena `.json` for those animals (see [Arena Configuration](#arena-configuration-geometry-tasks)). If you cancel, it lists those animals and asks whether to continue without them; they are then skipped and marked invalid in the log.
5. **Read the log.** Progress and per-animal warnings appear in the log box. Animals with missing or invalid files are skipped and listed there. The results are described in [Outputs & Metrics](#outputs--metrics).

**Files needed per animal:**

| Experiment | Files |
|---|---|
| Open Field, Elevated Plus Maze | `<video>DLC..._filtered.csv`, `<video>.jpg`, `<video>.json` (or one arena `.json` for the batch) |
| Social Recognition | `<video>DLC..._filtered.csv`, `<video>DLC..._filtered_skeleton.csv`, `<video>.jpg`, `<video>_roi.csv` |
| Social Discrimination | `<video>DLC..._filtered.csv`, `<video>DLC..._filtered_skeleton.csv`, `<video>.jpg`, `<video>_roiL.csv`, `<video>_roiR.csv` |

-----

## CLI Usage

Behavython ships a headless command-line entry point (`behavython-cli`) for batch processing without opening the GUI. This is useful for server-side automation or scripted pipelines.

**Basic usage:**
```bash
behavython-cli --config run.json
```

**With overrides:**
```bash
behavython-cli --config run.json --output /data/results --no-plots
```

**From raw videos to metrics** (Social Recognition with the CD1 network). Run the preparation and the analysis as two calls, because the files in the folder are listed once at the start of each call:
```bash
behavython-cli -f ./videos --extract-frames --create-rois --run-tracking --network cd1
behavython-cli -f ./videos --experiment-type social_recognition -o ./results
```

**Get the templates:** `behavython-cli --init -o ./my_run` copies `cli_config.example.json` and the arena config templates into `./my_run`. Add `--experiment-type open_field` to copy only the matching arena template.

### Analysis settings

Analysis runs when `--config` or `--experiment-type` is given. The config file holds the analysis settings. Flags override the matching config values:

| Flag | Overrides | Description |
|---|---|---|
| `--config`, `-c PATH` | | JSON config file with the fields below |
| `--input-folder`, `-f DIR [DIR ...]` | `input_folder` | One or more folders with the animal files |
| `--output`, `-o DIR` | `output_folder` | Output folder |
| `--experiment-type TYPE` | `experiment_type` | Experiment type (see the table below) |
| `--arena-config PATH` | `config_path` | Global arena JSON for animals without their own (Open Field, EPM) |
| `--no-plots` | `no_plots` | Skip plot generation |
| `--verbose`, `-v` | | Print debug messages |

Config template: `cli_config.example.json` (copy it with `--init`). Fields:

| Field | Description | Default |
|---|---|---|
| `experiment_type` | One of: `open_field`, `elevated_plus_maze`, `social_recognition`, `social_discrimination`, `object_discrimination` | — |
| `input_folder` | Folder containing all animal files (CSVs, images, ROI/JSON configs) | — |
| `input_files` | Explicit file list, for non-standard folder layouts. Ignored when `input_folder` is set | `[]` |
| `output_folder` | Destination directory for results | — |
| `config_path` | Global fallback arena JSON (maze experiments only) | `null` |
| `arena_width` / `arena_height` | Physical arena dimensions in cm | `30` |
| `frames_per_second` | Recording frame rate | `30` |
| `task_duration` | Analysis window in seconds | `300` |
| `trim_amount` | Seconds to skip at video start | `0` |
| `crop_video` | Restrict analysis to `[trim, trim + duration]` | `false` |
| `animal` | `mouse` or `rat` (sets body-length threshold) | `mouse` |
| `figure_resolution` | Max plot resolution: `640x480`, `1280x720`, `1920x1080`, `2560x1440` | `1920x1080` |
| `no_plots` | Skip plot generation | `false` |
| `generate_video` | Generate annotated output video | `false` |

### Actions

Action flags run on the videos in `--input-folder`. They can be combined with each other and with an analysis. They always run in the order below, and the analysis runs last. If an action fails, the run stops.

| Flag | What it does | Needs |
|---|---|---|
| `--transfer-labels` | Copies DLC labels into another project, dropping bodyparts the target does not have | `--dlc-config` (target project), `--label-folders DIR [DIR ...]` |
| `--standardize` | Converts videos to H.264 with a constant frame rate (see [Video Pre-processing](#video-pre-processing-experimental)) | |
| `--run-cropping` | Crops videos from a saved cropping project | `--crop-config PATH` |
| `--extract-frames` | Saves one frame per video as `<video>.jpg` (middle of the video, or `--frame-number N`) | |
| `--create-rois` | Creates `<video>_roi.csv` with the ROI network (see [Automatic ROIs](#roi-configuration-interaction-tasks)) | optional `--roi-config PATH` |
| `--cleanup` | Moves files not needed for the experiment type into `unwanted_files/` | `--experiment-type` or `experiment_type` in the config |
| `--run-tracking` | Runs DeepLabCut on the videos and filters the predictions | `--dlc-config PATH` or `--network c57\|cd1` |
| `--likelihood-plots` | Saves likelihood plots for the tracked videos | `--dlc-config` or `--network` |
| `--annotate-video` | Creates DeepLabCut annotated videos | `--dlc-config` or `--network` |

`--network` uses a downloaded [pretrained model](#pretrained-models). The CLI does not download it: install it by hand or open it once in the GUI. `--shuffle` and `--trainingsetindex` select the DeepLabCut shuffle and training set (inferred when omitted).

Return codes: `0` = all animals valid, `1` = fatal error, `2` = completed with warnings/invalid animals.

-----

## Pretrained Models

Pretrained DeepLabCut networks are published on the [GitHub Releases page](https://github.com/mrdrzit/behavython/releases/tag/models-v2.0). The GUI downloads them when an action needs one.

The latest release (`models-v2.0`) includes:

  * `c57_network_2025_minified.zip` - Pose tracking of C57BL/6 mice, top view, white arena (TensorFlow).
  * `cd1_network_2026.zip` - Pose tracking of CD1 mice, top view (PyTorch).
  * `roi_network_2026.zip` - Cup detection for automatic ROI creation in social recognition (PyTorch).

These networks are trained on the social recognition setups of our lab. On other setups, check the results, or train your own network.

To install by hand, extract each ZIP into a folder with the same name inside `.behavython/models/` in your home directory, so that `config.yaml` sits directly inside it:
- **Windows:** `C:\Users\<YourUsername>\.behavython\models\roi_network_2026\config.yaml`
- **Linux/Mac:** `~/.behavython/models/roi_network_2026/config.yaml`

-----

## Video Pre-processing (Experimental)

> ⚠️ **Note:** This is currently an **experimental feature** available only when running Behavython in debug mode. It can be toggled on demand, but please contact the developers for instructions on how to activate it for now.

Behavython includes a dedicated pipeline for standardizing and cropping raw behavioral videos, ensuring they are optimized for computer vision analysis (DeepLabCut, SLEAP, etc.).

### High-Performance Batch Cropping
- **Interactive Designer:** Draw crop regions and define rotation angles directly on video previews.
- **Hardware Acceleration:** Native support for **Nvidia NVENC**, enabling processing speeds of up to 800+ FPS.
- **Batch Processing:** Define settings once and process entire folders in the background.
- **Non-Destructive:** Original videos are preserved; results are saved in a `/cropped` subfolder.

### Video Standardization
Many acquisition systems save videos in legacy formats (like MPEG4 or AVI) that are not "reliably seekable." This can lead to desynced frames during tracking. Behavython's **Standardization Tool**:
1. **Automatic Detection:** Background probing detects problematic codecs or variable frame rates.
2. **Lossless Conversion:** Converts videos to a pristine H.264 format with Constant Frame Rate (CFR).
3. **Unlocks GPU Speed:** Standardizing moves the decoding workload from the CPU to the GPU, often increasing processing speed by 5x to 10x.

### Standard Workflow
1. **Select Folder:** Click `GET FOLDER` to choose the directory where your videos are stored (ideally, this folder should only contain the videos you intend to crop).
2. **Standardize (If Prompted):** If the interface detects legacy codecs, click the *Standardize Videos (Fix Codecs)* button to convert them safely.
3. **Open Cropping Window:** Click *Open Cropping Window* to launch the interactive editor.
4. **Draw Crops & Set Coordinates:** 
   - Drag with the **Left Mouse Button** across the frame to draw a crop box.
   - Use the **Mouse Wheel** to rotate the box (hold Ctrl/Shift to adjust rotation speed).
   - Once the crop is perfect, click **Set Coordinates** for that video.
   - *Note: If all your videos have different positions, you must select each video individually, draw the box, and click "Set Coordinates". If the position is identical across videos, simply use the **Apply to checked videos** button to propagate your settings.*
5. **Video List Color Code:** The sidebar list uses colors to track your progress:
   - 🟡 **Yellow:** Needs attention (Coordinates have not been set).
   - 🟢 **Green:** Ready (Coordinates are set and saved).
   - ⚪ **White:** Finished (The video has already been cropped in the `/cropped` folder).
6. **Save Project:** Click *Save Project (JSON)* to write your coordinates to disk.
7. **Execute:** Close the cropping window and click **CROP VIDEOS** in the main GUI to run the batch process.

-----

## Workflow & Configuration

### The Pipeline

```
Video → DeepLabCut → Filtered CSV → Behavython Core Pipeline → Metrics & Parquet
```

### Arena Configuration (Geometry Tasks)

For Open Field and Elevated Plus Maze (EPM) experiments, Behavython requires a `.json` configuration file defining the spatial geometry. You can extract these coordinates using the ImageJ Point Tool.

There are two ways to give it, and they can be mixed in one batch:

  * **Per animal:** name the file after the video (`video_name.json`, `video_name_maze.json` or `video_name_config.json`) and select it together with the other files of that animal. Use this when the arena position changes between videos.
  * **One for the batch:** if any animal has no `.json` of its own, Behavython asks for one file after you pick the output folder (`--arena-config` or `config_path` in the CLI). It is used only for the animals without their own file. Without it, those animals are skipped and the others still run.

An animal's own `.json` always wins over the batch file.

  * **Open Field:** Requires exactly 4 ordered corners (Top-Left, Top-Right, Bottom-Right, Bottom-Left).
  * **Elevated Plus Maze:** Requires exactly 12 ordered points defining the outer boundaries, arms, and center zone.

**Example: Open Field (`arena.json`)**
Use the image as reference to order the points correctly.
Here, you can copy this example and save as a .json file to use 
In order, the points should be created in imageJ in this sequence:
1. top-left 
2. top-right
3. bottom-right
4. bottom-left

```json
{
  "experiment_type": "open_field",
  "arena_corners": [
    [126.0, 72.0],
    [637.0, 74.0],
    [633.0, 581.0],
    [128.0, 581.0]
  ]
}
```

**Example: Elevated Plus Maze (`arena.json`)**
As with the open field, use the image as reference to order the points correctly.
Here, you can copy this example and save as a .json file to use 
In order, the points should be created in imageJ in this sequence:
1. Center Top Left 
2. Top Left
3. Top Right
4. Center Top Right
5. Right Top
6. Right Bottom
7. Center Bottom Right
8. Bottom Right
9. Bottom Left
10. Center Bottom Left
11. Left Bottom
12. Left Top

```json
{
  "experiment_type": "elevated_plus_maze",
  "maze_points": [
    [128, 336],
    [384, 336],
    [384, 32],
    [514, 32],
    [514, 336],
    [900, 336],
    [900, 446],
    [514, 446],
    [514, 1042],
    [384, 1042],
    [384, 446], 
    [128, 446]
  ]
}
```

*Note: Incorrect coordinate ordering will corrupt spatial occupancy metrics.*

<div align="center">
  <img src="https://raw.githubusercontent.com/mrdrzit/behavython/refs/heads/main/src/behavython/gui/assets/images/geometry_reference.png" width="400" alt="Geometry Point Ordering Reference"/>
  <br>
  <em>Coordinate ordering reference for Open Field and Elevated Plus Maze.</em>
</div>

### ROI Configuration (Interaction Tasks)

For interaction paradigms (like Social Recognition or Object Discrimination), Behavython requires Region of Interest (ROI) definitions exported as CSV files. You can generate these using the ImageJ Oval Tool.

**ROI Requirements:**

  * **ImageJ Measurements:** Go to *Analyze → Set Measurements*. You **must** ensure both **Centroid** and **Bounding Rectangle** are checked. The resulting CSV needs the bounding box (BX, BY, Width, Height) and centroid (X, Y) coordinates.
  * **File Naming Convention:** The exported CSV must contain the original video name, followed by an ROI identifier:
    * *Single-Object/Target:* `video_name_roi.csv`
    * *Two-Choice Tasks:* `video_name_roiL.csv` and `video_name_roiR.csv` (Left and Right).
  * **File Format:** The file must be a standard `.csv` (Comma Separated Values) file.

**Example: Social Recognition/Discrimination (`video_name_roi.csv`)**
```csv
 ,Area,X,Y,BX,BY,Width,Height
1,24065,376.500,387.500,289,300,175,175
```

**Automatic ROIs (Social Recognition):** The **CREATE ROIS** button in the DeepLabCut tab, or `behavython-cli -f <folder> --create-rois`, writes `video_name_roi.csv` for each video with `roi_network_2026`. The network finds the top, right, bottom and left points of the cup on 5 frames per video, skipping the first 10%. The median of each point gives the center (X, Y), Width (left-right) and Height (top-bottom). Existing ROI files are never overwritten. Check the images in the `roi_check` folder, draw the ROIs that are wrong by hand, and read the warnings in the log about frames or videos that disagree. The network is trained on our CD1 and C57 cups only. For other setups, right-click the button (or pass `--roi-config`) to use your own DLC network with the bodyparts `top`, `right`, `bottom` and `left`.

-----

## Outputs & Metrics

The pipeline outputs data in multiple formats for both statistical aggregation and granular programmatic review.

### General Storage

  * **`analysis_summary.xlsx` / `.csv`**: Scalar metrics aggregated per animal.
  * **`analysis_timeseries.parquet`**: Highly compressed, frame-by-frame data utilizing Apache Arrow for efficient downstream data science workflows.
  * **`analysis_log.json`**: Comprehensive error and warning logs per session.
  * **Session logs**: every GUI or CLI session also writes a full log to `.behavython/logs/` in your home directory (the last 20 are kept). Attach it when you report a bug.

### Task-Specific Metrics

**Geometry Experiments (Open Field, EPM):**

  * Zone occupancy times and percentages.
  * Transition counts between zones.
  * Discrete `spatial_state` arrays per frame.

**Interaction Experiments (Social/Object):**

  * Investigation and approach proportions.
  * Mean inter-bout intervals (seconds).
  * Discrete bout analysis (Collision bouts, approach-only bouts, abortive retreats). These counts, the proportions and the intervals above are computed on **approach sequences**: each approach is linked to a following collision and retreat within 1 s. A collision with no preceding approach is not counted in them.
  * **`bouts.xlsx`**: two long tables for manual analysis, one row per event, all animals stacked, with `animal_id` and `roi_name` columns and times in seconds. Also saved as `investigation_bouts.parquet` and `approach_sequences.parquet`.
      * `investigation_bouts` sheet: one row per contiguous run of collision frames (at least 3 frames) in one ROI, regardless of approach or retreat. Columns: `bout_id`, `start_s`, `end_s`, `duration_s`, `start_frame`, `end_frame`. Durations add up to the exploration time, except for runs under 3 frames.
      * `approach_sequences` sheet: one row per approach sequence, with its `outcome` (`collision`, `abortive_retreat` or `approach_only`) and the start and end of each stage (approach, collision, retreat). Stages that did not happen are empty.
  * `analysis_collisions.parquet`: Granular export containing distance to objects, interaction angles, and frame-by-frame flags.

-----

## Contributing

Contributions to the codebase and scientific pipelines are welcome.

  * Open an issue to report bugs or suggest features.
  * Submit a pull request for code changes. Ensure modifications align with the project's modular architecture and strict type-hinting standards.

-----

## Citation

If you use Behavython in your research, please cite:

```bibtex
@software{passos_moreira_behavython_2026,
  author       = {Passos, Matheus Costa and Carvalho Moreira, João Pedro},
  title        = {Behavython: Automated behavioral analysis software and pipeline for neuroscience},
  year         = {2026},
  publisher    = {Zenodo},
  version      = {0.9.9rc13},
  url          = {https://github.com/mrdrzit/behavython}
}
```

Metadata is also available in [CITATION.cff](CITATION.cff).

-----

## License

This project is distributed under the GNU GPL v3.0 License. See the `LICENSE` file for more information.

-----

## Contact

  * **Matheus Costa** — [matheuscosta3004@gmail.com](mailto:matheuscosta3004@gmail.com)
  * **João Pedro** — [mcjpedro@gmail.com](mailto:mcjpedro@gmail.com)

-----

## Acknowledgments

  * Flávio Mourão — [https://github.com/fgmourao](https://github.com/fgmourao)
  * Núcleo de Neurociências (NNC) — [http://www.nnc.ufmg.br](http://www.nnc.ufmg.br)

<br>
<p align="left">
  <strong>Developed at</strong><br>
  Núcleo de Neurociências (NNC)<br>
  Universidade Federal de Minas Gerais (UFMG)<br>
  Brazil
</p>
