Metadata-Version: 2.4
Name: analogos
Version: 0.5.0
Summary: analogOS — Universal analogy kernel with JSON-configurable domain primitives, PyTorch integration, and FastAPI runtime
Author: Zaqueu Ribeiro
License: GPL-3.0
Project-URL: Homepage, https://github.com/omega-Core-Dev/analogOS
Project-URL: Repository, https://github.com/omega-Core-Dev/analogOS
Project-URL: Issues, https://github.com/omega-Core-Dev/analogOS/issues
Keywords: analogy,analogy-engine,complex-systems,signal-propagation,cognitive-computing,domain-agnostic,primitives,ai-runtime,fastapi,pytorch,agent,pipeline
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: fastapi>=0.111
Requires-Dist: uvicorn[standard]>=0.29
Requires-Dist: pydantic>=2.0
Provides-Extra: runtime
Requires-Dist: redis>=5.0; extra == "runtime"
Requires-Dist: httpx>=0.27; extra == "runtime"
Provides-Extra: torch
Requires-Dist: torch>=2.0; extra == "torch"
Provides-Extra: jax
Requires-Dist: jax>=0.4; extra == "jax"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: httpx>=0.27; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Provides-Extra: all
Requires-Dist: analogos[dev,runtime,torch]; extra == "all"
Dynamic: license-file


# analogos
### Programmable Analogy Framework · v0.5.0 · Apache-2.0

> *"Analogy is not a way to explain systems. Analogy **is** the system."*

[![PyPI version](https://img.shields.io/badge/pypi-v0.5.0-blue)](https://pypi.org/project/analogos/)
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/omega-Core-Dev/analogOS/blob/main/analogOS_demo.ipynb)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![PyTorch](https://img.shields.io/badge/backend-PyTorch-ee4c2c)](https://pytorch.org/)
[![JAX](https://img.shields.io/badge/backend-JAX-00599c)](https://github.com/google/jax)
[![Python](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org/)

---

## What is analogos?

**analogos** is a general-purpose framework that formalizes analogy as a programmable primitive.

It is a **systems algebra** — a minimal set of operators that describes the behavior of any system where information is generated, distributed, filtered, propagated, and composed.

The central proposition:
> Different complex systems — neural networks, financial markets, immune systems, blockchains — are instances of the **same structural pattern**.

---

## Install

```bash
pip install analogs

```
## 🚀 AI Mainframe: PyTorch & JAX Integration (v0.5.0)
O **analogos** agora opera como um mainframe de alto desempenho para IA, suportando tensores nativos e execução em hardware acelerado (GPU/TPU).
 * **Diferenciação Automática:** Pritimitivas prontas para integração em loops de treino PyTorch.
 * **XLA Compilation:** Performance otimizada via JAX para processamento de analogias em larga escala.
 * **Hardware Agnostic:** Alterne entre CPU, CUDA e TPU apenas mudando o backend.
```python
import torch
from analogos.backends import TorchPipeline

# Execução em GPU com tensores de alta dimensão
pipeline = TorchPipeline(device='cuda')
result = pipeline.run(source=query_tensor, entities=tensor_space)

```
## Universal Kernel (v0.5.0)

The Kernel is the new central runtime — it executes any domain from a JSON config, a built-in name, or an inline dict.

```python
from analogos import Kernel, Entity

k = Kernel()

# built-in domain
result = k.run(source, entities, domain="neuro")

# external JSON file
result = k.run(source, entities, domain="my_domain.json")

# inline dict
result = k.run(source, entities, domain={
    "name": "custom",
    "broadcast":  {"falloff": "linear", "intensity": 0.8},
    "candidate":  {"threshold": 0.1},
    "propagate":  {"social_factor": 0.5},
    "compose":    {"mode": "top_k", "top_k": 5},
})

print(result.summary())
```

Built-in domain configs (`analogos/domains/*.json`):

| Domain | falloff | threshold | social_factor | compose |
|--------|---------|-----------|---------------|---------|
| `neuro` | quadratic | 0.25 | 0.65 | top_k (8) |
| `market` | sqrt | 0.15 | 0.75 | top_k (6) |
| `immune` | quadratic | 0.30 | 0.80 | top_k (6) |
| `blockchain` | linear | 0.03 | 0.60 | vote (5) |

---

## The Five Universal Primitives
```
scan → broadcast → candidate → propagate → compose

```
| Primitive | Description | Complexity |
|---|---|---|
| scan() | Traverses the entity space and builds a reference map | O(n) |
| broadcast() | Source emits a signal; intensity decays with distance | O(k) |
| candidate() | Filters entities that received sufficient signal | O(k) |
| propagate() | Candidates relay signal to neighbors — emerging clusters | O(k·r) |
| compose() | Aggregates the cluster into a unified output | O(k) |
## Domain Instances
O **analogos** permite parametrizar diferentes domínios sem reescrever a lógica central:
| Domain | Application |
|---|---|
| **analog-attention** | Mecanismos de atenção baseados em analogia. |
| **analog-neuro** | Simulação de caminhos de ativação neuronal. |
| **analog-market** | Contágio de sinais de preço em ativos financeiros. |
| **analog-immune** | Cascatas de resposta imunológica. |
| **analog-blockchain** | Propagação de consenso e validação em rede. |
## Project Structure
```
analogos/
├── core/                ← Primitivas universais (scan, broadcast, etc)
├── backends/            ← Integração PyTorch e JAX (v0.5.0)
├── domains/             ← Implementações específicas (Neuro, Market, etc)
├── adaptive.py          ← Engine de calibração automática
└── memory.py            ← Analogical Memory Loop

```
## License
**Apache License 2.0** — use, modifique e distribua livremente, inclusive para fins comerciais.
Diferente da GPL-3.0 anterior, a Apache 2.0 permite:
 * Integração em projetos proprietários sem obrigatoriedade de abrir o código derivado.
 * Concessão explícita de direitos de patente.
 * Segurança jurídica para uso em ecossistemas de produção industrial.
## Author
**Zaqueu Ribeiro** · github.com/omega-Core-Dev
> *"The pattern was always there. It just needed a name."*
> 
```

```
print(r1.summary())

# cycle 2 — correlates with cycle 1, adapts parameters
r2 = ap.process("Financial markets propagate price signals across assets...", doc_id="market")
print(r2.summary())
# → finds shared patterns: ['signals', 'propagation', 'activation', 'patterns']
# → adjusts threshold and social_factor based on structural correlation

# retrieve documents similar to the query
similar = ap.memory.retrieve_similar(source_entity, top_k=3)
```
 
Each cycle:
1. Converts raw text into `Entity` objects via hash-stable random projections (numpy-only, no ML dependencies)
2. Runs the full analogy pipeline
3. Computes Jaccard + cosine similarity against memory
4. Adjusts `threshold` and `social_factor` based on cluster density and correlation strength
5. Stores the result for future cycles

---

## Domain Instances

Each domain is a parameterization of the five primitives — no new code, only different parameters.

| Domain | scan | broadcast | candidate | propagate | compose |
|--------|------|-----------|-----------|-----------|---------|
| **analog-attention** | tokens | query vector | keys ≥ threshold | value context | weighted sum |
| **analog-neuro** | neurons | action potential | threshold neurons | synaptic relay | firing pattern |
| **analog-market** | assets | price signal | eligible assets | market contagion | portfolio |
| **analog-immune** | antigens | receptor signal | activated cells | immune cascade | response |
| **analog-blockchain** | nodes | broadcast tx | validators | peer relay | block commit |

### analog-neuro

```python
from analogos.domains.neuro import NeuroPipeline, Neuron, Stimulus

neurons = [
    Neuron("LGN_1", "LGN", layer=4, neurotransmitter="glutamate"),
    Neuron("V1_L4", "V1",  layer=4, neurotransmitter="glutamate"),
    Neuron("V2_1",  "V2",  layer=2, neurotransmitter="glutamate"),
    Neuron("MT_1",  "MT",  layer=4, neurotransmitter="glutamate"),
    Neuron("PFC_1", "PFC", layer=3, neurotransmitter="dopamine"),
]
stimulus = Stimulus("s1", "flash visual", modality="visual", target_region="V1")

result = NeuroPipeline().fire(stimulus, neurons)
print(result.summary())
# Caminho de ativação: LGN → V1 → V2 → MT → PFC
```

### analog-market

```python
from analogos.domains.market import MarketPipeline, Asset, MarketEvent

assets = [
    Asset("TLT",  "iShares 20Y Treasury", sector="bonds",      beta=-0.3),
    Asset("XLF",  "Financial Select",     sector="financials", beta=1.3),
    Asset("QQQ",  "NASDAQ-100",           sector="tech",       beta=1.5),
    Asset("GLD",  "Gold Trust",           sector="commodities",beta=-0.1),
]
event = MarketEvent("fed_hike", "Fed rate hike +75bps", magnitude=0.85,
                    affected_sectors=["bonds", "financials"])

result = MarketPipeline().shock(event, assets)
print(result.summary())
# Contágio setorial: bonds → financials → tech → commodities
```

### analog-immune

```python
from analogos.domains.immune import ImmunePipeline, ImmuneCell, Pathogen

cells = [
    ImmuneCell("dc1",    "dendritic",   specificity=0.95),
    ImmuneCell("th1",    "T_helper",    specificity=0.85),
    ImmuneCell("bc_mem", "B_cell",      specificity=0.92, is_memory=True),
    ImmuneCell("tc1",    "T_cytotoxic", specificity=0.90),
]
pathogen = Pathogen("flu", "Influenza H3N2", pathogen_type="virus", virulence=0.75)

result = ImmunePipeline().respond(pathogen, cells)
print(result.summary())
# Resposta: mista (inata + adaptativa) · células de memória: [bc_mem]
```

### analog-blockchain

```python
from analogos.domains.blockchain import BlockchainPipeline, Node, Transaction

nodes = [
    Node("val_01", "validator", stake=0.95, reputation=0.98, region="north_america"),
    Node("val_02", "validator", stake=0.90, reputation=0.96, region="europe"),
    Node("full_01","full_node", stake=0.20, reputation=0.88, region="asia_pacific"),
]
tx = Transaction("tx_001", "DeFi swap 50 ETH → USDC", fee=0.08, priority=0.9)

result = BlockchainPipeline().broadcast_tx(tx, nodes)
print(result.summary())
# Consenso: ✓ ATINGIDO · Bloco: ✓ COMMITADO
```

---

## Project Structure

```
analogos/                    ← installable package
├── __init__.py              ← full public API
├── py.typed                 ← PEP 561 — IDE autocomplete & type checking
├── core/
│   ├── entity.py            ← Entity base class
│   └── primitives/
│       ├── scan.py
│       ├── broadcast.py
│       ├── candidate.py
│       ├── propagate.py
│       └── compose.py
├── pipeline.py              ← Pipeline · PipelineConfig · PipelineResult
├── ingest.py                ← TextIngester (text → Entity[])
├── memory.py                ← AnalogMemory (incremental record store)
├── correlator.py            ← cross-document structural correlation
└── adaptive.py              ← AdaptivePipeline

examples/                    ← runnable demos
tests/                       ← pytest suite
pyproject.toml               ← pip-installable, PEP 517/518
```

---

## IDE Support

The package ships with `py.typed` (PEP 561) and full type annotations.  
Autocomplete, go-to-definition, and inline docs work out of the box in VS Code, PyCharm, Neovim, and any LSP-compatible editor.

```python
from analogos import Entity, Pipeline, AdaptivePipeline  # fully typed
```

---

## Roadmap

- [x] **v0.1.0** — Foundation: five primitives in pure Python + architecture
- [x] **v0.2.0** — Installable library: `pip install analogos`, typed API, adaptive pipeline, memory loop, 11 unit tests
- [x] **v0.3.0** — Domains: `analog_neuro`, `analog_market`, `analog_immune`, `analog_blockchain` — 33 unit tests
- [x] **v0.4.1** — Integrations: PyTorch tensors, JAX, benchmark vs dot-product attention
- [x] **v0.5.0** — Universal Kernel: JSON-configurable domains, `Kernel.run(source, entities, domain=...)`, declarative domain schema
- [ ] **v1.0.0** — Multi-language bindings (Rust/PyO3, gRPC) + technical paper

---

## Theoretical Foundation

Conventional use of analogy in computing is **didactic**: it explains a hard concept using a familiar domain, then discards the analogy.

**analogos inverts this flow.**

The central claim is that the structure of the analogy *is* the structure of the system. The immune system is not "similar to" an attention mechanism. Both are instances of the same formal pattern:

```
scan → broadcast → candidate → propagate → compose
```

What does not exist in the literature is the formalization of analogy as a **reusable programmable primitive** — an operator that can be instantiated across any domain without rewriting the core logic.

That is what analogos proposes.

---

## License

Apache-2.0 — use, modify, and redistribute freely. See the LICENSE file for details.

---

## Author

**Zaqueu Ribeiro** · [github.com/omega-Core-Dev](https://github.com/omega-Core-Dev)

---

> *"The pattern was always there. It just needed a name."*
