seraphim-logic-core 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.4
2
+ Name: seraphim-logic-core
3
+ Version: 0.1.0
4
+ Summary: Quantum-classical hybrid symbolic agent framework — Seraphim |LZ⟩
5
+ Author-email: "Perfect Squared Inc. | P2 Labs" <contact@perfectsquaredinc.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/10XAnalytics/seraphim-logic-core
8
+ Project-URL: Repository, https://github.com/10XAnalytics/seraphim-logic-core
9
+ Project-URL: Bug Tracker, https://github.com/10XAnalytics/seraphim-logic-core/issues
10
+ Keywords: quantum,symbolic-ai,agents,pennylane,entropy,swarm
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Topic :: Scientific/Engineering :: Physics
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ Requires-Dist: numpy>=1.24
24
+ Requires-Dist: pennylane>=0.36
25
+ Provides-Extra: qiskit
26
+ Requires-Dist: qiskit>=1.0; extra == "qiskit"
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=7.0; extra == "dev"
29
+ Requires-Dist: pytest-cov; extra == "dev"
30
+
31
+ # seraphim-logic-core
32
+
33
+ **Quantum-Classical Hybrid Symbolic Agent Framework**
34
+ Perfect Squared Inc. | P2 Labs | Seraphim |LZ⟩
35
+
36
+ > *Agents of the Highest Order*
37
+
38
+ ---
39
+
40
+ ## Overview
41
+
42
+ `seraphim-logic-core` is the symbolic intelligence engine behind the Seraphim |LZ⟩ research initiative. It implements a quantum-native agent framework where agents exist in superposition across all symbolic states and collapse to a single truth via a PennyLane quantum circuit.
43
+
44
+ ```
45
+ |S⟩ = Σ αᵢ |sᵢ⟩ → |s*⟩
46
+
47
+ P(kᵢ) ∝ exp(-Entropy(kᵢ))
48
+ D = argmax_i(I(sᵢ) - β·E(sᵢ))
49
+ ```
50
+
51
+ ## Architecture
52
+
53
+ ```
54
+ seraphim_logic_core/
55
+ ├── constants.py — System constants (entropy thresholds, lifecycle states)
56
+ ├── entropy.py — XOR-Lattice Entropy Engine (Shannon entropy, XOR diff, anomaly detection)
57
+ ├── grammar.py — Symbolic Grammar Engine (symbols, rules, pre-built grammars)
58
+ ├── collapse.py — Quantum Collapse Engine (PennyLane StatePrep + probs)
59
+ ├── agent.py — SymbolicAgent (full ENCODED→DELIVERED lifecycle)
60
+ └── swarm.py — AgentSwarm (parallel agent coordination + entropy-aware voting)
61
+ ```
62
+
63
+ ## Agent Lifecycle
64
+
65
+ ```
66
+ ENCODED → EVOLVED → INITIALIZED → COLLAPSED → ACTIVATED → DELIVERED
67
+ ```
68
+
69
+ Each agent:
70
+ 1. **Encodes** a symbolic grammar into its logic space
71
+ 2. **Evolves** via grammar transition rules driven by entropy signals
72
+ 3. **Initializes** as |LZ⟩ — superposition across all states
73
+ 4. **Collapses** via PennyLane quantum circuit to |s*⟩
74
+ 5. **Activates** — emits a structured decision dict
75
+ 6. **Delivers** to the target system (QUANTA handler)
76
+
77
+ ## Quick Start
78
+
79
+ ```python
80
+ from seraphim_logic_core import SymbolicAgent, AgentSwarm
81
+ from seraphim_logic_core import threat_detection_grammar, integrity_grammar
82
+
83
+ # Single agent — threat detection
84
+ agent = SymbolicAgent(grammar=threat_detection_grammar())
85
+ result = agent.run(entropy_signal=0.85)
86
+ print(result["symbol"]) # e.g. "ANOMALOUS"
87
+
88
+ # Swarm — integrity monitoring
89
+ swarm = AgentSwarm(grammar=integrity_grammar())
90
+ verdict = swarm.respond_to_xor_event(window_1, window_2)
91
+ print(verdict["symbol"]) # e.g. "DEGRADED"
92
+ ```
93
+
94
+ ## Pre-Built Grammars
95
+
96
+ | Grammar | Product | States |
97
+ |---------|---------|--------|
98
+ | `threat_detection_grammar()` | QUANTA-PULSE / QUANTA-RAD | NOMINAL → ANOMALOUS → SPOOFED → CONFIRMED → RESOLVED |
99
+ | `integrity_grammar()` | QUANTA-VIGIL | SECURE → DEGRADED → BREACHED → RESTORING |
100
+
101
+ ## Installation
102
+
103
+ ```bash
104
+ pip install seraphim-logic-core
105
+ ```
106
+
107
+ **Development:**
108
+ ```bash
109
+ git clone https://github.com/10XAnalytics/seraphim-logic-core
110
+ cd seraphim-logic-core
111
+ pip install -e ".[dev]"
112
+ pytest
113
+ ```
114
+
115
+ ## Quantum Backend
116
+
117
+ Uses [PennyLane](https://pennylane.ai/) `default.qubit` simulator (1024 shots).
118
+ Production deployments can target real quantum hardware via PennyLane device plugins.
119
+
120
+ Classical fallback available for testing:
121
+ ```python
122
+ agent = SymbolicAgent(grammar=threat_detection_grammar(), use_quantum=False)
123
+ ```
124
+
125
+ ## License
126
+
127
+ Apache 2.0 — See [LICENSE](LICENSE)
128
+
129
+ ---
130
+
131
+ *Perfect Squared Inc. | P2 Labs — "Simulate the Future. Secure the Present."*
@@ -0,0 +1,101 @@
1
+ # seraphim-logic-core
2
+
3
+ **Quantum-Classical Hybrid Symbolic Agent Framework**
4
+ Perfect Squared Inc. | P2 Labs | Seraphim |LZ⟩
5
+
6
+ > *Agents of the Highest Order*
7
+
8
+ ---
9
+
10
+ ## Overview
11
+
12
+ `seraphim-logic-core` is the symbolic intelligence engine behind the Seraphim |LZ⟩ research initiative. It implements a quantum-native agent framework where agents exist in superposition across all symbolic states and collapse to a single truth via a PennyLane quantum circuit.
13
+
14
+ ```
15
+ |S⟩ = Σ αᵢ |sᵢ⟩ → |s*⟩
16
+
17
+ P(kᵢ) ∝ exp(-Entropy(kᵢ))
18
+ D = argmax_i(I(sᵢ) - β·E(sᵢ))
19
+ ```
20
+
21
+ ## Architecture
22
+
23
+ ```
24
+ seraphim_logic_core/
25
+ ├── constants.py — System constants (entropy thresholds, lifecycle states)
26
+ ├── entropy.py — XOR-Lattice Entropy Engine (Shannon entropy, XOR diff, anomaly detection)
27
+ ├── grammar.py — Symbolic Grammar Engine (symbols, rules, pre-built grammars)
28
+ ├── collapse.py — Quantum Collapse Engine (PennyLane StatePrep + probs)
29
+ ├── agent.py — SymbolicAgent (full ENCODED→DELIVERED lifecycle)
30
+ └── swarm.py — AgentSwarm (parallel agent coordination + entropy-aware voting)
31
+ ```
32
+
33
+ ## Agent Lifecycle
34
+
35
+ ```
36
+ ENCODED → EVOLVED → INITIALIZED → COLLAPSED → ACTIVATED → DELIVERED
37
+ ```
38
+
39
+ Each agent:
40
+ 1. **Encodes** a symbolic grammar into its logic space
41
+ 2. **Evolves** via grammar transition rules driven by entropy signals
42
+ 3. **Initializes** as |LZ⟩ — superposition across all states
43
+ 4. **Collapses** via PennyLane quantum circuit to |s*⟩
44
+ 5. **Activates** — emits a structured decision dict
45
+ 6. **Delivers** to the target system (QUANTA handler)
46
+
47
+ ## Quick Start
48
+
49
+ ```python
50
+ from seraphim_logic_core import SymbolicAgent, AgentSwarm
51
+ from seraphim_logic_core import threat_detection_grammar, integrity_grammar
52
+
53
+ # Single agent — threat detection
54
+ agent = SymbolicAgent(grammar=threat_detection_grammar())
55
+ result = agent.run(entropy_signal=0.85)
56
+ print(result["symbol"]) # e.g. "ANOMALOUS"
57
+
58
+ # Swarm — integrity monitoring
59
+ swarm = AgentSwarm(grammar=integrity_grammar())
60
+ verdict = swarm.respond_to_xor_event(window_1, window_2)
61
+ print(verdict["symbol"]) # e.g. "DEGRADED"
62
+ ```
63
+
64
+ ## Pre-Built Grammars
65
+
66
+ | Grammar | Product | States |
67
+ |---------|---------|--------|
68
+ | `threat_detection_grammar()` | QUANTA-PULSE / QUANTA-RAD | NOMINAL → ANOMALOUS → SPOOFED → CONFIRMED → RESOLVED |
69
+ | `integrity_grammar()` | QUANTA-VIGIL | SECURE → DEGRADED → BREACHED → RESTORING |
70
+
71
+ ## Installation
72
+
73
+ ```bash
74
+ pip install seraphim-logic-core
75
+ ```
76
+
77
+ **Development:**
78
+ ```bash
79
+ git clone https://github.com/10XAnalytics/seraphim-logic-core
80
+ cd seraphim-logic-core
81
+ pip install -e ".[dev]"
82
+ pytest
83
+ ```
84
+
85
+ ## Quantum Backend
86
+
87
+ Uses [PennyLane](https://pennylane.ai/) `default.qubit` simulator (1024 shots).
88
+ Production deployments can target real quantum hardware via PennyLane device plugins.
89
+
90
+ Classical fallback available for testing:
91
+ ```python
92
+ agent = SymbolicAgent(grammar=threat_detection_grammar(), use_quantum=False)
93
+ ```
94
+
95
+ ## License
96
+
97
+ Apache 2.0 — See [LICENSE](LICENSE)
98
+
99
+ ---
100
+
101
+ *Perfect Squared Inc. | P2 Labs — "Simulate the Future. Secure the Present."*
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "seraphim-logic-core"
7
+ version = "0.1.0"
8
+ description = "Quantum-classical hybrid symbolic agent framework — Seraphim |LZ⟩"
9
+ authors = [
10
+ { name = "Perfect Squared Inc. | P2 Labs", email = "contact@perfectsquaredinc.com" }
11
+ ]
12
+ license = { text = "Apache-2.0" }
13
+ readme = "README.md"
14
+ requires-python = ">=3.10"
15
+ keywords = ["quantum", "symbolic-ai", "agents", "pennylane", "entropy", "swarm"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "Intended Audience :: Science/Research",
20
+ "License :: OSI Approved :: Apache Software License",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
26
+ "Topic :: Scientific/Engineering :: Physics",
27
+ ]
28
+ dependencies = [
29
+ "numpy>=1.24",
30
+ "pennylane>=0.36",
31
+ ]
32
+
33
+ [project.optional-dependencies]
34
+ qiskit = ["qiskit>=1.0"]
35
+ dev = [
36
+ "pytest>=7.0",
37
+ "pytest-cov",
38
+ ]
39
+
40
+ [project.urls]
41
+ Homepage = "https://github.com/10XAnalytics/seraphim-logic-core"
42
+ Repository = "https://github.com/10XAnalytics/seraphim-logic-core"
43
+ "Bug Tracker" = "https://github.com/10XAnalytics/seraphim-logic-core/issues"
44
+
45
+ [tool.setuptools.packages.find]
46
+ where = ["."]
47
+ include = ["seraphim_logic_core*"]
48
+
49
+ [tool.pytest.ini_options]
50
+ testpaths = ["tests"]
51
+ addopts = "-v --tb=short"
@@ -0,0 +1,71 @@
1
+ """
2
+ seraphim-logic-core
3
+ Perfect Squared Inc. | P2 Labs | Seraphim |LZ⟩
4
+
5
+ Quantum-classical hybrid symbolic agent framework.
6
+ Agents exist in superposition — the quantum circuit collapses them to truth.
7
+
8
+ |S⟩ = Σ αᵢ |sᵢ⟩ → |s*⟩
9
+ """
10
+
11
+ __version__ = "0.1.0"
12
+ __author__ = "Perfect Squared Inc. | P2 Labs"
13
+ __license__ = "Apache-2.0"
14
+
15
+ from .constants import (
16
+ ENTROPY_THRESHOLD,
17
+ BETA,
18
+ WINDOW_SIZE,
19
+ STRIDE,
20
+ QUANTUM_SHOTS,
21
+ STATE_ENCODED,
22
+ STATE_EVOLVED,
23
+ STATE_INITIALIZED,
24
+ STATE_COLLAPSED,
25
+ STATE_ACTIVATED,
26
+ STATE_DELIVERED,
27
+ LIFECYCLE,
28
+ )
29
+
30
+ from .entropy import (
31
+ shannon_entropy,
32
+ xor_lattice_diff,
33
+ entropy_over_stream,
34
+ entropy_decision,
35
+ anomaly_detected,
36
+ agent_spawn_count,
37
+ )
38
+
39
+ from .grammar import (
40
+ Symbol,
41
+ GrammarRule,
42
+ SymbolicGrammar,
43
+ threat_detection_grammar,
44
+ integrity_grammar,
45
+ )
46
+
47
+ from .collapse import (
48
+ entropy_weighted_amplitudes,
49
+ collapse,
50
+ collapse_classical,
51
+ )
52
+
53
+ from .agent import SymbolicAgent
54
+ from .swarm import AgentSwarm
55
+
56
+ __all__ = [
57
+ # Constants
58
+ "ENTROPY_THRESHOLD", "BETA", "WINDOW_SIZE", "STRIDE", "QUANTUM_SHOTS",
59
+ "STATE_ENCODED", "STATE_EVOLVED", "STATE_INITIALIZED",
60
+ "STATE_COLLAPSED", "STATE_ACTIVATED", "STATE_DELIVERED", "LIFECYCLE",
61
+ # Entropy
62
+ "shannon_entropy", "xor_lattice_diff", "entropy_over_stream",
63
+ "entropy_decision", "anomaly_detected", "agent_spawn_count",
64
+ # Grammar
65
+ "Symbol", "GrammarRule", "SymbolicGrammar",
66
+ "threat_detection_grammar", "integrity_grammar",
67
+ # Collapse
68
+ "entropy_weighted_amplitudes", "collapse", "collapse_classical",
69
+ # Agent + Swarm
70
+ "SymbolicAgent", "AgentSwarm",
71
+ ]
@@ -0,0 +1,204 @@
1
+ """
2
+ seraphim-logic-core — Symbolic Agent
3
+ Perfect Squared Inc. | P2 Labs | Seraphim |LZ⟩
4
+
5
+ A SymbolicAgent exists in superposition across all symbolic states defined
6
+ by its grammar. Each agent traverses the Seraphim Field lifecycle:
7
+
8
+ ENCODED → EVOLVED → INITIALIZED → COLLAPSED → ACTIVATED → DELIVERED
9
+
10
+ The agent uses the quantum collapse engine to resolve superposition and
11
+ the entropy decision function to select optimal state transitions.
12
+ """
13
+
14
+ import uuid
15
+ import numpy as np
16
+ from typing import Optional, List, Callable
17
+ from .constants import (
18
+ STATE_ENCODED, STATE_EVOLVED, STATE_INITIALIZED,
19
+ STATE_COLLAPSED, STATE_ACTIVATED, STATE_DELIVERED, LIFECYCLE
20
+ )
21
+ from .entropy import entropy_decision, shannon_entropy
22
+ from .grammar import SymbolicGrammar
23
+ from .collapse import collapse, collapse_classical
24
+
25
+
26
+ class SymbolicAgent:
27
+ """
28
+ A quantum-symbolic agent in the Seraphim Field.
29
+
30
+ Each agent:
31
+ - Carries a SymbolicGrammar defining its logic space
32
+ - Traverses the lifecycle: ENCODED → ... → DELIVERED
33
+ - Collapses superposition via PennyLane quantum circuit
34
+ - Emits decisions as collapsed symbolic states
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ grammar: SymbolicGrammar,
40
+ agent_id: Optional[str] = None,
41
+ use_quantum: bool = True,
42
+ initial_symbol: Optional[str] = None,
43
+ ):
44
+ self.id = agent_id or str(uuid.uuid4())[:8]
45
+ self.grammar = grammar
46
+ self.use_quantum = use_quantum
47
+
48
+ # Lifecycle state
49
+ self.lifecycle_state: str = STATE_ENCODED
50
+
51
+ # Current symbolic state (name of active symbol)
52
+ symbol_names = list(grammar.symbols.keys())
53
+ if initial_symbol and initial_symbol in grammar.symbols:
54
+ self.current_symbol: str = initial_symbol
55
+ elif symbol_names:
56
+ self.current_symbol = symbol_names[0]
57
+ else:
58
+ self.current_symbol = ""
59
+
60
+ # History of collapsed states
61
+ self.history: List[dict] = []
62
+
63
+ # Entropy signal (updated externally or via observe())
64
+ self.entropy_signal: float = 0.0
65
+
66
+ # ── Lifecycle ─────────────────────────────────────────────────────────────
67
+
68
+ def _advance_lifecycle(self) -> str:
69
+ """Move to the next lifecycle stage."""
70
+ current_idx = LIFECYCLE.index(self.lifecycle_state) if self.lifecycle_state in LIFECYCLE else -1
71
+ if current_idx < len(LIFECYCLE) - 1:
72
+ self.lifecycle_state = LIFECYCLE[current_idx + 1]
73
+ return self.lifecycle_state
74
+
75
+ def encode(self) -> "SymbolicAgent":
76
+ """Stage 0: Symbol encoded below Planck threshold."""
77
+ self.lifecycle_state = STATE_ENCODED
78
+ return self
79
+
80
+ def evolve(self, entropy_signal: float) -> "SymbolicAgent":
81
+ """
82
+ Stage 1: Evolve in the Seraphim Field.
83
+ Applies grammar transition rules based on entropy signal.
84
+ """
85
+ self.entropy_signal = entropy_signal
86
+ next_symbol = self.grammar.transition(self.current_symbol, entropy_signal)
87
+ if next_symbol:
88
+ self.current_symbol = next_symbol
89
+ self.lifecycle_state = STATE_EVOLVED
90
+ return self
91
+
92
+ def initialize(self) -> "SymbolicAgent":
93
+ """Stage 2: Initialize as |LZ⟩ — prepare superposition."""
94
+ self.lifecycle_state = STATE_INITIALIZED
95
+ return self
96
+
97
+ def collapse_state(self) -> Optional[dict]:
98
+ """
99
+ Stage 3: |S⟩ = Σαᵢ|sᵢ⟩ → |s*⟩
100
+
101
+ Collapse superposition to a single symbolic state.
102
+ Uses quantum circuit (PennyLane) or classical fallback.
103
+ Returns the collapsed state dict.
104
+ """
105
+ states = self.grammar.all_states()
106
+ if not states:
107
+ return None
108
+
109
+ if self.use_quantum:
110
+ result = collapse(states)
111
+ else:
112
+ result = collapse_classical(states)
113
+
114
+ if result:
115
+ self.current_symbol = result.get("name", self.current_symbol)
116
+ self.history.append(result)
117
+
118
+ self.lifecycle_state = STATE_COLLAPSED
119
+ return result
120
+
121
+ def activate(self, payload: Optional[dict] = None) -> dict:
122
+ """
123
+ Stage 4: Activate within QUANTA — emit decision.
124
+ Packages the collapsed state with entropy metadata.
125
+ """
126
+ symbol = self.grammar.get_symbol(self.current_symbol)
127
+ decision = {
128
+ "agent_id": self.id,
129
+ "grammar": self.grammar.name,
130
+ "symbol": self.current_symbol,
131
+ "value": symbol.value if symbol else 0.0,
132
+ "entropy_cost": symbol.entropy_cost if symbol else 0.0,
133
+ "information_gain": symbol.information_gain if symbol else 0.0,
134
+ "entropy_signal": self.entropy_signal,
135
+ "lifecycle": self.lifecycle_state,
136
+ }
137
+ if payload:
138
+ decision["payload"] = payload
139
+ self.lifecycle_state = STATE_ACTIVATED
140
+ decision["lifecycle"] = STATE_ACTIVATED
141
+ return decision
142
+
143
+ def deliver(self, decision: dict, handler: Optional[Callable[[dict], None]] = None) -> dict:
144
+ """
145
+ Stage 5: Deliver to target system.
146
+ Optionally calls a handler function with the decision.
147
+ """
148
+ decision["lifecycle"] = STATE_DELIVERED
149
+ self.lifecycle_state = STATE_DELIVERED
150
+ if handler:
151
+ handler(decision)
152
+ return decision
153
+
154
+ # ── Full lifecycle run ────────────────────────────────────────────────────
155
+
156
+ def run(
157
+ self,
158
+ entropy_signal: float,
159
+ payload: Optional[dict] = None,
160
+ handler: Optional[Callable[[dict], None]] = None,
161
+ ) -> dict:
162
+ """
163
+ Execute the full agent lifecycle in one call.
164
+
165
+ ENCODED → EVOLVED → INITIALIZED → COLLAPSED → ACTIVATED → DELIVERED
166
+
167
+ Returns the final delivered decision dict.
168
+ """
169
+ self.encode()
170
+ self.evolve(entropy_signal)
171
+ self.initialize()
172
+ self.collapse_state()
173
+ decision = self.activate(payload)
174
+ return self.deliver(decision, handler)
175
+
176
+ # ── Observation ───────────────────────────────────────────────────────────
177
+
178
+ def observe(self, stream: np.ndarray) -> float:
179
+ """
180
+ Compute entropy signal from a raw data stream.
181
+ Updates self.entropy_signal and returns it.
182
+ """
183
+ h = shannon_entropy(stream)
184
+ self.entropy_signal = h
185
+ return h
186
+
187
+ def optimal_state(self) -> Optional[dict]:
188
+ """
189
+ D = argmax_i(I(sᵢ) - β·E(sᵢ))
190
+ Returns the optimal state by entropy decision function.
191
+ """
192
+ states = self.grammar.all_states()
193
+ if not states:
194
+ return None
195
+ idx = entropy_decision(states)
196
+ return states[idx]
197
+
198
+ # ── Representation ────────────────────────────────────────────────────────
199
+
200
+ def __repr__(self) -> str:
201
+ return (
202
+ f"SymbolicAgent(id={self.id}, grammar={self.grammar.name}, "
203
+ f"symbol={self.current_symbol}, lifecycle={self.lifecycle_state})"
204
+ )
@@ -0,0 +1,118 @@
1
+ """
2
+ seraphim-logic-core — Quantum Collapse Engine (PennyLane)
3
+ Perfect Squared Inc. | P2 Labs | Seraphim |LZ⟩
4
+
5
+ Implements Schrödinger-style superposition collapse using real quantum circuits:
6
+
7
+ |S⟩ = Σ αᵢ |sᵢ⟩ → |s*⟩
8
+
9
+ P(kᵢ) ∝ exp(-Entropy(kᵢ))
10
+
11
+ Agents exist in superposition across all possible symbolic states.
12
+ The quantum circuit collapses this superposition to a final logic state |s*⟩
13
+ based on entropy-weighted amplitudes.
14
+ """
15
+
16
+ import math
17
+ import numpy as np
18
+ import pennylane as qml
19
+ from typing import List, Optional
20
+ from .constants import QUANTUM_SHOTS
21
+
22
+
23
+ def _build_collapse_circuit(amplitudes: np.ndarray, n_qubits: int):
24
+ """Build a PennyLane quantum circuit that initializes and collapses superposition."""
25
+ dev = qml.device("default.qubit", wires=n_qubits, shots=QUANTUM_SHOTS)
26
+
27
+ @qml.qnode(dev)
28
+ def circuit():
29
+ # Initialize quantum state with entropy-weighted amplitudes
30
+ qml.StatePrep(amplitudes, wires=range(n_qubits))
31
+ # Measure all qubits — collapses superposition to |s*⟩
32
+ return qml.probs(wires=range(n_qubits))
33
+
34
+ return circuit
35
+
36
+
37
+ def entropy_weighted_amplitudes(states: List[dict]) -> np.ndarray:
38
+ """
39
+ P(kᵢ) ∝ exp(-Entropy(kᵢ))
40
+
41
+ Converts symbolic states to quantum amplitudes weighted by entropy.
42
+ Lower entropy cost = higher amplitude = more likely to be selected.
43
+ """
44
+ n = len(states)
45
+ if n == 0:
46
+ raise ValueError("No states to collapse")
47
+
48
+ # Compute weights: exp(-entropy_cost)
49
+ weights = np.array([
50
+ math.exp(-s.get("entropy_cost", 0.5))
51
+ for s in states
52
+ ], dtype=complex)
53
+
54
+ # Pad to next power of 2 (required for quantum state vector)
55
+ n_qubits = math.ceil(math.log2(max(n, 2)))
56
+ padded_size = 2 ** n_qubits
57
+
58
+ padded = np.zeros(padded_size, dtype=complex)
59
+ padded[:n] = weights[:n]
60
+
61
+ # Normalize to unit vector (quantum requirement)
62
+ norm = np.linalg.norm(padded)
63
+ if norm == 0:
64
+ padded[:n] = 1.0 / math.sqrt(n)
65
+ else:
66
+ padded = padded / norm
67
+
68
+ return padded, n_qubits
69
+
70
+
71
+ def collapse(states: List[dict]) -> Optional[dict]:
72
+ """
73
+ |S⟩ = Σ αᵢ |sᵢ⟩ → |s*⟩
74
+
75
+ Main collapse function. Takes a list of symbolic states in superposition
76
+ and uses a quantum circuit to collapse to a single final state.
77
+
78
+ Returns the collapsed state dict, or None if no states provided.
79
+ """
80
+ if not states:
81
+ return None
82
+
83
+ if len(states) == 1:
84
+ return states[0]
85
+
86
+ # Build quantum amplitudes from entropy weights
87
+ amplitudes, n_qubits = entropy_weighted_amplitudes(states)
88
+
89
+ # Run quantum circuit — collapse superposition
90
+ circuit = _build_collapse_circuit(amplitudes, n_qubits)
91
+ probs = circuit()
92
+
93
+ # Select the most probable basis state
94
+ collapsed_idx = int(np.argmax(probs))
95
+
96
+ # Map back to symbolic state (clamp to valid range)
97
+ state_idx = min(collapsed_idx, len(states) - 1)
98
+ return states[state_idx]
99
+
100
+
101
+ def collapse_classical(states: List[dict]) -> Optional[dict]:
102
+ """
103
+ Classical fallback collapse — uses entropy weights without quantum circuit.
104
+ Used for testing or when quantum backend is unavailable.
105
+
106
+ P(kᵢ) ∝ exp(-Entropy(kᵢ)) — same math, sampled classically.
107
+ """
108
+ if not states:
109
+ return None
110
+
111
+ weights = np.array([
112
+ math.exp(-s.get("entropy_cost", 0.5))
113
+ for s in states
114
+ ])
115
+ weights = weights / weights.sum()
116
+
117
+ idx = np.random.choice(len(states), p=weights)
118
+ return states[int(idx)]