cos-comparison
Formal release v1.0.0 — Production/Stable. A zero-dependency, biologically inspired local-comparison engine: information is produced by comparing neighbouring regions, with a C accelerator and a mandatory pure-Python fallback.
- Version:
1.0.0(Development Status :: 5 - Production/Stable) · License: MIT - Runtime dependencies: none — the standard library only · Python:
>= 3.8(GIL and free-threaded builds) - Backends:
c(compiled, selected when available) andpy(pure Python, always available)
1. Core principle
Information arises from local comparison of neighbouring regions, not from model fitting. A meaningful structure — an edge, a texture, a boundary, a pattern — is the place where two nearby windows differ. The engine compares local windows with a similarity measure that has a direct geometric meaning, so every output is deterministic and interpretable.
The primitive is the centre-surround antagonism of biological vision: a centre window and a surround window are compared at a fixed relative displacement, reproducing the receptive-field organisation of retinal ganglion cells and the direction selectivity of primary visual cortex. No gradients are computed, no parameters are optimised, and no priors are learned. Reference labels are optional metadata for recognition and never fit the operator.
2. Three similarity measures
For two equal-length vectors a and b, with dot = a·b and squared
norms ‖a‖² = Σx², ‖b‖² = Σy², three scalar kernels share one
universal form f(Σx², Σy², Σxy) and isolate different geometric
information.
| Measure | Formula | Sensitivity |
|---|---|---|
cos |
dot / (‖a‖·‖b‖) |
direction / orientation (shape and texture); invariant to scale |
mod |
2·‖a‖·‖b‖ / (‖a‖² + ‖b‖²) |
magnitude / amplitude (norm balance); invariant to angle |
cosmod |
2·dot / (‖a‖² + ‖b‖²) |
combined direction and magnitude (the default algorithm) |
- All three are bounded in
[0, 1]for the scalar kernels and equal1for identical windows.cosignores amplitude and answers whether two windows point the same way;modignores angle and answers whether their magnitudes match.cosmodcouples the two and needs no square root, so it is the numerically efficient default. cosmodis a normalised Euclidean similarity:1 − cosmod = ‖a − b‖² / (‖a‖² + ‖b‖²). The score is a monotone function of the squared Euclidean distance under a shared normaliser, which is why it behaves as a genuine non-degenerate metric comparison rather than a loose correlation.- At the origin (zero norm) the degenerate rule applies: equal zero
windows score
1, otherwise0.
The whole-tensor cos(a, b) entry point uses the directional cos
kernel; the passive and active operators default to cosmod. Any kernel
is supplied as a callable, so the algorithm is selectable per call.
3. Dual working modes
The two modes are distinct primitives with distinct data types and are never averaged together.
3.1 Passive mode — within-data boundary detection
cos_comparison_passive compares the data against itself shifted by a
displacement vector d. Each scalar window is scored against its
shifted neighbour with the cosmod kernel: a uniform region keeps a
score near 1, while a boundary — including a zero crossing — lowers the
score. No external template and no training are involved.
- The displacement
dselects the orientation of the detected boundary (horizontal, vertical, or diagonal); the window size sets the scale. - The shifted axis loses one element. An
h × wmap with a scalar window andd-shift yields an(h − 1) × wpassive map; a 1-D signal withwindow_size=(1,),d=(1,)yields lengthn − 1. - A region that cannot form a valid
d-shift is rejected withValueErrorrather than returning an undefined result.
3.2 Active mode — kernel template matching
cos_comparison_active slides a caller-supplied kernel over the data
and compares it against every local window, producing a response field
analogous to a matched filter. The kernel is a keyword argument
(kernel=...), and its scale is the object's own arrangement scale.
3.3 Choosing a mode
Use passive mode for unsupervised edge, boundary, and discontinuity detection inside one signal. Use active mode for locating a known reference pattern and for recognition. When both channels are combined, the decision takes the maximum of the two (not a weighted sum), so a weak channel cannot dilute a strong one.
4. Module architecture
The principle above is carried by a brain-inspired stack of independent
modules. Each module has one responsibility and communicates through
attach-and-take containers rather than shared mutable globals. The table
lists the modules in data-flow order; the directories sit directly under
cos_comparison/.
| Module | Role and key primitives |
|---|---|
core |
The engine. Three scalar kernels, the passive/active entry points, sliding-window pool, local statistics, the element-wise and threshold families, and backend selection. C99 sources under core/include/. |
data |
Tensor containers (base_tensor, parallel_tensor): accept nested lists, array.array, and buffers, and provide stride-and-offset zero-copy views and a PEP 688 buffer. |
sense_layer |
Receptors and the recognition path: region reads, active_peak, template_scores, template_recognize, data_match, elementwise_extract. |
memory_layer |
Structural carriers — base, inner, database, and I/O memory — that hold mappings without a learned model. |
brain_layer |
Symbolic and probabilistic logic (logic/), reflexes (reflex/: trigger, monitor, feedback), and the hierarchical mapper (mapper/base_map.py). |
action_layer |
Executers that drive operations. |
generate_layer |
Reverse-composition generation from the mapping graph; it composes new content rather than retrieving or copying stored samples. |
interface |
APIs (api/: async, call, parallel, I/O, database, communicate, system, time) and tools (tools/: iter, op, func, context, random, and math_tool for topology, Fourier, linear algebra, unit maps). |
extension_layer |
Plugin hosting and batch aggregation. |
shell_tool |
Unified shell, batch, and instruction surface. |
app |
Docker manager and protocol surface. |
test_tool |
The built-in debugger. |
The modules implement continuous-map hierarchical isolation: mappings between levels form a transformation group. Forward maps coarsen local detail into global structure; reverse maps guide global structure back into local composition. Each level applies a different primitive and preserves the mapping graph rather than collapsing it to a scalar. The generation engine records these mappings and reverse-guides compositional generation of new content; it does not retrieve or copy stored samples.
5. Recognition by continuous active alignment
The sense_layer formalises the perception path on top of the active
operator. Every kernel is compared as a continuous, arrangement-preserving
local match — the field is read backend-agnostically through core.get_item,
with no quantization into a symbol bag, no voting, and no training.
| Primitive | Behaviour |
|---|---|
active_peak(data, kernel) |
Slides the kernel through the core active comparison and reduces the response field to its peak: the translation-tolerant continuous alignment. |
template_scores(data, templates) |
Keeps the per-template peak of a gallery as a list of continuous scores. |
template_recognize(data, templates, labels=None) |
Returns the deterministic best (winner, score); ties resolve to the earliest entry. An empty gallery or a label-length mismatch raises ValueError. |
data_match(data, template, ...) |
Yields response-field positions whose match lies in an optional interval. |
Preserving the N-D arrangement is the decisive axis for recognition, and
the kernel window must cover the object's own scale. These claims are
evidenced by controlled experiments (see
docs/exploration/recognition_active_alignment.md):
on MNIST, template_recognize reaches 88.7% with 2,000 local
templates (20×20 kernels) and 91.1% with 5,000, approaching the
93.4% raw-pixel 1-NN ceiling, while position-invariant symbol-bag
variants collapse to the ~10% class prior.
6. Multi-backend system
The engine exposes one identical API across two backends; switching does not change user code or results.
| Backend | Call name | Module | Character |
|---|---|---|---|
| C extension | c |
cos_comparison_pydll |
Compiled acceleration; selected first when it loads |
| Pure Python | py |
cos_comparison |
Reference implementation; always available |
from cos_comparison import core
core.get_available_backends() # ('c', 'py')
core.get_active_backend() # the backend currently loaded
core.set_mode('py') # force a backend, or set_mode(['c', 'py'])
The C extension is built at install time and is never a hard requirement:
if it cannot be built, the loader falls back to pure Python (a one-time
RuntimeWarning, silenced with COS_COMPARISON_SILENT_FALLBACK=1), and
COS_COMPARISON_REQUIRE_C=1 turns a missing C backend into a hard error.
Both backends produce matching results; the C units are strict C99, use
the limited C API, hold no process-global mutable state, and are
free-thread safe.
7. Design properties
- Dimension-generic: one set of call names covers 1-D through 4-D data (time series and audio, images, volumes and video), with no per-dimension variant names.
- Duck-typed: nested lists, tuples,
array.array,memoryview, mapping and sequence protocols, and NumPy-style buffers are accepted structurally; no ABC registration is required. - Absolute locality: a global object is only locality-equal to itself; unknown or ambiguous cases are reported rather than guessed (three-valued honesty).
- No recursion, distributed: every walk is a carry-based odometer,
and the local processing is concurrency-friendly. External CPU/GPU
engines drive the core through the
iterateslot without modifying the package.
8. Installation
pip install cos-comparison
The C extension is built automatically when a compiler is available; with no compiler the pure-Python backend installs and runs unchanged. There are no third-party runtime dependencies.
From a source checkout, an in-place build compiles the C units:
python setup.py build_ext --inplace
See docs/build.md for compiler, free-threaded, and ABI details.
9. Quick start
from cos_comparison.core import (
cos_comparison_passive, cos_comparison_active, cos, create_void_list)
# Passive boundary detection on a 2-D image (horizontal edges)
edges = cos_comparison_passive(
image, window_size=(3, 3), step=(1, 1), d=(1, 0))
# Active template matching with a pre-allocated output
output = create_void_list((out_h, out_w))
cos_comparison_active(image, kernel=template, step=(1, 1), output=output)
# Whole-tensor directional similarity
score = cos(a, b)
10. Testing
The suite runs against the installed package from a directory outside the source tree, using the standard library and the package itself (the optional NumPy test self-skips).
python -m pytest tests -q
Current full-suite result on CPython with the C backend active: 1,001 passed, 26 skipped, 8 subtests passed across 41 test modules. The standard-library runner reports the same coverage as 1,027 tests, 26 skipped; the two runners enumerate subtests differently.
python -m unittest discover -s tests
11. Performance
The C backend accelerates the bulk paths that dominate real workloads. On
the reference machine, passive 2-D comparison runs roughly 80–150×
faster than pure Python across 64²–2048², local statistics reach
195–254×, and sliding-window pool runs about 9–13× (the
per-window Python callback bounds the latter). Callback-bound
element-wise paths narrow to roughly 2–3× or parity, and single-element
access is the one place the C extension loses to pure Python, so bulk
paths are the intended use. External GPU engines plugged through the
iterate slot reach 130–560× the single-thread C fast path end-to-end.
Full figures, the environment, methodology, and memory/import audits are in docs/performance.md.
12. Documentation
| Start with | Document |
|---|---|
| Setup and first run | Getting Started |
| Building the C backends | Build |
| Command-line protocol | Command Line |
| Core and mode APIs | Core · Passive · Active |
| Architecture and theory | Architecture · Principles |
| Experiments and findings | Exploration |
The complete documentation index is docs/README.md.
13. Project structure
cos_comparison/
core/ backend loader, pure-Python reference, config; C sources
data/ tensor containers and zero-copy views
sense_layer/ receptors and the recognition API
memory_layer/ memory carriers
brain_layer/ logic, reflexes, hierarchical mapping
action_layer/ executers
generate_layer/ reverse-composition generation
interface/ APIs and tools (parallel, async, io, shell, math)
extension_layer/ plugin hosting
shell_tool/ unified shell / batch / instruction surface
app/ docker manager and protocol surface
test_tool/ built-in debugger
tests/ standalone test suite (stdlib + package)
explore/ principle implementations on the installed engine
docs/ full documentation
History.txt change history (the single changelog)
14. Author and license
Author: Li Jinxin , born 2008-05-31. Contact: lijinxin_gx@sina.cn Source: github.com/LiJinxin-gx/cos-comparison
Released under the MIT License.
15. Change history
This document describes the formal release as a static reference and does not enumerate changes. The complete change history, including every earlier release, is maintained in History.txt.
Metadata
Release files for cos-comparison 1.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| cos_comparison-1.0.0.tar.gz | 537.0 kB | Without provenance | Details for cos_comparison-1.0.0.tar.gz |
Release files / cos_comparison-1.0.0.tar.gz
| Download URL | cos_comparison-1.0.0.tar.gz |
|---|---|
| Size | 537.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
351717ef2e933704890a1997ed8f1b6a213a8063bc4e05f1d1dab4ec6dbbbc7e
|
|
BLAKE2b-256 checksum How to use checksums |
4fe159a1437b44f0148ba33febb5deb3b77ee8128e7d86ecb79224c74d6a19f0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.15.0
|
Security for cos-comparison 1.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.