Metadata-Version: 2.4
Name: cos-comparison
Version: 1.0.0
Summary: Local similarity comparison for feature extraction - biologically inspired, zero-training edge/pattern detection, multi-backend acceleration.
Author-email: Li Jinxin <lijinxin_gx@sina.cn>
License-Expression: MIT
Project-URL: Homepage, https://github.com/LiJinxin-gx/cos-comparison
Project-URL: Repository, https://github.com/LiJinxin-gx/cos-comparison.git
Project-URL: Issue Tracker, https://github.com/LiJinxin-gx/cos-comparison/issues
Project-URL: Documentation, https://cos-comparison.readthedocs.io/
Keywords: cosine similarity,local comparison,AGI,feature extraction,edge detection,template matching
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Programming Language :: C
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Image Processing
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Dynamic: license-file

# 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) and `py` (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 equal `1`
  for identical windows. `cos` ignores amplitude and answers whether two
  windows point the same way; `mod` ignores angle and answers whether
  their magnitudes match. `cosmod` couples the two and needs no square
  root, so it is the numerically efficient default.
- `cosmod` is 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`, otherwise `0`.

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 `d` selects the orientation of the detected boundary
  (horizontal, vertical, or diagonal); the window size sets the scale.
- The shifted axis loses one element. An `h × w` map with a scalar
  window and `d`-shift yields an `(h − 1) × w` passive map; a 1-D signal
  with `window_size=(1,)`, `d=(1,)` yields length `n − 1`.
- A region that cannot form a valid `d`-shift is rejected with
  `ValueError` rather 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](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          |

```python
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 `iterate` slot without modifying the
  package.

---

## 8. Installation

```bash
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:

```bash
python setup.py build_ext --inplace
```

See [docs/build.md](docs/build.md) for compiler, free-threaded, and ABI
details.

---

## 9. Quick start

```python
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).

```bash
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.

```bash
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](docs/performance.md).

---

## 12. Documentation

| Start with               | Document                                                                                           |
| ------------------------ | -------------------------------------------------------------------------------------------------- |
| Setup and first run      | [Getting Started](docs/getting-started.md)                                                         |
| Building the C backends  | [Build](docs/build.md)                                                                             |
| Command-line protocol    | [Command Line](docs/command-line.md)                                                               |
| Core and mode APIs       | [Core](docs/api/core.md) · [Passive](docs/api/passive-mode.md) · [Active](docs/api/active-mode.md) |
| Architecture and theory  | [Architecture](docs/architecture/README.md) · [Principles](docs/principles/README.md)              |
| Experiments and findings | [Exploration](docs/exploration/README.md)                                                          |

The complete documentation index is [docs/README.md](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](mailto:lijinxin_gx@sina.cn)
**Source:** [github.com/LiJinxin-gx/cos-comparison](https://github.com/LiJinxin-gx/cos-comparison)

Released under the [MIT License](LICENSE.txt).

---

## 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](History.txt).
