AuroraProgram commited on
Commit
1fd89e0
·
verified ·
1 Parent(s): e9462fd

Upload trinity_3\trigate.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. trinity_3//trigate.py +344 -0
trinity_3//trigate.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Aurora Trinity-3 Trigate Implementation
3
+ ======================================
4
+
5
+ Fundamental logic module based on geometric coherence and ternary logic.
6
+ Implements inference, learning, and deduction modes with O(1) LUT operations.
7
+
8
+ Based on the principle: A + B + R = 180° (geometric triangle closure)
9
+ Translated to ternary logic: {0, 1, NULL}
10
+
11
+ Author: Aurora Program
12
+ License: Apache-2.0 + CC-BY-4.0
13
+ """
14
+
15
+ from typing import List, Union, Optional, Tuple, Dict
16
+ import itertools
17
+
18
+
19
+ # Ternary values
20
+ NULL = None
21
+ TERNARY_VALUES = [0, 1, NULL]
22
+
23
+
24
+ class Trigate:
25
+ """
26
+ Fundamental Aurora logic module implementing ternary operations.
27
+
28
+ Supports three operational modes:
29
+ 1. Inference: A + B + M -> R (given inputs and control, compute result)
30
+ 2. Learning: A + B + R -> M (given inputs and result, learn control)
31
+ 3. Deduction: M + R + A -> B (given control, result, and one input, deduce other)
32
+
33
+ All operations are O(1) using precomputed lookup tables (LUTs).
34
+ """
35
+
36
+ # Class-level LUTs (computed once at module load)
37
+ _LUT_INFER: Dict[Tuple, int] = {}
38
+ _LUT_LEARN: Dict[Tuple, int] = {}
39
+ _LUT_DEDUCE_A: Dict[Tuple, int] = {}
40
+ _LUT_DEDUCE_B: Dict[Tuple, int] = {}
41
+ _initialized = False
42
+
43
+ def __init__(self):
44
+ """Initialize Trigate and ensure LUTs are computed."""
45
+ if not Trigate._initialized:
46
+ Trigate._initialize_luts()
47
+
48
+ @classmethod
49
+ def _initialize_luts(cls):
50
+ """
51
+ Initialize all lookup tables for O(1) operations.
52
+
53
+ Based on extended XOR logic with NULL propagation:
54
+ - 0 XOR 0 = 0, 0 XOR 1 = 1, 1 XOR 0 = 1, 1 XOR 1 = 0
55
+ - Any operation with NULL propagates NULL
56
+ - Control bit M determines XOR (1) or XNOR (0)
57
+ """
58
+ print("Initializing Trigate LUTs...")
59
+
60
+ # Generate all possible combinations for ternary logic
61
+ for a, b, m, r in itertools.product(TERNARY_VALUES, repeat=4):
62
+
63
+ # INFERENCE LUT: (a, b, m) -> r
64
+ computed_r = cls._compute_inference(a, b, m)
65
+ cls._LUT_INFER[(a, b, m)] = computed_r
66
+
67
+ # LEARNING LUT: (a, b, r) -> m
68
+ # Find control M that produces R given A, B
69
+ learned_m = cls._compute_learning(a, b, r)
70
+ cls._LUT_LEARN[(a, b, r)] = learned_m
71
+
72
+ # DEDUCTION LUTS: (m, r, a) -> b and (m, r, b) -> a
73
+ deduced_b = cls._compute_deduction_b(m, r, a)
74
+ deduced_a = cls._compute_deduction_a(m, r, b)
75
+
76
+ cls._LUT_DEDUCE_B[(m, r, a)] = deduced_b
77
+ cls._LUT_DEDUCE_A[(m, r, b)] = deduced_a
78
+
79
+ cls._initialized = True
80
+ print(f"Trigate LUTs initialized: {len(cls._LUT_INFER)} entries each")
81
+
82
+ @staticmethod
83
+ def _compute_inference(a: Union[int, None], b: Union[int, None], m: Union[int, None]) -> Union[int, None]:
84
+ """
85
+ Compute R given A, B, M using ternary logic.
86
+
87
+ Logic:
88
+ - If any input is NULL, result is NULL
89
+ - If M is 1: R = A XOR B
90
+ - If M is 0: R = A XNOR B (NOT(A XOR B))
91
+ """
92
+ if a is NULL or b is NULL or m is NULL:
93
+ return NULL
94
+
95
+ if m == 1: # XOR mode
96
+ return a ^ b
97
+ else: # XNOR mode (m == 0)
98
+ return 1 - (a ^ b)
99
+
100
+ @staticmethod
101
+ def _compute_learning(a: Union[int, None], b: Union[int, None], r: Union[int, None]) -> Union[int, None]:
102
+ """
103
+ Learn control M given A, B, R.
104
+
105
+ Logic:
106
+ - If any input is NULL, cannot learn -> NULL
107
+ - If A XOR B == R, then M = 1 (XOR)
108
+ - If A XOR B != R, then M = 0 (XNOR)
109
+ """
110
+ if a is NULL or b is NULL or r is NULL:
111
+ return NULL
112
+
113
+ xor_result = a ^ b
114
+ if xor_result == r:
115
+ return 1 # XOR mode produces correct result
116
+ else:
117
+ return 0 # XNOR mode produces correct result
118
+
119
+ @staticmethod
120
+ def _compute_deduction_a(m: Union[int, None], r: Union[int, None], b: Union[int, None]) -> Union[int, None]:
121
+ """
122
+ Deduce A given M, R, B.
123
+
124
+ Logic:
125
+ - If any input is NULL, cannot deduce -> NULL
126
+ - If M is 1: A = R XOR B (since R = A XOR B)
127
+ - If M is 0: A = NOT(R) XOR B (since R = NOT(A XOR B))
128
+ """
129
+ if m is NULL or r is NULL or b is NULL:
130
+ return NULL
131
+
132
+ if m == 1: # XOR mode: A XOR B = R -> A = R XOR B
133
+ return r ^ b
134
+ else: # XNOR mode: NOT(A XOR B) = R -> A XOR B = NOT(R) -> A = NOT(R) XOR B
135
+ return (1 - r) ^ b
136
+
137
+ @staticmethod
138
+ def _compute_deduction_b(m: Union[int, None], r: Union[int, None], a: Union[int, None]) -> Union[int, None]:
139
+ """
140
+ Deduce B given M, R, A.
141
+
142
+ Logic: Same as deduce_a but solving for B instead of A.
143
+ """
144
+ if m is NULL or r is NULL or a is NULL:
145
+ return NULL
146
+
147
+ if m == 1: # XOR mode: A XOR B = R -> B = R XOR A
148
+ return r ^ a
149
+ else: # XNOR mode: NOT(A XOR B) = R -> A XOR B = NOT(R) -> B = NOT(R) XOR A
150
+ return (1 - r) ^ a
151
+
152
+ def infer(self, A: List[Union[int, None]], B: List[Union[int, None]], M: List[Union[int, None]]) -> List[Union[int, None]]:
153
+ """
154
+ Inference mode: Compute R given A, B, M.
155
+
156
+ Args:
157
+ A: First input vector (3 bits)
158
+ B: Second input vector (3 bits)
159
+ M: Control vector (3 bits)
160
+
161
+ Returns:
162
+ R: Result vector (3 bits)
163
+
164
+ Example:
165
+ >>> trigate = Trigate()
166
+ >>> A = [0, 1, 0]
167
+ >>> B = [1, 0, 1]
168
+ >>> M = [1, 1, 0] # XOR, XOR, XNOR
169
+ >>> R = trigate.infer(A, B, M)
170
+ >>> print(R) # [1, 1, 1]
171
+ """
172
+ if not (len(A) == len(B) == len(M) == 3):
173
+ raise ValueError("All vectors must have exactly 3 elements")
174
+
175
+ return [self._LUT_INFER[(a, b, m)] for a, b, m in zip(A, B, M)]
176
+
177
+ def learn(self, A: List[Union[int, None]], B: List[Union[int, None]], R: List[Union[int, None]]) -> List[Union[int, None]]:
178
+ """
179
+ Learning mode: Learn control M given A, B, R.
180
+
181
+ Args:
182
+ A: First input vector (3 bits)
183
+ B: Second input vector (3 bits)
184
+ R: Target result vector (3 bits)
185
+
186
+ Returns:
187
+ M: Learned control vector (3 bits)
188
+
189
+ Example:
190
+ >>> trigate = Trigate()
191
+ >>> A = [0, 1, 0]
192
+ >>> B = [1, 0, 1]
193
+ >>> R = [1, 1, 1]
194
+ >>> M = trigate.learn(A, B, R)
195
+ >>> print(M) # [1, 1, 0]
196
+ """
197
+ if not (len(A) == len(B) == len(R) == 3):
198
+ raise ValueError("All vectors must have exactly 3 elements")
199
+
200
+ return [self._LUT_LEARN[(a, b, r)] for a, b, r in zip(A, B, R)]
201
+
202
+ def deduce_a(self, M: List[Union[int, None]], R: List[Union[int, None]], B: List[Union[int, None]]) -> List[Union[int, None]]:
203
+ """
204
+ Deduction mode: Deduce A given M, R, B.
205
+
206
+ Args:
207
+ M: Control vector (3 bits)
208
+ R: Result vector (3 bits)
209
+ B: Known input vector (3 bits)
210
+
211
+ Returns:
212
+ A: Deduced input vector (3 bits)
213
+ """
214
+ if not (len(M) == len(R) == len(B) == 3):
215
+ raise ValueError("All vectors must have exactly 3 elements")
216
+
217
+ return [self._LUT_DEDUCE_A[(m, r, b)] for m, r, b in zip(M, R, B)]
218
+
219
+ def deduce_b(self, M: List[Union[int, None]], R: List[Union[int, None]], A: List[Union[int, None]]) -> List[Union[int, None]]:
220
+ """
221
+ Deduction mode: Deduce B given M, R, A.
222
+
223
+ Args:
224
+ M: Control vector (3 bits)
225
+ R: Result vector (3 bits)
226
+ A: Known input vector (3 bits)
227
+
228
+ Returns:
229
+ B: Deduced input vector (3 bits)
230
+ """
231
+ if not (len(M) == len(R) == len(A) == 3):
232
+ raise ValueError("All vectors must have exactly 3 elements")
233
+
234
+ return [self._LUT_DEDUCE_B[(m, r, a)] for m, r, a in zip(M, R, A)]
235
+
236
+ def validate_triangle_closure(self, A: List[Union[int, None]], B: List[Union[int, None]],
237
+ M: List[Union[int, None]], R: List[Union[int, None]]) -> bool:
238
+ """
239
+ Validate that A, B, M, R form a valid logical triangle.
240
+
241
+ This ensures geometric coherence: the triangle "closes" properly.
242
+
243
+ Args:
244
+ A, B, M, R: The four vectors forming the logical triangle
245
+
246
+ Returns:
247
+ True if triangle is valid, False otherwise
248
+ """
249
+ # Compute expected R from A, B, M
250
+ expected_R = self.infer(A, B, M)
251
+
252
+ # Check if computed R matches provided R
253
+ for expected, actual in zip(expected_R, R):
254
+ if expected != actual:
255
+ return False
256
+
257
+ return True
258
+
259
+ def get_truth_table(self, operation: str = "infer") -> str:
260
+ """
261
+ Generate human-readable truth table for debugging.
262
+
263
+ Args:
264
+ operation: "infer", "learn", "deduce_a", or "deduce_b"
265
+
266
+ Returns:
267
+ Formatted truth table string
268
+ """
269
+ if operation == "infer":
270
+ lut = self._LUT_INFER
271
+ header = "A | B | M | R"
272
+ elif operation == "learn":
273
+ lut = self._LUT_LEARN
274
+ header = "A | B | R | M"
275
+ elif operation == "deduce_a":
276
+ lut = self._LUT_DEDUCE_A
277
+ header = "M | R | B | A"
278
+ elif operation == "deduce_b":
279
+ lut = self._LUT_DEDUCE_B
280
+ header = "M | R | A | B"
281
+ else:
282
+ raise ValueError(f"Unknown operation: {operation}")
283
+
284
+ def format_val(v):
285
+ return "N" if v is NULL else str(v)
286
+
287
+ lines = [header, "-" * len(header)]
288
+
289
+ for key, value in sorted(lut.items()):
290
+ key_str = " | ".join(format_val(k) for k in key)
291
+ val_str = format_val(value)
292
+ lines.append(f"{key_str} | {val_str}")
293
+
294
+ return "\n".join(lines)
295
+
296
+ def __repr__(self) -> str:
297
+ return f"Trigate(initialized={self._initialized}, lut_size={len(self._LUT_INFER)})"
298
+
299
+
300
+ # Example usage and testing
301
+ if __name__ == "__main__":
302
+ # Create Trigate instance
303
+ trigate = Trigate()
304
+
305
+ print("=== Aurora Trigate Implementation ===\n")
306
+
307
+ # Test inference
308
+ print("1. Inference Test:")
309
+ A = [0, 1, 0]
310
+ B = [1, 0, 1]
311
+ M = [1, 1, 0] # XOR, XOR, XNOR
312
+ R = trigate.infer(A, B, M)
313
+ print(f" A={A}, B={B}, M={M} -> R={R}")
314
+
315
+ # Test learning
316
+ print("\n2. Learning Test:")
317
+ A = [0, 1, 0]
318
+ B = [1, 0, 1]
319
+ R = [1, 1, 1]
320
+ M_learned = trigate.learn(A, B, R)
321
+ print(f" A={A}, B={B}, R={R} -> M={M_learned}")
322
+
323
+ # Test deduction
324
+ print("\n3. Deduction Test:")
325
+ M = [1, 1, 0]
326
+ R = [1, 1, 1]
327
+ A = [0, 1, 0]
328
+ B_deduced = trigate.deduce_b(M, R, A)
329
+ print(f" M={M}, R={R}, A={A} -> B={B_deduced}")
330
+
331
+ # Test with NULL values
332
+ print("\n4. NULL Propagation Test:")
333
+ A_null = [0, 1, None]
334
+ B_null = [1, 0, 1]
335
+ M_null = [1, 1, 1]
336
+ R_null = trigate.infer(A_null, B_null, M_null)
337
+ print(f" A={A_null}, B={B_null}, M={M_null} -> R={R_null}")
338
+
339
+ # Validate triangle closure
340
+ print("\n5. Triangle Closure Validation:")
341
+ is_valid = trigate.validate_triangle_closure([0, 1, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1])
342
+ print(f" Triangle is valid: {is_valid}")
343
+
344
+ print(f"\n6. Trigate Status: {trigate}")