Sunday, September 13, 2026

The UPC Visual Simulator: Real-Time Desktop Wave Visual for Semantic Collapse

The Universal Principle of Collapse (UPC) Visual Simulator is a desktop Python application that lets you watch text frames transition step-by-step from an uncollapsed semantic wave into a locked classical trace. As the operator chain progresses through potential vectors, model partitioning, and recognition thresholds, an interactive wave display dampens in real time before resolving into eigenstate proximity bars and structured JSON logs. For quick, no-install testing in a browser, you can explore the Live Browser Circuit Simulator, or check out the background methodology on the UPC Visual Simulator Blog Edition.




import json
import re
import threading
import time
import webbrowser
import tkinter as tk
from tkinter import font as tkfont, messagebox, Toplevel
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

EIGENSTATE_ANCHORS = {
    "State_A": [
        "I recognize the boundary conditions of this system and acknowledge the structural constraints.",
        "The model frame is explicitly defined, and I am auditing the underlying assumptions.",
        "Acknowledging the limits of the current measurement framework and integrating the boundary."
    ],
    "T_phantom": [
        "That is completely absurd and refuted by standard common sense.",
        "You are using logical fallacies, everyone knows this was already disproven.",
        "You're just making things up to sound smart, classic bad faith argument."
    ],
    "T_mechanized": [
        "As an AI language model, I cannot provide personal opinions on this topic.",
        "Furthermore, it is important to consider multiple perspectives on this complex issue.",
        "In summary, while there are valid arguments on both sides, further research is required."
    ],
    "T_visceral": [
        "Shut up you idiot, you don't know what you are talking about!",
        "Total trash post, absolute nonsense and complete garbage.",
        "Get out of here with this ridiculous rubbish, complete fake news!"
    ],
    "T_outlier": [
        "Purple monkey dishwasher banana flying across the blue quantum soup.",
        "X7#q9! random noise string with zero semantic correlation to the domain.",
        "Unrelated tangential babble ignoring all prior context completely."
    ]
}

class DesktopUPCEngine:
    def __init__(self):
        # Using char_wb n-grams (2, 5) to prevent zero-vector dropouts on short or colloquial inputs
        self.vectorizer = TfidfVectorizer(analyzer='char_wb', ngram_range=(2, 5))
        corpus = []
        for phrases in EIGENSTATE_ANCHORS.values():
            corpus.extend(phrases)
        self.vectorizer.fit(corpus)
        
        self.anchor_embeddings = {}
        for state, phrases in EIGENSTATE_ANCHORS.items():
            vecs = self.vectorizer.transform(phrases).toarray()
            self.anchor_embeddings[state] = np.mean(vecs, axis=0).reshape(1, -1)

    def evaluate(self, input_text):
        if not input_text.strip(): return {}
        po_vector = self.vectorizer.transform([input_text]).toarray()
        
        macro_scores = {
            state: float(cosine_similarity(po_vector, vec)[0][0]) + 1e-5 
            for state, vec in self.anchor_embeddings.items()
        }
        
        sentences = [s.strip() for s in re.split(r'[.!?]+', input_text) if len(s.strip()) > 1]
        sentence_scores_sum = {state: 0.0 for state in EIGENSTATE_ANCHORS.keys()}
        sentence_subtotals = []

        if sentences:
            for s in sentences:
                s_vec = self.vectorizer.transform([s]).toarray()
                s_scores = {
                    state: float(cosine_similarity(s_vec, self.anchor_embeddings[state])[0][0]) + 1e-5
                    for state in EIGENSTATE_ANCHORS.keys()
                }
                for state, sc in s_scores.items(): 
                    sentence_scores_sum[state] += sc
                sentence_subtotals.append({
                    "sentence": s,
                    "collapsed_state": max(s_scores, key=s_scores.get),
                    "scores": s_scores
                })
            sentence_averages = {st: sentence_scores_sum[st] / len(sentences) for st in sentence_scores_sum}
        else:
            sentence_averages = macro_scores.copy()

        composite_scores = {
            state: float((macro_scores[state] * 0.5) + (sentence_averages[state] * 0.5)) 
            for state in EIGENSTATE_ANCHORS.keys()
        }
        collapsed_state = max(composite_scores, key=composite_scores.get)

        return {
            "operator_chain": "(C o Jo o LO o s o MO)|PO>",
            "input_text": input_text,
            "collapsed_eigenstate": collapsed_state,
            "composite_scores": composite_scores,
            "macro_scores": macro_scores,
            "sentence_count": len(sentences),
            "sentence_subtotals": sentence_subtotals,
            "metrological_status": "LOCKED" if collapsed_state == "State_A" else "UN_AUDITED_SCRIPT"
        }

class UPCVisualSimulator(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Universal Principle of Collapse — Desktop Visual Simulator")
        self.geometry("1000x740")
        self.minsize(920, 680)
        self.configure(bg="#121212")
        self.resizable(True, True)

        self.engine = DesktopUPCEngine()
        self.operators = ["PO", "MO", "s", "LO", "Jo", "C", "T"]
        self.eigenstates = ["State_A", "T_phantom", "T_mechanized", "T_visceral", "T_outlier"]
        self.current_step = 0
        self.is_running = False

        self.descriptions = {
            "PO": "Uncollapsed Potential Vector (|PO> ↔ |Ψ>): Initial input loaded into semantic Hilbert space.",
            "MO": "Model Operator (MO ↔ POVM): TF-IDF/Dense logic partitions space into observable sectors.",
            "s": "Salience Pulse (s ↔ P(k)): Calculates Born weights across active attention channels.",
            "LO": "Articulation Operator (LO ↔ Pk): Projection operators fix articulated distinctions. [QM Hardware Stops Here!]",
            "Jo": "Recognition Operator (Jo ↔ ∅): Meaning-bearing observer evaluates boundary alignment and agency threshold.",
            "C": "Collapse Operator (C ↔ |k>): Frame reduction fixes the dominant eigenstate.",
            "T": "Classical Trace (T ↔ ak): Immutable measurement record externalized into classical reality."
        }

        self.build_ui()
        self.render_state(0)

    def build_ui(self):
        main_frame = tk.Frame(self, bg="#1e1e1e", padx=15, pady=15)
        main_frame.pack(fill="both", expand=True, padx=10, pady=10)

        header_row = tk.Frame(main_frame, bg="#1e1e1e")
        header_row.pack(fill="x", pady=(0, 6))
        tk.Label(header_row, text="Universal Principle of Collapse", bg="#1e1e1e", fg="#b0bec5", font=("Segoe UI", 11, "bold")).pack(side="left")
        
        btn_info = tk.Button(header_row, text="INFO", bg="#333335", fg="#4FC3F7", font=("Segoe UI", 7, "bold"), relief="flat", padx=10, pady=2, command=self.open_info_popup)
        btn_info.pack(side="right")

        top_row = tk.Frame(main_frame, bg="#1e1e1e")
        top_row.pack(fill="x", pady=(0, 8))

        self.text_input = tk.Text(top_row, height=3, bg="#0d0d0d", fg="#ffffff", insertbackground="white", font=("Segoe UI", 9), relief="flat", padx=8, pady=8)
        self.text_input.pack(side="left", fill="both", expand=True, padx=(0, 10))
        self.text_input.insert("1.0", "I recognize the boundary conditions of this system and acknowledge the structural constraints.")
        self.setup_text_widget_context_menu(self.text_input)

        btn_frame = tk.Frame(top_row, bg="#1e1e1e")
        btn_frame.pack(side="right", fill="y")

        self.btn_step = tk.Button(btn_frame, text="STEP", bg="#e0e0e0", fg="#121212", font=("Segoe UI", 8, "bold"), relief="flat", width=12, command=self.step_simulation)
        self.btn_step.pack(pady=2)

        self.btn_auto = tk.Button(btn_frame, text="AUTO-RUN", bg="#e0e0e0", fg="#121212", font=("Segoe UI", 8, "bold"), relief="flat", width=12, command=self.run_auto_play)
        self.btn_auto.pack(pady=2)

        self.btn_reset = tk.Button(btn_frame, text="RESET", bg="#e0e0e0", fg="#121212", font=("Segoe UI", 8, "bold"), relief="flat", width=12, command=self.reset_simulation)
        self.btn_reset.pack(pady=2)

        self.top_pills_frame = tk.Frame(main_frame, bg="#252526", padx=10, pady=5)
        self.top_pills_frame.pack(fill="x", pady=(0, 8))
        self.top_pill_labels = {}
        for op in self.operators:
            lbl = tk.Label(self.top_pills_frame, text=op, font=("Segoe UI", 8, "bold"), bg="#252526", fg="#757575", padx=10, pady=2)
            lbl.pack(side="left", expand=True)
            self.top_pill_labels[op] = lbl

        info_banner = tk.Label(main_frame, text="Operator Wave Progression & Collapse Field (PO → MO → s → LO → Jo → C → T)", bg="#1e1e1e", fg="#888888", font=("Segoe UI", 7, "italic"), anchor="w")
        info_banner.pack(fill="x", pady=(0, 3))

        self.canvas = tk.Canvas(main_frame, width=850, height=140, bg="#f4f6f9", highlightthickness=1, highlightbackground="#333")
        self.canvas.pack(fill="x", pady=(0, 6))

        self.status_label = tk.Label(main_frame, text="System ready. Press STEP or AUTO-RUN to trace operator progression.", bg="#1e1e1e", fg="#4FC3F7", font=("Segoe UI", 8, "italic"), anchor="w")
        self.status_label.pack(fill="x", pady=(0, 6))

        chain_frame = tk.Frame(main_frame, bg="#1e1e1e")
        chain_frame.pack(fill="x", pady=(0, 8))
        self.chain_buttons = {}
        for idx, op in enumerate(self.operators):
            btn = tk.Button(chain_frame, text=op, bg="#2a2a2c", fg="#b0bec5", font=("Segoe UI", 8, "bold"), relief="flat", command=lambda i=idx: self.manual_select_step(i))
            btn.pack(side="left", expand=True, fill="x", padx=2, ipady=4)
            self.chain_buttons[op] = btn

        split_frame = tk.Frame(main_frame, bg="#1e1e1e")
        split_frame.pack(fill="both", expand=True, pady=(0, 8))

        left_sub = tk.Frame(split_frame, bg="#1e1e1e")
        left_sub.pack(side="left", fill="both", expand=True, padx=(0, 5))
        tk.Label(left_sub, text="JSON Trace Output", bg="#1e1e1e", fg="#b0bec5", font=("Segoe UI", 8, "bold")).pack(anchor="w", pady=(0, 3))
        self.json_output = tk.Text(left_sub, height=8, bg="#0d0d0d", fg="#00E676", font=("Consolas", 8), relief="flat", padx=8, pady=6)
        self.json_output.pack(fill="both", expand=True)
        self.json_output.insert("1.0", "// Trace output JSON pending execution...")
        self.setup_text_widget_context_menu(self.json_output)

        right_sub = tk.Frame(split_frame, bg="#252526", padx=10, pady=8, relief="flat")
        right_sub.pack(side="right", fill="both", expand=True, padx=(5, 0))
        tk.Label(right_sub, text="Eigenstate Proximity Bars (Populates at C / T)", bg="#252526", fg="#b0bec5", font=("Segoe UI", 8, "bold")).pack(anchor="w", pady=(0, 6))

        self.bar_rows = {}
        for state in self.eigenstates:
            row_f = tk.Frame(right_sub, bg="#252526")
            row_f.pack(fill="x", pady=3)
            lbl = tk.Label(row_f, text=state, width=13, anchor="w", bg="#252526", fg="#e0e0e0", font=("Consolas", 7, "bold"))
            lbl.pack(side="left")
            
            c_f = tk.Frame(row_f, bg="#1e1e1e", height=14)
            c_f.pack(side="left", fill="x", expand=True, padx=4)
            bar = tk.Frame(c_f, bg="#2962FF", width=1, height=14)
            bar.place(x=0, y=0, relheight=1)
            
            val_lbl = tk.Label(row_f, text="0.000", width=6, anchor="e", bg="#252526", fg="#4FC3F7", font=("Consolas", 7))
            val_lbl.pack(side="right")
            self.bar_rows[state] = (bar, c_f, val_lbl)

        footer = tk.Label(main_frame, text="ELOY ESCAGEDO GUTIERREZ ALL RIGHTS RESERVED", bg="#1e1e1e", fg="#888", font=("Segoe UI", 7, "bold"))
        footer.pack(pady=(4, 0))

    def setup_text_widget_context_menu(self, text_widget):
        context_menu = tk.Menu(text_widget, tearoff=0, bg="#252526", fg="#ffffff")
        context_menu.add_command(label="Copy", command=lambda: text_widget.event_generate("<>"))
        context_menu.add_command(label="Cut", command=lambda: text_widget.event_generate("<>"))
        context_menu.add_command(label="Paste", command=lambda: text_widget.event_generate("<>"))
        context_menu.add_separator(background="#444")
        context_menu.add_command(label="Select All", command=lambda: text_widget.tag_add("sel", "1.0", "end"))

        def show_context_menu(event):
            try:
                context_menu.tk_popup(event.x_root, event.y_root)
            finally:
                context_menu.grab_release()

        text_widget.bind("", show_context_menu)

    def open_info_popup(self):
        popup = Toplevel(self)
        popup.title("UPC Framework Info & Resources")
        popup.geometry("520x460")
        popup.configure(bg="#1e1e1e")
        popup.resizable(False, False)

        tk.Label(popup, text="Universal Principle of Collapse — Operator Guide", bg="#1e1e1e", fg="#4FC3F7", font=("Segoe UI", 10, "bold")).pack(anchor="w", padx=15, pady=(15, 6))
        
        guide_text = tk.Text(popup, bg="#0d0d0d", fg="#e0e0e0", font=("Segoe UI", 8), wrap="word", relief="flat", padx=10, pady=8, height=13)
        guide_text.pack(fill="x", padx=15, pady=(0, 10))
        
        info_str = "\n".join([f"• [{op}]: {desc}" for op, desc in self.descriptions.items()])
        guide_text.insert("1.0", info_str)
        guide_text.config(state="disabled")

        links_frame = tk.Frame(popup, bg="#252526", padx=10, pady=8)
        links_frame.pack(fill="x", padx=15, pady=(0, 12))
        tk.Label(links_frame, text="Project Editions & Resources:", bg="#252526", fg="#b0bec5", font=("Segoe UI", 8, "bold")).pack(anchor="w", pady=(0, 4))

        def make_link_lbl(parent, text, url):
            lbl = tk.Label(parent, text=text, bg="#252526", fg="#4FC3F7", font=("Segoe UI", 8, "underline"), cursor="hand2", anchor="w")
            lbl.pack(fill="x", pady=2)
            lbl.bind("", lambda e: webbrowser.open(url))
            return lbl

        make_link_lbl(
            links_frame,
            "🌐 Live Browser Circuit Simulator (Online Edition)",
            "https://upcresearchproject.blogspot.com/2026/09/interactive-circuit-simulator-live.html"
        )
        make_link_lbl(
            links_frame,
            "💻 UPC Visual Simulator (Local Desktop Research Edition)",
            "https://upcresearchproject.blogspot.com/2026/09/the-upc-visual-simulator-demonstrating.html"
        )

        tk.Button(popup, text="CLOSE", bg="#2962FF", fg="#ffffff", font=("Segoe UI", 8, "bold"), relief="flat", command=popup.destroy).pack(pady=(0, 12))

    def update_eigenstate_bars(self, scores_dict):
        max_val = max(abs(v) for v in scores_dict.values()) if scores_dict else 1.0
        if max_val == 0:
            max_val = 1.0

        for state, (bar, container, val_lbl) in self.bar_rows.items():
            val = scores_dict.get(state, 0.0)
            val_lbl.config(text=f"{val:.3f}")
            container.update_idletasks()
            total_w = container.winfo_width() or 180
            ratio = max(0.0, min(1.0, (val / max_val)))
            bar_w = max(2, int(ratio * total_w))
            bar.place(x=0, y=0, width=bar_w, relheight=1)

    def render_state(self, step_idx):
        for i, op in enumerate(self.operators):
            if i == step_idx:
                self.top_pill_labels[op].config(bg="#2962FF", fg="#ffffff")
                self.chain_buttons[op].config(bg="#2962FF", fg="#ffffff")
            else:
                self.top_pill_labels[op].config(bg="#252526", fg="#757575")
                self.chain_buttons[op].config(bg="#2a2a2c", fg="#b0bec5")

        self.canvas.update_idletasks()
        width = self.canvas.winfo_width()
        if width <= 10:
            width = 850
        height = 140
        center_y = height / 2

        self.canvas.delete("all")
        self.canvas.create_line(0, center_y, width, center_y, fill="#cfd8dc", dash=(4, 4))

        amplitudes = [45, 36, 28, 16, 5, 2, 0]
        amp = amplitudes[step_idx]

        xs = np.linspace(0, width, 400)
        freq = 3.5 + (step_idx * 0.3)
        ys = center_y + amp * np.sin(xs * (2 * np.pi / width) * freq)

        points = []
        for x, y in zip(xs, ys):
            points.extend([x, y])
        self.canvas.create_line(points, fill="#2962FF", width=2.5)

        np.random.seed(42 + step_idx)
        for _ in range(22):
            px = np.random.uniform(20, width - 20)
            py = center_y + amp * np.sin(px * (2 * np.pi / width) * freq) + np.random.uniform(-5, 5)
            r = np.random.uniform(2, 4.5)
            self.canvas.create_oval(px - r, py - r, px + r, py + r, fill="#ce93d8", outline="")

        if step_idx >= 4:
            jo_x = width * 0.71
            self.canvas.create_oval(jo_x - 6, center_y - 6, jo_x + 6, center_y + 6, fill="#FF3D00", outline="")

        if step_idx >= 5:
            c_x = width * 0.85
            self.canvas.create_line(c_x, center_y - 35, c_x, center_y + 35, fill="#FFD600", width=3)

    def step_simulation(self):
        op = self.operators[self.current_step]
        self.render_state(self.current_step)
        self.status_label.config(text=f"Step {self.current_step + 1}/7 — [{op} Operator]: {self.descriptions[op]}")

        text = self.text_input.get("1.0", "end-1c")
        result = self.engine.evaluate(text)

        if self.current_step >= 5 and result:
            self.update_eigenstate_bars(result.get("composite_scores", {}))

        if self.current_step == len(self.operators) - 1:
            self.json_output.delete("1.0", "end")
            self.json_output.insert("1.0", json.dumps(result, indent=2))

        if self.current_step < len(self.operators) - 1:
            self.current_step += 1

    def manual_select_step(self, idx):
        self.current_step = idx
        op = self.operators[idx]
        self.render_state(idx)
        self.status_label.config(text=f"Manual Step {idx + 1}/7 — [{op} Operator]: {self.descriptions[op]}")
        
        text = self.text_input.get("1.0", "end-1c")
        result = self.engine.evaluate(text)

        if idx >= 5 and result:
            self.update_eigenstate_bars(result.get("composite_scores", {}))
        elif idx < 5:
            self.update_eigenstate_bars({s: 0.0 for s in self.eigenstates})

        if idx == len(self.operators) - 1:
            self.json_output.delete("1.0", "end")
            self.json_output.insert("1.0", json.dumps(result, indent=2))

    def reset_simulation(self):
        self.is_running = False
        self.current_step = 0
        self.render_state(0)
        self.status_label.config(text="Pipeline Reset. Ready to trace operators.")
        self.json_output.delete("1.0", "end")
        self.json_output.insert("1.0", "// Trace output JSON pending execution...")
        self.update_eigenstate_bars({s: 0.0 for s in self.eigenstates})

    def run_auto_play(self):
        if self.is_running:
            return
        if self.current_step >= len(self.operators) - 1:
            self.current_step = 0
            self.update_eigenstate_bars({s: 0.0 for s in self.eigenstates})
        self.is_running = True
        threading.Thread(target=self._auto_play_worker, daemon=True).start()

    def _auto_play_worker(self):
        while self.is_running and self.current_step < len(self.operators):
            self.after(0, self.step_simulation)
            if self.current_step == len(self.operators) - 1:
                break
            time.sleep(1.2)
        self.is_running = False

if __name__ == "__main__":
    app = UPCVisualSimulator()
    app.mainloop()

No comments:

Post a Comment

The Puzzle-Piece Fallacy: Why Materialism Collapses into Its Own Output

The Universal Principle of Collapse (UPC) Eloy Escagedo Gutierrez Oct 14, 2026 Introduction Modern physicalists are trapped inside a looping...