---
title: "Box counting in Cython"
url: "https://edoardo.anteprime.edoardogabrielli.com/en/projects/box-counting-cython"
lang: "en"
updated: "2026-11-01"
---

# Box counting in Cython

> cyboxcounting: a Cython extension that estimates the fractal dimension of a point set with box counting, using a tree.

A Cython extension that estimates the fractal dimension of a point set by counting occupied cells, without building the whole grid. I wrote it on my own in one month, between November and December 2022.

## The problem

To measure the dimension of an attractor with box counting you count how many cells of side ε contain at least one point. With many points or many dimensions the full grid takes too much memory. I used a tree that branches only where there are points.

![Tree built on the Hénon map at four levels](https://edoardo.anteprime.edoardogabrielli.com/media/originals/2026/11/ab6cd4c5705f4c3fa5f8adf3dd8c7a18/cyboxcounting-albero.webp)

## How it works

### 1. The tree

A recursive N-ary tree written in C inside Cython: each level halves the cell side and only occupied branches are created. The tree memory is freed by hand with free().

### 2. The fit

occupation counts the cells at each level; fit_show does the linear fit with SciPy and shows the plots.

### 3. Tests

On the Hénon and Lorenz attractors, with figures saved in the repository.

![Cell counts and estimated dimension for the Lorenz attractor](https://edoardo.anteprime.edoardogabrielli.com/media/originals/2026/11/c0dcd49395d34287ba1d3e525320475f/cyboxcounting-lorenz.webp)

Lorenz attractor. On the right, the estimated dimension depends on the scale (from 2.3 to 1.8): the choice of the fit range matters.

### What I did

All the code, 19 commits, about 530 lines of Cython and Python.

### Limits

One-line README, no documentation, test scripts run by hand. I did not measure how much faster it is than a grid, so I claim nothing.

**Stack:** Python, Cython, C, NumPy, SciPy, Matplotlib.

[Code on GitHub](https://github.com/dodogabrie/cyboxcounting)

[← All projects](https://edoardo.anteprime.edoardogabrielli.com/en/projects)