Pixel-Based Density Approximation: Hopalong Attractor (Python)

Despite its common name, Hopalong is not an attractor.
The map preserves area (Jacobian determinant 1), so nothing contracts onto an attracting set; the familiar picture is
the footprint of a single orbit from (0, 0), and other starting points can give different pictures.
For the regular and chaotic regions behind this, see Hopalong Phase Space.
Abstract
Historical Context
The Hopalong* attractor, authored by Barry Martin of Aston University in Birmingham, England [2],
was popularized by A.K. Dewdney in the September 1986 issue of Scientific American. In Germany, the Hopalong attractor gained further popularity through an algorithm called HÜPFER in the article Psychotapeten published in Spektrum der Wissenschaft. [3].
*Nicknamed by A.K. Dewdney.
The Hopalong Attractor Functions
The mathematical definition of the Hopalong attractor is given by the following system of recursive functions, defined in [2]:
$$
\large
\begin{cases}
x_{n+1} = y_n - \text{sgn}(x_n) \sqrt{\lvert b x_n - c \rvert} \
y_{n+1} = a - x_n
\end{cases}
\large
$$
Where:
- The sequence starts from the initial point (x0 , y0) = (0 , 0).
- xn and yn represent the coordinates at the n-th iteration of the attractor.
- a, b, and c are parameters influencing the attractor's dynamics.
- sgn is the signum function. However, the programs use
math.copysign() , which is defined as follows:
$$
\text{copysign}(1.0,x) =
\begin{cases}
1.0 & \text{if } & \text{x } & \text{is} &\text{positive}, & \text{0.0} & or &\text{infinity} \
-1.0 & \text{if } & \text{x } & \text{is} &\text{negative}, & \text{-0.0} & or &\text{negative infinity}
\end{cases}
$$
Computational Approach
The available Python programs calculate and visualize the attractor by iterating the described function system.
Goal:
Visual Representation:
The attractor is rendered as a density heatmap, with color intensity reflecting areas of high or low point concentration.
Efficiency:
Large numbers of iterations are computed with low memory usage and high processing speed.
Core Algorithm:
The algorithm consists of two main passes:
First Pass: Determines the spatial extent of the attractor trajectory.
Second Pass: Maps the sequentially generated trajectory points in continuous space directly to a discrete pixel grid, keeping track of the number of pixel hits used to generate the density heatmap matrix.
For a more in-depth look, consult Pixel-Based Density Approximation
Just-in-time (JIT) compilation is applied and supported by a low-complexity code structure.
For details regarding two-pass strategy, see Two-Pass Approach
Back to Table of Contents
Requirements
To run the programs, the following Python libraries or modules must be installed / imported:
- matplotlib *
- numpy *
- numba *
- math *
(* mandatory)
Optional (for performance tracking):
Import the time and resource libraries if you want to track process time and system memory usage.
Otherwise, please comment out the corresponding code fragments in the import section, the corresponding function and in the main function.
...
#import time
#import resource
...
"""
def calculate_and_display_resource_usage(start_time, end_time):
# Calculate the CPU user and system time
cpu_sys_time_used = end_time - start_time
# Calculate the memory resources used
memMb = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024.0 / 1024.0
print(f'CPU User&System time: {cpu_sys_time_used:.2f} seconds')
print(f'Memory (RAM): {memMb:.2f} MByte used')
"""
...
# Start the time measurement
#start_time = time.process_time()
...
# End the time measurement
#end_time = time.process_time()
#calculate_and_display_resource_usage(start_time, end_time)
...
Back to Table of Contents
Usage
Input
When you run the programs, you will be prompted to enter the following parameters, which determine the behavior of the Hopalong Attractor:
- a (float or integer): The first parameter affecting the attractor's dynamics.
- b (float or integer): The second parameter affecting the attractor's dynamics.
- c (float or integer): The third parameter affecting the attractor's dynamics.
- n (integer): The number of iterations to run (e.g. 1e6, 1_000_000 or 1000000).
Example Parameters:
- a = -2
- b = -0.33
- c = 0.01
- n = 2e8
Experimenting with different values of these parameters will yield diverse and intricate visual patterns.
Output
The programs generate a visual representation of the attractor trajectory as a density heatmap, where color intensity reflects the frequency of points visited (hit counts). Lighter areas indicate regions of higher density, highlighting the attractor's intricate structure. The generated density heatmap matrix also supports a 3D representation by mapping normalized density values along the Z-axis.
Basic Version 2D

Basic Version 3D ax.contourf3D

Basic Version 3D ax.contour3D

Extended Version

Back to Table of Contents
Features, Functionality, and Special Scenarios
Program Variants
Basic: Calculates and displays the Hopalong attractor as a 2D density heatmap with an integrated color bar.
Basic 2D/3D: Adds the ability to visualize the attractor in 3D by mapping normalized density values along the Z-axis. Users can select the visualization mode at runtime.
Extended: Incorporates all features of the Basic version (except the color bar) and includes additional statistics as well as a visualization of the pixel hit count distribution.
Examples of outputs can be found in the "Usage" section above.
Back to Table of Contents
Pixel-Based Density Approximation
Continuous to Discrete Mapping
Trajectory points, represented as floating-point coordinates in a two-dimensional continuous space, are scaled and mapped to integer pixel coordinates for visualization. Scaling factors derived from the trajectory's extents and the image dimensions ensure the continuous coordinates fit within the pixel grid while preserving spatial relationships.
Integer Conversion by Rounding to Nearest Integer
Integer conversion during continuous-to-discrete mapping introduces quantization, where closely spaced trajectory points may map to the same pixel due to the quantization of coordinates. Together with the preceding steps, this forms the discretization process, aggregating local density within the pixel grid. However, the grouping effect may reduce fine details.
Tracking of Density Aggregation
An image array, initialized with zeros, serves as a blank canvas for recording density. Each trajectory point, after being mapped to a pixel, increments the value at the corresponding array index. The resulting array is referred to as the Density Heatmap Matrix. Pixel hit counts encode the spatial distribution of trajectory point densities in continuous space. Higher hit counts indicate greater density.
Note: The total sum of pixel hit counts equals the number of trajectory iterations, as each iteration contributes one pixel, which may be hit multiple times, to the density heatmap matrix.
For mathematical definition, see:Mathematical Appendix:
Comparison of Pixel-Based Density Approximation vs. Histogram-Based Density Estimation
Pixel-Based Approximation
This generative method creates a density heatmap matrix by mapping trajectory points directly to discrete pixels. Each pixel corresponds to a specific region in continuous space, with emergent density patterns arising from the interaction between the attractor's dynamics and the discretization process.
Histogram-Based Estimation
Using np.histogram2d(..., density=True), this analytic method divides the continuous space into a grid of equal-area bins and counts the number of trajectory points that fall into each bin. The counts are then normalized by the total number of points and the bin area, resulting in a density matrix representing relative point distributions across the entire space for quantitative analysis. The density patterns, similar to the pixel-based approach, arise from the interplay between the attractor's dynamics and the bin grid configuration.
Impact of bin size:
Smaller bins (higher bin count) improve density precision but reduce density contrast by spreading density over more bins.
Larger bins (lower bin count) increase density contrast by concentrating normalized density values in fewer, larger bins but reduce precision.
Note: Kernel Density Estimation (KDE) may provide more accurate density estimates, especially in scenarios such as the Hopalong attractor where dense and sparse regions coexist, as it smoothes and adjusts for such variations. However, due to the high computational cost, it was unsuitable for this study. Similarly, smoothing the density heatmap matrix using scipy.ndimage.gaussian_filter, which resembles a KDE-like effect, was avoided as it changes the number of pixel hits despite improving visualization.
Visualization of Aggregated Density Distribution