Skip to main content

Local similarity comparison for feature extraction – biologically inspired, zero‑training edge/pattern detection, multi-backend acceleration.

Project description

Cos Comparison

PyPI version Python 3.8+ License: MIT

An AGI-oriented project based on local similarity comparison for feature extraction – biologically inspired, zero-training edge / pattern detection.


Core Idea

Information is produced by local comparison in raw data.
This module implements the centre-surround antagonism mechanism from neuroscience, extracting edges, textures, and keypoints using only sliding-window similarity.

The core formula (cosine-modulated similarity, recommended default):

$$ \text{cosmod} = \frac{2(A \cdot B)}{|A|^2 + |B|^2} $$

  • A step toward biologically plausible AGI
  • No training, no labels, no backpropagation
  • Works on 1D, 2D, 3D, 4D data (audio, images, video, volumetric data)
  • Supports passive (reflexive boundary detection) and active (template matching) modes
  • Pure Python core with optional C extension acceleration

Core Principles

  1. Information emerges from local comparison – edges, textures, and patterns arise by comparing neighboring regions.
  2. Centre-surround antagonism – two sliding windows are compared with a fixed displacement vector d, mimicking the response of retinal ganglion cells.
  3. Three complementary similarity measures_cos (angular similarity), _mod (magnitude similarity), _cosmod (recommended balanced combination).
  4. Dual operational modespassive (boundary detection without templates) and active (template matching with a user-supplied kernel).
  5. Multi-scale and multi-directionality – vary window size for scale selection, change d for orientation selectivity (vertical, horizontal, diagonal).
  6. Dimension-agnostic – the same algorithm runs natively on 1D, 2D, 3D, 4D, and higher-dimensional data.
  7. Zero training, zero labels – fully deterministic, ready to use out of the box.
  8. Full determinism and interpretability – every output has a clear geometric meaning.
  9. Modular, pluggable architecture – pure Python reference implementation with optional high-performance C extension and automatic fallback.

Design Principles

The library adheres to two key design principles:

  • Zero internal dependencies – the core is self-contained and does not rely on any third-party modules. It runs everywhere Python runs.
  • Open integration – a generic hook/interface mechanism is provided, allowing users to seamlessly plug in any external module that conforms to the specified protocols (e.g., GPU/NPU accelerators, custom tensor types, or specialized hardware backends). This keeps the core lightweight while enabling unlimited extensibility.

🚀 What's New in Version 0.3.1

Version 0.3.1 brings major architectural improvements, performance optimizations, and expanded documentation.

Highlights

  • Multi-Backend Architecture – two backends with automatic fallback:
    • Python C Extension (cos_comparison_pydll) – maximum performance, tight Python integration, GIL release support.
    • Pure Python (cos_comparison) – zero-dependency reference implementation, guaranteed to work everywhere.
  • Preallocated Output Supportoutput, output_start, output_step parameters for memory-efficient batch processing.
  • Callback Systemstart_callback, end_callback, global_error_callback, local_error_callback, return_callback for extensibility.
  • Custom Typesvector_map_as_tensor, func_name_space, default_contain for advanced use cases.
  • Duck Typing Protocol__cos_comparison_passive__ / __cos_comparison_active__ for custom data types (including native NumPy array and PyTorch tensor support).
  • Dimension Aliases*_1d, *_2d, *_3d, *_4d convenience functions for all core operations.
  • Seven-Layer Cognitive Architecture – brain-inspired layered design from low-level computation to high-level cognition.
  • Complete English Documentation – professional, academic-grade documentation covering principles, architecture, and full API reference.

Backend Performance Comparison

Backend Relative Speed Memory Usage Status
Python C Extension 100–200× ~5–8 MB (estimated) 🟡 Beta
Pure Python ~22 MB ✅ Stable

Note: Memory measurements are based on a 424×322×3 test image with a 3×3 window. C-extension memory is estimated because tracemalloc cannot track C-level allocations. The ctypes backend has been deprecated in this release due to stability issues; users requiring maximum performance should use the native C extension.

⚠️ Breaking Changes

1. NumPy backend removed
Introducing a dedicated NumPy backend added unnecessary complexity and potential supply-chain risk. The core now natively supports NumPy arrays (and any type implementing __index__ and __len__, such as PyTorch tensors) via the duck-typing protocol, without requiring a separate backend.

2. Spelling errors corrected
All historical misspellings (e.g., genrategenerate) have been fixed throughout the codebase and documentation.


⚠️ Migration Guide from 0.2.x

Starting from version 0.2.0, the package has been restructured.
All core functions now reside in the core submodule.

Correct import statement:

from cos_comparison import core

Legacy code using import cos_comparison as cc will not work with 0.3.0. Please update your imports accordingly.


Installation

pip install cos-comparison

To install with optional test dependencies:

pip install cos-comparison[test]

Quick Start

1D – detect discontinuities (passive mode)

from cos_comparison import core

data = [1.0, 2.0, 3.0, 4.0, 5.0]
result = core.cos_comparison_passive_1d(
    data,
    window_size=(2,),
    step=(1,),
    d=(1,)
)
print(result)

2D – edge detection (passive mode)

from cos_comparison import core

image = [
    [1, 1, 0, 0],
    [1, 1, 0, 0],
    [0, 0, 1, 1],
    [0, 0, 1, 1]
]
edges = core.cos_comparison_passive_2d(
    image,
    window_size=(2, 2),
    step=(1, 1),
    d=(1, 0)
)
print(edges)

Active mode – template matching

from cos_comparison import core

data = [1.0, 2.0, 3.0, 4.0, 5.0]
kernel = [1.0, 0.0]
result = core.cos_comparison_active_1d(
    data,
    kernel=kernel,
    step=(1,)
)
print(result)

Whole-tensor cosine similarity

from cos_comparison import core

a = [1, 2, 3]
b = [2, 3, 4]
sim = core.cos_1d(a, b)
print(sim)

Using the recommended _cosmod similarity measure

from cos_comparison import core

result = core.cos_comparison_passive_1d(
    data,
    window_size=(2,),
    step=(1,),
    d=(1,),
    algorithm=core._cosmod
)

Multi-Backend System

The package provides a sophisticated multi-backend manager that automatically selects the fastest available backend while maintaining a unified API.

Default Backend Priority

Priority Backend Implementation Performance Status
1 cos_comparison_pydll Python C Extension 100–200× 🟡 Beta
2 cos_comparison Pure Python ✅ Stable

Key Features

  • Automatic fallback – if a higher-priority backend is unavailable, the system automatically falls back to the next option.
  • Runtime switching – manually switch backends at any time during execution.
  • Unified API – all backends expose exactly the same interface.
  • Configuration flexibility – control backend priority via a config file or environment variable.
  • Zero-dependency guarantee – the pure Python backend always works, no compilation required.

Switching Backends

from cos_comparison import core

# Check current backend configuration
backends = core.get_mode()
print(backends)

# Force pure Python mode (useful for debugging)
core.set_mode("cos_comparison")

# Multiple backends (tried in specified order)
core.set_mode(["cos_comparison_pydll", "cos_comparison"])

Environment Variable

# Unix
export COS_BACKEND=cos_comparison_pydll,cos_comparison

# Windows
set COS_BACKEND=cos_comparison_pydll,cos_comparison

API Overview

Passive mode (self-similarity / edge detection)

  • cos_comparison_passive_1d / _2d / _3d / _4d + generic N-dimensional cos_comparison_passive

Active mode (template matching)

  • cos_comparison_active_1d / _2d / _3d / _4d + generic N-dimensional cos_comparison_active

Whole-tensor similarity measures

  • cos_1d / _2d / _3d / _4d (cosine similarity)
  • mod_1d / _2d / _3d / _4d (magnitude similarity)
  • cosmod_1d / _2d / _3d / _4d (cosine-modulated similarity, recommended)

Local statistics (sliding window)

  • mean_local_1d / _2d / _3d / _4d
  • local_variance_1d / _2d / _3d / _4d

Generic helpers

  • cos(A, B, algorithm=core._cos) – works on arbitrarily nested lists and array-like objects.
  • execute_many(func, arg_iter, kwarg_iter) – batch execution (returns a list).
  • execute_many_iter(func, arg_iter, kwarg_iter) – batch execution (lazy generator).

Performance & Memory Benchmarks

Benchmark results for the two backends (pure Python and Python C extension) using a 322×424×3 RGB test image.
All tests were run with the same parameter grid: 3 window sizes, 3 offsets, and 3 similarity algorithms (27 combinations total).
Test environment: Windows 11 x64, 18-thread CPU, Python 3.14.6, JIT enabled.

Note: Memory figures for the C extension are estimated because tracemalloc cannot track C-level allocations. Figures are derived from process-level working set measurements.


⏱️ Execution Time (27-run average)

Backend 3×3 window (s) 5×5 window (s) 7×7 window (s) Total (27 runs) Speedup vs Python
Pure Python 7.31 18.80 28.00 486.8 s
Python C Extension 0.088 0.213 0.407 6.35 s ~77×
  • Algorithm choice (cos / mod / cosmod) has negligible impact (<5%) on execution time.
  • Window size is the dominant factor – larger windows increase execution time proportionally.
  • The C extension provides approximately 77× speedup over pure Python for typical workloads.

🧠 Memory Usage (peak working set)

Backend Average peak memory Notes
Pure Python ~21.5 MB Stable across all parameter combinations
Python C Extension ~5–8 MB (estimated) C-allocated memory not fully captured by Python tracers
  • Memory usage is largely independent of window size, offset, or algorithm choice.
  • The pure Python backend uses a fixed ~21–22 MB for the standard test image.
  • The C extension is extremely memory-efficient, allocating only the minimal required output tensor.

✅ Output Consistency

Both backends produce numerically identical output values (within floating-point precision) for every parameter combination – verifying that the core algorithm is correctly implemented across all backends.


📊 Full Raw Data

Complete CSV results (time and memory for all 27 combinations) are available in the tests/ directory:

  • test_python.txt, test_pydll.txt – performance timing data
  • memory_python.txt, memory_pydll.txt – memory usage data
  • out_*.txt – execution logs with saved heatmap output paths

🧪 How to Reproduce

# Performance test (all available backends)
python tests/test_performance.py --image tests/testdata/image_20260408.png --repeat 3 --output results.csv

# Memory test
python tests/test_memory.py --image tests/testdata/image_20260408.png --output memory.csv

Benchmarks run on a standard x86-64 CPU. Your results may vary depending on hardware, compiler optimizations, and operating system.


Author

I was born on May 31, 2008, and I feel fortunate to grow up in an era of rapid progress in artificial intelligence.

I have run extensive tests and observed many surprising emergent properties in the outputs. Earlier versions of this project contained numerous issues, as examination-oriented education left me limited time for thorough testing. I now have the opportunity to properly test, refine, and polish this work.

There remains a long road ahead to achieve true general artificial intelligence. I may be forced to set aside this research due to personal circumstances, but I do not want these ideas to fade away unnoticed. The purpose of open-sourcing this project is to share my thoughts, in the hope that others may build upon them and continue this line of inquiry.


Next Steps

  1. Introduce a formal extension interface in the core, allowing users to plug in GPU, NPU, or other custom accelerators.
  2. Complete the remaining cognitive submodules, working toward a simple but functional embodied AI agent.

License

MIT © 2026 Li Jinxin. See LICENSE for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cos_comparison-0.3.1.tar.gz (5.0 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cos_comparison-0.3.1-cp314-cp314-win_amd64.whl (75.6 kB view details)

Uploaded CPython 3.14Windows x86-64

File details

Details for the file cos_comparison-0.3.1.tar.gz.

File metadata

  • Download URL: cos_comparison-0.3.1.tar.gz
  • Upload date:
  • Size: 5.0 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.6

File hashes

Hashes for cos_comparison-0.3.1.tar.gz
Algorithm Hash digest
SHA256 6775925972d2a8e71b2dcdd3ef6d2c1b5e461aec731827f4d635f67da27f3d10
MD5 e9119405936fc1bf04006eb1c4d16d51
BLAKE2b-256 df39a3396f302a95445890c867b829b772d56994bfe7bf0cc2bf8325a73510e5

See more details on using hashes here.

File details

Details for the file cos_comparison-0.3.1-cp314-cp314-win_amd64.whl.

File metadata

File hashes

Hashes for cos_comparison-0.3.1-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 0985a3af2c3ebb21fa26a564f77cd33cc13cbabbf0c8ae0d47c940cabd5a686c
MD5 1931938f3f635de3caf578e2a89054a4
BLAKE2b-256 53548efbfc5b0c1d933eb4d14942f6b56fdc2a4a715b6c78235efd3f60571447

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page