--- /dev/null
+#!/usr/bin/env python3
+"""
+Symbol.py
+Epimetheus Symbol Implementation.
+Core Concept: A Symbol is a discrete, hashable set defined by its identity.
+"""
+
+import weakref
+
+class Symbol(set):
+ """
+ A persistent, unique identity that acts as a container.
+
+ Properties:
+ - Identity: Equality and Hashing are based on memory address (id).
+ - Container: Inherits from set. Can contain other symbols (differentiation).
+ - Hierarchy: Knows its parent to support dealloc().
+ """
+
+ def __init__(self, parent=None):
+ super().__init__()
+ # We hold a strong ref to the parent?
+ # If we hold strong, the root keeps the whole tree alive.
+ # If we hold weak, we can't dealloc if parent dies (but that's expected).
+ # Standard graph theory: Edges are usually strong.
+ self._parent = parent
+
+ def alloc(self):
+ """
+ Allocates a new differentiated symbol from this one.
+ The new symbol is added to this symbol (the set).
+ """
+ child = Symbol(parent=self)
+ self.add(child)
+ return child
+
+ def dealloc(self):
+ """
+ Removes this symbol from its parent.
+ If no other references exist, this symbol will be garbage collected.
+ """
+ if self._parent is not None:
+ self._parent.remove(self)
+ self._parent = None
+ # If parent is None (Root), dealloc does nothing.
+
+ # --- Identity Overrides (Force Set to be Hashable) ---
+
+ def __hash__(self):
+ return id(self)
+
+ def __eq__(self, other):
+ return self is other
+
+ def __repr__(self):
+ return f"<Symbol {id(self):x}>"
+
+# --- Example ---
+
+def example_symbol_lifecycle():
+ print("--- Symbol Lifecycle Example ---")
+ root = Symbol()
+
+ # 1. Root exists
+ print(f"Root: {root}")
+
+ # 2. Alloc Features
+ nav = root.alloc()
+ print(f"Allocated 'nav' inside root: {nav}")
+ print(f"root has nav? {nav in root}")
+
+ # 3. Alloc Leaf
+ left = nav.alloc()
+ print(f"Allocated 'left' inside nav: {left}")
+
+ # 4. Dealloc
+ print("Deallocating 'left'...")
+ left.dealloc()
+ print(f"nav has left? {left in nav} (Expected: False)")
+
+if __name__ == "__main__":
+ example_symbol_lifecycle()
+++ /dev/null
-class Symbol(set):
- """
- Epimetheus Symbol.
-
- Properties:
- 1. Identity: Each instance is unique (based on memory address).
- 2. Container: It is a Set. Differentiation puts child symbols inside parents.
- 3. Hashable: It uses id(self), allowing symbols to contain symbols.
- """
-
- def __hash__(self):
- # The distinctness of the symbol is its memory address (Process Local ID)
- return id(self)
-
- def __eq__(self, other):
- # Symbols are only equal if they are the same object
- return self is other
-
- def __repr__(self):
- # Hex address is the standard Python way to represent opaque identity
- return f"<Symbol {id(self):x}>"
-
-# --- The Factory ---
-
-class Epimetheus:
- @staticmethod
- def symbol():
- """Mints a new, unique Symbol."""
- return Symbol()
-
- @staticmethod
- def differentiate(parent_symbol):
- """
- Creates a new symbol that is a differentiation of the parent.
- The child is added to the parent's set.
- """
- child = Symbol()
- parent_symbol.add(child)
- return child
-
-# --- Usage Example ---
-
-def test_symbols():
- # 1. Mint a Root Symbol
- color = Epimetheus.symbol()
- print(f"Root: {color}")
-
- # 2. Differentiate
- red = Epimetheus.differentiate(color)
- blue = Epimetheus.differentiate(color)
-
- print(f"Red: {red}")
- print(f"Blue: {blue}")
-
- # 3. Verify Structure
- print(f"Color contains Red? {red in color}") # True
- print(f"Color contains Blue? {blue in color}") # True
- print(f"Red is Blue? {red == blue}") # False
-
- # 4. Nested Differentiation (Hierarchical)
- dark_red = Epimetheus.differentiate(red)
- print(f"Red contains DarkRed? {dark_red in red}") # True
- print(f"Color contains DarkRed? {dark_red in color}") # False (Direct containment only)
-
-if __name__ == "__main__":
- test_symbols()
#!/usr/bin/env python3
import sys
+from Symbol import Symbol
try:
import TM_module
print("Error: Import failed. Run 'python3 setup.py build_ext --inplace'")
sys.exit(1)
-class Features:
- # No features currently supported for Array TM
- pass
+# ==========================================
+# 1. The TM Stub (Callable Proxy)
+# ==========================================
-# The First Order TM Factory
-TM = TM_module.TM
+class TM_Factory_Stub:
+ """
+ A Proxy object that acts as both:
+ 1. The Namespace Root (holding .feature)
+ 2. The Callable Factory (delegating to an implementation)
+ """
+ def __init__(self):
+ self._impl = None
+
+ def __call__(self, *args, **kwargs):
+ if self._impl is None:
+ raise TypeError("TM factory logic not yet bound.")
+ return self._impl(*args, **kwargs)
+
+# Create the persistent TM object immediately
+TM = TM_Factory_Stub()
+
+# ==========================================
+# 2. Define Features (Directly on TM)
+# ==========================================
+
+# Create the namespace root
+TM.feature = Symbol()
+
+# Allocating features directly onto the persistent object.
+# Now we don't need temporary variables like _SR or _L.
+TM.feature.SR = TM.feature.alloc() # Step Right
+TM.feature.ND = TM.feature.alloc() # Non-Destructive
+TM.feature.L = TM.feature.alloc() # Mirror View
+
+# ==========================================
+# 3. The Implementation Logic
+# ==========================================
+
+def _tm_implementation(data_obj ,feature_seq=None):
+ """
+ The actual factory logic.
+ Now allows us to refer to 'TM.feature' directly inside the function.
+ """
+ # Optimization: Default Case
+ if not feature_seq: return TM_module.TM_Array_SR_ND(data_obj)
+
+ # Normalize
+ fs = set(feature_seq)
+
+ # Remove Defaults (Referring to the authoritative symbols directly)
+ fs.discard(TM.feature.SR)
+ fs.discard(TM.feature.ND)
+
+ # Check Empty
+ if not fs: return TM_module.TM_Array_SR_ND(data_obj)
+
+ # Check Mirror View
+ if TM.feature.L in fs:
+ fs.remove(TM.feature.L)
+ if not fs: return TM_module.TM_Array_ND(data_obj)
+
+ # Unknowns
+ raise ValueError(f"Unrecognized features: {fs}")
+
+# ==========================================
+# 4. Bind the Logic
+# ==========================================
+
+TM._impl = _tm_implementation
/*
TM_module.c
- CPython Extension: Tape Machine Factory
+ CPython Extension: Tape Machine Types
Implements:
- - TM·Array_SR_ND (Pointer-based, Solitary, Step Right, Non-Destructive)
-
- Style Note:
- - RT Naming Convention: TM·Class·Method
- - Uses UTF-8 center dot '·' for namespace separation.
+ - TM·Array_SR_ND
+ - TM·Array_ND
*/
+/* #define · _ */
+
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"
Py_TYPE(self)->tp_free((PyObject*)self);
}
-/* Helper: Refresh Pointers (Used on Init) */
static int refresh_pointers(FastTM* self){
if (!PyList_Check(self->tape_obj)) return -1;
-
Py_ssize_t len = PyList_GET_SIZE(self->tape_obj);
PyObject** items = ((PyListObject*)self->tape_obj)->ob_item;
-
self->start_ptr = items;
self->end_ptr = items + len;
- self->head_ptr = items; /* Initialize to start */
-
+ self->head_ptr = items;
return 0;
}
/* ========================================================= */
-/* 2. TM·Array_SR_ND Methods (Static Implementation) */
+/* 2. MIXINS */
/* ========================================================= */
-/* TM·Array_SR_ND·s: Step Right */
-static PyObject* TM·Array_SR_ND·s(FastTM* self){
+/* --- Navigation --- */
+static PyObject* Mixin·s(FastTM* self){
self->head_ptr++;
Py_RETURN_NONE;
}
-/* TM·Array_SR_ND·sn: Step N */
-static PyObject* TM·Array_SR_ND·sn(FastTM* self, PyObject* arg_tuple){
+static PyObject* Mixin·sn(FastTM* self, PyObject* arg_tuple){
Py_ssize_t n_val;
if( !PyArg_ParseTuple(arg_tuple, "n", &n_val) ) return NULL;
-
- if (n_val < 0) {
- PyErr_SetString(PyExc_ValueError, "Step Right machine supports positive steps only.");
- return NULL;
- }
self->head_ptr += n_val;
Py_RETURN_NONE;
}
-/* TM·Array_SR_ND·LsR: Rewind */
-static PyObject* TM·Array_SR_ND·LsR(FastTM* self){
+static PyObject* Mixin·ls(FastTM* self){
+ self->head_ptr--;
+ Py_RETURN_NONE;
+}
+
+static PyObject* Mixin·LsR(FastTM* self){
self->head_ptr = self->start_ptr;
Py_RETURN_NONE;
}
-/* TM·Array_SR_ND·r: Read */
-static PyObject* TM·Array_SR_ND·r(FastTM* self){
+static PyObject* Mixin·sR(FastTM* self){
+ self->head_ptr = self->end_ptr - 1;
+ Py_RETURN_NONE;
+}
+
+/* --- I/O --- */
+static PyObject* Mixin·r(FastTM* self){
PyObject* item = *(self->head_ptr);
Py_INCREF(item);
return item;
}
-/* TM·Array_SR_ND·w: Write */
-static PyObject* TM·Array_SR_ND·w(FastTM* self, PyObject* val_obj){
+static PyObject* Mixin·w(FastTM* self, PyObject* val_obj){
PyObject* old_val = *(self->head_ptr);
Py_INCREF(val_obj);
*(self->head_ptr) = val_obj;
Py_RETURN_NONE;
}
-/* TM·Array_SR_ND·qR: Query Rightmost */
-static PyObject* TM·Array_SR_ND·qR(FastTM* self){
+/* --- Queries --- */
+static PyObject* Mixin·qR(FastTM* self){
if( self->head_ptr >= (self->end_ptr - 1) ) Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
-/* TM·Array_SR_ND·address: Get Index */
-static PyObject* TM·Array_SR_ND·address(FastTM* self){
+static PyObject* Mixin·qL(FastTM* self){
+ if( self->head_ptr <= self->start_ptr ) Py_RETURN_TRUE;
+ Py_RETURN_FALSE;
+}
+
+static PyObject* Mixin·address(FastTM* self){
Py_ssize_t idx = self->head_ptr - self->start_ptr;
return PyLong_FromSsize_t(idx);
}
/* ========================================================= */
-/* 3. TM·Array_SR_ND Init */
+/* 3. INITIALIZATION */
/* ========================================================= */
-static int TM·Array_SR_ND·init(FastTM* self, PyObject* args, PyObject* kwds){
+static int Common·init(FastTM* self, PyObject* args, PyObject* kwds){
PyObject* input_obj = NULL;
- PyObject* features_obj = NULL;
-
- if( !PyArg_ParseTuple(args, "O|O", &input_obj, &features_obj) ) return -1;
+ /* Accepts 1 argument: The List */
+ if( !PyArg_ParseTuple(args, "O", &input_obj) ) return -1;
- if( !PyList_Check(input_obj) ){
- PyErr_SetString(PyExc_TypeError, "Array TM requires a list data object.");
- return -1;
- }
-
- if (PyList_Size(input_obj) == 0) {
- PyErr_SetString(PyExc_ValueError, "First Order TM cannot be empty.");
+ if( !PyList_Check(input_obj) || PyList_Size(input_obj) == 0 ){
+ PyErr_SetString(PyExc_ValueError, "TM requires non-empty list.");
return -1;
}
self->tape_obj = input_obj;
Py_INCREF(self->tape_obj);
-
refresh_pointers(self);
-
return 0;
}
/* ========================================================= */
-/* 4. TYPE DEFINITION */
+/* 4. TYPES */
/* ========================================================= */
+/* TM·Array_SR_ND */
static PyMethodDef TM·Array_SR_ND·methods[] = {
- {"s", (PyCFunction)TM·Array_SR_ND·s, METH_NOARGS, "Step Right"},
- {"sn", (PyCFunction)TM·Array_SR_ND·sn, METH_VARARGS, "Step N"},
- {"r", (PyCFunction)TM·Array_SR_ND·r, METH_NOARGS, "Read"},
- {"w", (PyCFunction)TM·Array_SR_ND·w, METH_O, "Write"},
- {"qR", (PyCFunction)TM·Array_SR_ND·qR, METH_NOARGS, "Query Rightmost"},
- {"LsR", (PyCFunction)TM·Array_SR_ND·LsR, METH_NOARGS, "Rewind"},
- {"address", (PyCFunction)TM·Array_SR_ND·address, METH_NOARGS, "Get Index"},
+ {"s", (PyCFunction)Mixin·s, METH_NOARGS, ""},
+ {"sn", (PyCFunction)Mixin·sn, METH_VARARGS, ""},
+ {"r", (PyCFunction)Mixin·r, METH_NOARGS, ""},
+ {"w", (PyCFunction)Mixin·w, METH_O, ""},
+ {"qR", (PyCFunction)Mixin·qR, METH_NOARGS, ""},
+ {"LsR", (PyCFunction)Mixin·LsR, METH_NOARGS, ""},
+ {"address", (PyCFunction)Mixin·address, METH_NOARGS, ""},
{NULL}
};
.tp_basicsize = sizeof(FastTM),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
.tp_new = PyType_GenericNew,
- .tp_init = (initproc)TM·Array_SR_ND·init,
+ .tp_init = (initproc)Common·init,
.tp_dealloc = (destructor)FastTM_dealloc,
.tp_methods = TM·Array_SR_ND·methods,
};
-/* ========================================================= */
-/* 5. FACTORY */
-/* ========================================================= */
-
-static PyObject* TM·Factory(PyObject* self, PyObject* args, PyObject* kwds){
- PyObject* input_obj = NULL;
- PyObject* features_obj = NULL;
-
- if( !PyArg_ParseTuple(args, "O|O", &input_obj, &features_obj) ) return NULL;
-
- /* Check Features (Reject incompatible ones) */
- if( features_obj && PyList_Check(features_obj) ){
- Py_ssize_t size = PyList_Size(features_obj);
- for( Py_ssize_t i=0; i<size; i++ ){
- PyObject* item = PyList_GetItem(features_obj, i);
- if( PyUnicode_Check(item) ){
- const char* s = PyUnicode_AsUTF8(item);
- if( s && strcmp(s, "aR") == 0 ) {
- PyErr_SetString(PyExc_TypeError, "Feature 'aR' is incompatible with Array TMs.");
- return NULL;
- }
- }
- }
- }
-
- /* Dispatch to TM·Array_SR_ND if input is List */
- if (!PyList_Check(input_obj)) {
- PyErr_SetString(PyExc_TypeError, "TM constructor requires a List container.");
- return NULL;
- }
-
- PyObject* arg_tuple = PyTuple_Pack(2, input_obj, features_obj ? features_obj : Py_None);
- PyObject* obj = PyObject_CallObject((PyObject*)&TM·Array_SR_ND·Type, arg_tuple);
- Py_DECREF(arg_tuple);
-
- return obj;
-}
+/* TM·Array_ND */
+static PyMethodDef TM·Array_ND·methods[] = {
+ {"s", (PyCFunction)Mixin·s, METH_NOARGS, ""},
+ {"sn", (PyCFunction)Mixin·sn, METH_VARARGS, ""},
+ {"ls", (PyCFunction)Mixin·ls, METH_NOARGS, ""},
+ {"sR", (PyCFunction)Mixin·sR, METH_NOARGS, ""},
+ {"LsR", (PyCFunction)Mixin·LsR, METH_NOARGS, ""},
+ {"qR", (PyCFunction)Mixin·qR, METH_NOARGS, ""},
+ {"qL", (PyCFunction)Mixin·qL, METH_NOARGS, ""},
+ {"r", (PyCFunction)Mixin·r, METH_NOARGS, ""},
+ {"w", (PyCFunction)Mixin·w, METH_O, ""},
+ {"address", (PyCFunction)Mixin·address, METH_NOARGS, ""},
+ {NULL}
+};
-static PyMethodDef module_methods[] = {
- {"TM", (PyCFunction)TM·Factory, METH_VARARGS | METH_KEYWORDS, "TM Factory"},
- {NULL, NULL, 0, NULL}
+static PyTypeObject TM·Array_ND·Type = {
+ PyVarObject_HEAD_INIT(NULL, 0)
+ .tp_name = "TM_module.TM_Array_ND",
+ .tp_doc = "Array TM: Pointer-based, Solitary, Bidirectional, ND",
+ .tp_basicsize = sizeof(FastTM),
+ .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
+ .tp_new = PyType_GenericNew,
+ .tp_init = (initproc)Common·init,
+ .tp_dealloc = (destructor)FastTM_dealloc,
+ .tp_methods = TM·Array_ND·methods,
};
+/* ========================================================= */
+/* 5. MODULE INIT */
+/* ========================================================= */
+
static PyModuleDef TM_module = {
- PyModuleDef_HEAD_INIT, "TM_module", "Fast TM Extension", -1, module_methods
+ PyModuleDef_HEAD_INIT, "TM_module", "Fast TM Types", -1, NULL
};
PyMODINIT_FUNC PyInit_TM_module(void){
PyObject* m_obj;
if( PyType_Ready(&TM·Array_SR_ND·Type) < 0 ) return NULL;
+ if( PyType_Ready(&TM·Array_ND·Type) < 0 ) return NULL;
m_obj = PyModule_Create(&TM_module);
if( !m_obj ) return NULL;
Py_INCREF(&TM·Array_SR_ND·Type);
PyModule_AddObject(m_obj, "TM_Array_SR_ND", (PyObject*)&TM·Array_SR_ND·Type);
+
+ Py_INCREF(&TM·Array_ND·Type);
+ PyModule_AddObject(m_obj, "TM_Array_ND", (PyObject*)&TM·Array_ND·Type);
+
return m_obj;
}
+++ /dev/null
-#!/usr/bin/env python3
-import sys
-from TM import TM ,Topology
-
-def CLI():
- print("--- TM Happy Path (example_TM_0) ---")
-
- # 1. Initialization
- # ---------------------------------------------------------
- print("\n[1] Initialization")
- data_list = [10 ,20 ,30 ,40 ,50]
- tm_0 = TM(data_list)
- print(f"Created TM with: {data_list}")
- print(f"Address: {tm_0.address()} (Should be 0)")
- print(f"Length: {tm_0.len()} (Should be 5)")
-
- # 2. Read / Step / Write
- # ---------------------------------------------------------
- print("\n[2] Movement and IO")
-
- # Read current (0)
- val = tm_0.r()
- print(f"r(): {val} (Exp: 10)")
-
- # Step 1, Read
- tm_0.s()
- print(f"s() -> r(): {tm_0.r()} (Exp: 20)")
-
- # Write
- tm_0.w(99)
- print(f"w(99) -> r(): {tm_0.r()} (Exp: 99)")
-
- # Step N
- tm_0.sn(2)
- print(f"sn(2) -> r(): {tm_0.r()} (Exp: 40)") # 0->1->3 (Indices: 0, 1, 2, 3)
-
- # Step Left
- tm_0.ls()
- print(f"ls() -> r(): {tm_0.r()} (Exp: 30)")
-
- # Bulk Write (wn)
- # Current head is at index 2 (val 30)
- # Write [33, 44] -> overwrites 30, 40
- tm_0.wn([33 ,44])
- print("wn([33 ,44])")
-
- # Bulk Read (rn)
- read_back = tm_0.rn(2)
- print(f"rn(2): {read_back} (Exp: [33, 44])")
-
- # 3. Allocation
- # ---------------------------------------------------------
- print("\n[3] Allocation")
-
- # Append Right (aR)
- tm_0.aR(60)
- print(f"aR(60) -> len: {tm_0.len()} (Exp: 6)")
-
- # Append Left (aL)
- # Head is at index 2.
- # aL inserts at 0. Indices shift right.
- # Head should increment to 3 to stay on '33'.
- print(f"Pre-aL Head: {tm_0.address()}")
- tm_0.aL(0)
- print(f"aL(0) -> Head: {tm_0.address()} (Exp: 3)")
- print(f"Value at Head: {tm_0.r()} (Exp: 33)")
-
- # Check 0 index
- tm_0.lsn(3) # Go to 0
- print(f"Value at 0: {tm_0.r()} (Exp: 0)")
-
- # 4. Deletion
- # ---------------------------------------------------------
- print("\n[4] Deletion")
-
- # Current Tape: [0, 10, 99, 33, 44, 50, 60]
- # Head at 0.
-
- # esd (Delete Neighbor -> 10)
- tm_0.esd()
- print(f"esd() -> Tape[1] should be 99. r(2): {tm_0.rn(2)} (Exp: [0, 99])")
-
- # d (Delete Current -> 0)
- tm_0.d()
- # Head stays at 0, which is now 99
- print(f"d() -> Current: {tm_0.r()} (Exp: 99)")
-
- # 5. Cloning (Entanglement)
- # ---------------------------------------------------------
- print("\n[5] Cloning")
- tm_clone = tm_0.e()
- print("Created tm_clone from tm_0")
-
- # Modify tm_0, check tm_clone
- tm_0.w(999)
- print(f"tm_0.w(999)")
- print(f"tm_clone.r(): {tm_clone.r()} (Exp: 999)")
-
- print("\n--- end of examples ---")
-
-if __name__ == "__main__":
- CLI()
-
-
+++ /dev/null
-#!/usr/bin/env python3
-import sys
-from TM import TM
-
-def CLI():
- print("--- TM Edge Cases (example_TM_1) ---")
-
- # 1. Entanglement Violation (Safety Check)
- # ---------------------------------------------------------
- print("\n[1] Entanglement Violation (Peer on Victim)")
-
- t1 = TM(['A' ,'B' ,'C'])
- t2 = t1.e() # Entangled Clone
-
- # Setup:
- # t1 at 0 ('A')
- # t2 moves to 1 ('B')
- t2.s()
- print(f"Setup: t1@{t1.address()}, t2@{t2.address()}")
-
- print("Action: t1.esd() -> Tries to delete 'B'")
- print("Expect: RuntimeError (Entanglement Violation)")
-
- try:
- t1.esd()
- print("!! FAILED: Operation succeeded (Should have failed)")
- except RuntimeError as e:
- print(f">> CAUGHT EXPECTED ERROR: {e}")
-
- # 2. Entanglement Violation (Peer on Current)
- # ---------------------------------------------------------
- print("\n[2] Entanglement Violation (Peer on Current)")
-
- # t1 at 0. t2 at 1.
- # Move t2 back to 0. Both at 0.
- t2.ls()
- print(f"Setup: t1@{t1.address()}, t2@{t2.address()}")
-
- print("Action: t1.d() -> Tries to delete 'A'")
- print("Expect: RuntimeError")
-
- try:
- t1.d()
- print("!! FAILED: Operation succeeded")
- except RuntimeError as e:
- print(f">> CAUGHT EXPECTED ERROR: {e}")
-
- # 3. Safe Deletion (No Peer Collision)
- # ---------------------------------------------------------
- print("\n[3] Safe Deletion (Peer Safe)")
-
- # t1 at 0 ('A'), t2 at 0 ('A').
- # Move t2 to 2 ('C').
- t2.sn(2)
- print(f"Setup: t1@{t1.address()} ('A'), t2@{t2.address()} ('C')")
-
- # t1 deletes 'B' (neighbor). 'B' is at index 1.
- # t2 is at index 2. Safe?
- # Yes. t2 is not ON the cell being deleted.
- # Note: t2's data will shift left index-wise, but Entanglement check
- # only cares if t2 is *on* the deleted cell.
-
- print("Action: t1.esd() -> Delete 'B'")
- t1.esd()
- print(">> Success (Operation Permitted)")
- print(f"Tape is now: {t1.rn(2)}")
-
- # 4. Map Input (Materialization)
- # ---------------------------------------------------------
- print("\n[4] Map Input")
- data_map = {'key1': 1 , 'key2': 2}
- tm_map = TM(data_map)
- print(f"TM from Map keys: {tm_map.rn(2)}")
-
- print("\n--- Finished ---")
-
-if __name__ == "__main__":
- CLI()
-
+++ /dev/null
-#!/usr/bin/env python3
-from TM import TM
-
-def test_base_machine():
- print("--- TM·Array_SR_ND Verification ---")
-
- data = [10, 20, 30]
- tm = TM(data)
- print(f"Created TM. Data: {data}")
-
- # Forward Scan
- print("\n[Forward Scan]")
- while True:
- print(f"Read: {tm.r()}")
- if tm.qR(): break
- tm.s()
-
- # Rewind
- print("\n[Rewind]")
- tm.LsR()
- print(f"After LsR, Read: {tm.r()} (Expected: 10)")
-
- # Write
- tm.w(999)
- print(f"Wrote 999. Read: {tm.r()} (Expected: 999)")
-
-if __name__ == "__main__":
- test_base_machine()
+++ /dev/null
-#!/usr/bin/env python3
-from TM import TMS, Features
-
-def test_ar_machine():
- print("--- TM_ARRAY_SR_ND_aR Verification ---")
-
- # 1. Initialization with Feature (Mandatory Data)
- data = [10, 20, 30]
- t = TMS(data, features=[Features.APPEND_RIGHT])
-
- print(f"Created Machine t1. Len: {t.len()}")
-
- # 2. Test Append on t1
- t.s() # Step to 20
- print("Executing t1.aR(99)...")
- t.aR(99)
- print(f"t1 Len: {t.len()} (Expected: 4)")
- print(f"t1 Content from Head: {t.rn(3)} (Expected: [20, 30, 99])")
-
- # 3. Test Entanglement (Shared Tape)
- # ---------------------------------------------------------
- t2 = t.e()
- print("\nCreated entangled machine t2 from t1.")
-
- print("Executing t2.aR(100)...")
- t2.aR(100)
-
- # Verify t2 (The actor)
- print(f"t2 Len: {t2.len()} (Expected: 5)")
-
- # Verify t1 (The observer) - PROOF OF ENTANGLEMENT
- # t1 should see the change immediately because the tape is shared.
- print(f"t1 Len: {t.len()} (Expected: 5)")
-
- if t.len() == 5:
- print(">> SUCCESS: t1 reflects change made by t2 (Tape is shared).")
- else:
- print("!! FAIL: t1 did not see the change (Tape is copied?).")
-
- # 4. Verify Base Restrictions
- try:
- t.ls()
- print("!! FAIL: ls() succeeded")
- except AttributeError:
- print(">> SUCCESS: ls() blocked.")
-
-if __name__ == "__main__":
- test_ar_machine()
+++ /dev/null
-#!/usr/bin/env python3
-from TM import TM, TMS, Features
-
-def test_base_machine():
- print("\n--- Test 1: Base Machine (TM_SR_ND) ---")
- data = [10, 20, 30]
-
- # No features requested
- t = TMS(data)
- print(f"Created Base Machine: {t.len()} items.")
-
- # 1. Step & Read (Should work)
- t.s()
- print(f"Step -> Val: {t.r()} (Expected: 20)")
-
- # 2. Try Append (Should FAIL)
- print("Attempting aR()...")
- try:
- t.aR(99)
- print("!! FAIL: aR() succeeded on Base Machine")
- except AttributeError:
- print(">> SUCCESS: Caught expected AttributeError (Feature missing)")
-
-def test_ar_machine():
- print("\n--- Test 2: Feature Machine (TM_SR_ND_AR) ---")
- data = [10, 20, 30]
-
- # Feature requested
- t = TMS(data, features=[Features.APPEND_RIGHT])
- print(f"Created Feature Machine: {t.len()} items.")
-
- # 1. Step
- t.s()
-
- # 2. Append (Should WORK)
- print("Attempting aR(99)...")
- try:
- t.aR(99)
- print(f">> SUCCESS: aR() completed. New Len: {t.len()}")
-
- # Verify data
- print(f"Tape content (from head): {t.rn(5)}")
- except AttributeError as e:
- print(f"!! FAIL: {e}")
-
- # 3. Entanglement Check
- print("Entangling...")
- t2 = t.e()
- print("Attempting aR(100) on Clone...")
- try:
- t2.aR(100)
- print(f">> SUCCESS: Clone inherited aR feature. Len: {t2.len()}")
- except AttributeError:
- print("!! FAIL: Clone lost the feature!")
-
-if __name__ == "__main__":
- test_base_machine()
- test_ar_machine()
-
+++ /dev/null
-#!/usr/bin/env python3
-from SymbolSpace import SymbolSpace
-from Binder import Binder
-from DiscreteFunction import DiscreteFunction
-from Namespace import DifferentiatedSymbol ,OrderedNamespace
-
-def example_queries():
- print("--- Epimetheus Architecture Example ---")
-
- # 1. System Initialization
- binder = Binder()
- graph = DiscreteFunction()
-
- # 2. Ontology Definition (The Factories)
- Frame = DifferentiatedSymbol("FrameMaterial")
- Price = OrderedNamespace("Price")
-
- # 3. Data Ingestion (Transient Objects)
- data_source = [
- ("Bike_A" ,"Carbon" ,3500),
- ("Bike_B" ,"Steel" ,800),
- ("Bike_C" ,"Alum" ,1200),
- ("Bike_D" ,"Carbon" ,1500),
- ]
-
- print(f"Ingesting {len(data_source)} items...")
-
- # Keep references to prevent GC during ingestion for this example
- start_objects = []
-
- for label, material, cost in data_source:
- # A. Create the Python Object
- obj = type("Bike", (), {"label": label})()
- start_objects.append(obj)
-
- # B. Bind: Object -> Symbol
- sym_bike = binder.get_symbol(obj)
-
- # C. Describe: Symbol -> Properties
- graph.set(sym_bike ,Frame(material))
- graph.set(sym_bike ,Price(cost))
-
- # ---------------------------------------------------------
- # Example 1: Exact Query ("Find Carbon Frames")
- # ---------------------------------------------------------
- print("\n[Example 1] Exact Match: Frame('Carbon')")
-
- # We ask the Factory for the symbol representing 'Carbon'
- sym_carbon = Frame("Carbon")
-
- # We ask the Graph for entities with that symbol
- results = graph.find(sym_carbon)
- print(f" -> Found {len(results)} bikes with Carbon frames.")
-
- # ---------------------------------------------------------
- # Example 2: Range Query ("Find Price 1000..2000")
- # ---------------------------------------------------------
- print("\n[Example 2] Range Match: Price(1000..2000)")
-
- # Step A: Ask Namespace for symbols in range
- # The OrderedNamespace uses bisect to find symbols efficiently
- price_symbols = Price.find_range(1000 ,2000)
- print(f" -> Namespace identified {len(price_symbols)} relevant price points.")
-
- # Step B: Ask Graph for objects having ANY of those symbols
- matches = set()
- for p_sym in price_symbols:
- found = graph.find(p_sym)
- matches.update(found)
-
- print(f" -> Graph resolved {len(matches)} bikes in price range.")
-
- # ---------------------------------------------------------
- # Example 3: Hierarchy Query ("Find Priced Things")
- # ---------------------------------------------------------
- print("\n[Example 3] Hierarchy Match: Has Price")
-
- # We query the Root Symbol of the Price namespace.
- # This works because the Graph automatically 'posts' up to the parent.
- # FIXED: Changed .root to .root_symbol to match Namespace.py
- all_priced = graph.find(Price.root_symbol)
- print(f" -> Found {len(all_priced)} objects that have a price.")
-
-def CLI():
- example_queries()
-
-if __name__ == "__main__":
- CLI()
+++ /dev/null
-#!/usr/bin/env python3
-from TM import TMS, RegionMachine
-
-def test_region():
- print("--- Region Machine Verification ---")
-
- # Tape: [10, 20, 30, 40, 50]
- t = TMS([10, 20, 30, 40, 50])
-
- # Create Region. Initially Boundaries are at 0 (start).
- # Region is [0, 0] (Single Cell).
- rm = RegionMachine(t)
-
- print("Region Initialized [0, 0].")
- print(f"qL: {rm.qL()} (Exp: True)")
- print(f"qR: {rm.qR()} (Exp: True)")
-
- # Expand Region: Move Right Boundary to index 2
- print("Expanding Right Boundary to index 2...")
- rm.t_right.sn(2)
-
- # Region is now [0, 2] (Indices 0, 1, 2)
- print(f"qR (Active at 0): {rm.qR()} (Exp: False)")
-
- # Move Active Head
- rm.s() # To 1
- print(f"Active at 1. Val: {rm.r()}")
- rm.s() # To 2
- print(f"Active at 2. Val: {rm.r()}")
-
- print(f"qR (Active at 2): {rm.qR()} (Exp: True)")
-
- # Try to step out of region
- print("Attempting to step past Right Boundary...")
- try:
- rm.s()
- print("!! FAIL: Stepped out of region!")
- except RuntimeError as e:
- print(f">> SUCCESS: Blocked by Boundary. ({e})")
-
-if __name__ == "__main__":
- test_region()
-