r/PythonLearning • • Jun 17 '25

What does this code do?

Warning. This is AI code, that’s why I’m asking. (I know nothing for python, hence the request).

=== rcc_core/rcc_grid.py ===

import numpy as np

class RCC_Cell: def init(self, position): self.position = np.array(position, dtype=float) self.Phi = 0.0 # Phase or some scalar field self.collapse_state = None # None means not collapsed

def update(self):
    # Placeholder logic for collapse update - should be replaced with RCC physics
    if self.Phi > 0.5:
        self.collapse_state = True
    else:
        self.collapse_state = False

class RCC_Grid: def init(self, shape=(10,10,10), spacing=1.0): self.shape = shape self.spacing = spacing self.grid = np.empty(shape, dtype=object)

    for x in range(shape[0]):
        for y in range(shape[1]):
            for z in range(shape[2]):
                pos = (x*spacing, y*spacing, z*spacing)
                self.grid[x,y,z] = RCC_Cell(pos)

def update_all(self):
    for x in range(self.shape[0]):
        for y in range(self.shape[1]):
            for z in range(self.shape[2]):
                self.grid[x,y,z].update()

=== rcc_visualizer/vispy_renderer.py ===

import numpy as np from vispy import app, scene

from rcc_core.rcc_grid import RCC_Grid from rcc_visualizer.ui_controls import InputController, HoverTooltip

class RCC_VispyRenderer(app.Canvas): def init(self, rcc_grid): app.Canvas.init(self, title="RCC Simulation Viewer", keys='interactive', size=(800, 600))

    self.grid = rcc_grid
    self.view = scene.widgets.ViewBox(border_color='white', parent=self.scene)
    self.view.camera = scene.cameras.TurntableCamera(fov=45, distance=20)
    
    # Prepare point cloud visuals for cells
    self.points = scene.visuals.Markers(parent=self.view.scene)
    
    # Input controller and hover tooltip for modular input and hover info
    self.input_controller = InputController(self.view.camera)
    self.hover_tooltip = HoverTooltip(self.grid, self.view, self)
    
    # Start timer for update loop
    self._timer = app.Timer('auto', connect=self.on_timer, start=True)
    
    self._update_point_data()
    
    # Mouse wheel zoom factor
    self.wheel_zoom_factor = 1.1
    
    self.show()

def _update_point_data(self):
    positions = []
    colors = []
    
    for x in range(self.grid.shape[0]):
        for y in range(self.grid.shape[1]):
            for z in range(self.grid.shape[2]):
                cell = self.grid.grid[x,y,z]
                positions.append(cell.position)
                # Color collapsed cells red, else blue
                if cell.collapse_state is not None and cell.collapse_state:
                    colors.append([1.0, 0.2, 0.2, 1.0])  # Red
                else:
                    colors.append([0.2, 0.2, 1.0, 1.0])  # Blue
    
    self.points.set_data(np.array(positions), face_color=np.array(colors), size=8)

def on_timer(self, event):
    # Update simulation grid
    self.grid.update_all()
    # Update point cloud visuals
    self._update_point_data()
    # Update input-driven movement
    self.input_controller.update_movement()
    # Request redraw
    self.update()

def on_key_press(self, event):
    self.input_controller.on_key_press(event)

def on_key_release(self, event):
    self.input_controller.on_key_release(event)

def on_mouse_wheel(self, event):
    self.input_controller.on_mouse_wheel(event)

def on_mouse_move(self, event):
    self.hover_tooltip.update_tooltip(event)

if name == "main": grid = RCC_Grid(shape=(10,10,10), spacing=1.0) viewer = RCC_VispyRenderer(grid) app.run()

=== rcc_visualizer/ui_controls.py ===

from vispy import app import numpy as np

class InputController: """ Manages keyboard and mouse input for camera control. Tracks pressed keys for WASD movement and mouse wheel zoom. """ def init(self, camera): self.camera = camera self._keys_pressed = set() self.wheel_zoom_factor = 1.1

def on_key_press(self, event):
    self._keys_pressed.add(event.key.name.upper())

def on_key_release(self, event):
    self._keys_pressed.discard(event.key.name.upper())

def on_mouse_wheel(self, event):
    if event.delta[1] > 0:
        self.camera.scale_factor /= self.wheel_zoom_factor
    else:
        self.camera.scale_factor *= self.wheel_zoom_factor

def update_movement(self):
    step = 0.2
    cam = self.camera
    if 'W' in self._keys_pressed:
        cam.center += cam.transform.map([0, 0, -step])[:3]
    if 'S' in self._keys_pressed:
        cam.center += cam.transform.map([0, 0, step])[:3]
    if 'A' in self._keys_pressed:
        cam.center += cam.transform.map([-step, 0, 0])[:3]
    if 'D' in self._keys_pressed:
        cam.center += cam.transform.map([step, 0, 0])[:3]

class HoverTooltip: """ Displays tooltip info about RCC_Cell under cursor. Needs access to grid and camera for picking. """ def init(self, grid, view, parent): self.grid = grid self.view = view self.parent = parent # Canvas self.tooltip_text = "" self.visible = False

    # Create text visual for tooltip
    from vispy.visuals import Text
    self.text_visual = Text("", color='white', parent=self.view.scene, font_size=12, anchor_x='left', anchor_y='bottom')
    self.text_visual.visible = False

def update_tooltip(self, event):
    # Convert mouse pos to 3D ray and find closest cell
    pos = event.pos
    # Raycast approximation: find closest projected cell within radius
    
    # Project all cell positions to 2D screen coordinates
    tr = self.view.scene.node_transform(self.parent)
    min_dist = 15  # pixels
    closest_cell = None
    
    for x in range(self.grid.shape[0]):
        for y in range(self.grid.shape[1]):
            for z in range(self.grid.shape[2]):
                cell = self.grid.grid[x,y,z]
                proj = tr.map(cell.position)[:2]
                dist = np.linalg.norm(proj - pos)
                if dist < min_dist:
                    min_dist = dist
                    closest_cell = cell
    
    if closest_cell is not None:
        self.tooltip_text = f"Pos: {closest_cell.position}\nΦ: {closest_cell.Phi:.2f}\nCollapse: {closest_cell.collapse_state}"
        self.text_visual.text = self.tooltip_text
        self.text_visual.pos = pos + np.array([10, -10])  # offset tooltip position
        self.text_visual.visible = True
        self.visible = True
    else:
        self.text_visual.visible = False
        self.visible = False

=== rcc_compiler/parser.py ===

from sympy import symbols, Symbol, sympify, Eq from sympy.parsing.sympy_parser import parse_expr

class RCC_Parser: """ Parses RCC symbolic formulas into sympy expressions. Supports variables: Φ, T, S, Ψ, ΔΦ, χ etc. """ def init(self): # Define RCC variables as sympy symbols self.variables = { 'Φ': symbols('Phi'), 'T': symbols('T', cls=Symbol), 'S': symbols('S'), 'Ψ': symbols('Psi'), 'ΔΦ': symbols('DeltaPhi'), 'χ': symbols('Chi'), }

def parse_formula(self, formula_str):
    """
    Parses string formula into sympy Eq or expression.
    Example input: 'Ψ = Φ * exp(I * ΔΦ)'
    """
    # Replace Greek vars with ASCII symbols for sympy
    replacements = {
        'Φ': 'Phi',
        'Ψ': 'Psi',
        'ΔΦ': 'DeltaPhi',
        'χ': 'Chi',
    }
    for k, v in replacements.items():
        formula_str = formula_str.replace(k, v)
    
    # Parse formula - if assignment exists (=), split LHS and RHS
    if '=' in formula_str:
        lhs, rhs = formula_str.split('=', 1)
        lhs = lhs.strip()
        rhs = rhs.strip()
        lhs_expr = sympify(lhs)
        rhs_expr = sympify(rhs)
        return Eq(lhs_expr, rhs_expr)
    else:
        return parse_expr(formula_str)

=== rcc_compiler/evaluator.py ===

from sympy import lambdify

class RCC_Evaluator: """ Evaluates RCC sympy formulas by substituting variable values. """ def init(self, sympy_eq): self.eq = sympy_eq # Extract variables used in expression self.variables = list(sympy_eq.free_symbols) # Lambdify RHS for fast numeric evaluation self.func = lambdify(self.variables, sympy_eq.rhs, 'numpy')

def evaluate(self, **kwargs):
    """
    Evaluate RHS with variable substitutions.
    Example: evaluator.evaluate(Phi=1.0, DeltaPhi=0.5)
    """
    # Extract variables in the order lambdify expects
    vals = []
    for var in self.variables:
        val = kwargs.get(str(var), None)
        if val is None:
            raise ValueError(f"Missing value for variable {var}")
        vals.append(val)
    return self.func(*vals)

=== Example usage of compiler and evaluator ===

if name == "main": # Simple test for parser + evaluator parser = RCC_Parser() formula = "Ψ = Φ * exp(I * ΔΦ)" eq = parser.parse_formula(formula)

evaluator = RCC_Evaluator(eq)
import numpy as np
result = evaluator.evaluate(Phi=1.0, DeltaPhi=0.5j)
print(f"Ψ = {result}")
0 Upvotes

22 comments sorted by

View all comments

Show parent comments

6

u/[deleted] Jun 17 '25

[removed] — view removed comment

-6

u/Dyformia Jun 17 '25

Well your comment just says it’s ‘unifinished’ and ‘nonsense’. You then go on to say “someone really thought they were cooking, and ai believed them”.

I’m a big confused though, since no part of that actually relates to what the code actually does. It may not even do anything, it may error out. But you didn’t say if it did that or not. You just called it garbage.

To go even further, when I questioned you about it, you just said that you already told me, and that if I didn’t understand (aka I’m too stupid) to have the ai explain to me what it does.

Now if the ai generated such bad code, thinking it was good, why would you have me go ask it to explain it to me? It thinks bad code is good, so obviously it has no right to explain any code in my opinion. And if you disagree with that, that sounds a lot like you are promoting the usage of bad ai, bad code, and crack pot theories.

So either apologize for being a blatant asshole for no reason, or accept that you promote the code you just shit on.

Your choice “Nonsense_Replies”.

3

u/Haunting-Pop-5660 Jun 17 '25

This is super pedantic. If you're here for the sake of pedantry, you may have better luck arguing semiotics with the AI.

-6

u/Dyformia Jun 17 '25

Bro hops right on the gravity train with the other. I refer you back to the 2nd to last paragraph in the prompt you responded to.

Your choice “Haunting-Pop-5660”

4

u/[deleted] Jun 17 '25

[removed] — view removed comment

1

u/Dyformia Jun 17 '25

I still don’t support a single one your comments. Should I have been so aggressive with my point? Probably not. Could you have just explained how to have ai check it similar to the other comment? Yeah. Sorry for being a butt, just those kinda comments everywhere are gigga trigga for my autism