Compare commits

..

No commits in common. "1fd1de2f82761d56b4fc579c9f4d6eb62aef3263" and "70937fbdc3335603b8638c7616d4e574dc05612c" have entirely different histories.

25 changed files with 1253 additions and 1635 deletions

218
Programming/TRAK/code/mapa_srodowiska/main.py Executable file → Normal file
View File

@ -1,64 +1,42 @@
#!/usr/bin/env python3
"""View an OpenEXR environment map from the inside, on a GLUT-textured sphere.
Drag with the left mouse button to look around. The image is loaded as
32-bit float RGB and uploaded as a `GL_RGB32F` texture, so the high dynamic
range survives all the way to the driver.
"""
from __future__ import annotations
import logging
import os
from dataclasses import dataclass
from pathlib import Path
import Imath
import OpenEXR
from OpenGL import GL, GLU, GLUT
import OpenGL.GL as gl
import OpenGL.GLU as glu
import OpenGL.GLUT as glut
logger = logging.getLogger(__name__)
# How far the camera turns per pixel of mouse drag.
_DEGREES_PER_PIXEL = 0.1
# Camera parameters
camera_angle_x = 0.0
camera_angle_y = 0.0
camera_distance = 2.0
mouse_last_x = 0
mouse_last_y = 0
mouse_left_down = False
@dataclass
class ViewerState:
"""Camera orientation and mouse-drag state, mutated by the GLUT callbacks."""
angle_x: float = 0.0
angle_y: float = 0.0
distance: float = 2.0
last_x: int = 0
last_y: int = 0
left_down: bool = False
STATE = ViewerState()
def load_hdr_environment_map(filepath: str) -> tuple[int, int, bytes]:
def load_hdr_environment_map(filepath):
"""Load an HDR environment map from an OpenEXR file.
Returns the width, the height, and the pixels as interleaved float RGB,
flipped vertically so that row 0 is the bottom row OpenGL expects.
Args:
filepath (str): Path to the HDR file.
Returns:
tuple: A tuple containing the width, height, and a bytes object representing the HDR environment map in RGB format.
"""
if not Path(filepath).exists():
msg = f"File not found: {filepath}"
raise FileNotFoundError(msg)
if not os.path.exists(filepath):
raise FileNotFoundError(f"File not found: {filepath}")
# Check file permissions
if not os.access(filepath, os.R_OK):
msg = f"File is not readable: {filepath}"
raise PermissionError(msg)
raise PermissionError(f"File is not readable: {filepath}")
# Open the EXR file
try:
exr_file = OpenEXR.InputFile(filepath)
except Exception as e:
msg = f"Unable to open '{filepath}' for read: {e!s}"
raise OSError(msg) from e
raise OSError(f"Unable to open '{filepath}' for read: {e!s}")
# Get the image dimensions
header = exr_file.header()
@ -99,117 +77,117 @@ def load_hdr_environment_map(filepath: str) -> tuple[int, int, bytes]:
return width, height, bytes(flipped_hdr_image)
def display_hdr_image(width: int, height: int, hdr_image: bytes) -> None:
"""Draw one frame: the environment map on the inside of a large sphere."""
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
def display_hdr_image(width, height, hdr_image):
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
# Enable texture mapping
GL.glEnable(GL.GL_TEXTURE_2D)
texture_id = GL.glGenTextures(1)
GL.glBindTexture(GL.GL_TEXTURE_2D, texture_id)
gl.glEnable(gl.GL_TEXTURE_2D)
texture_id = gl.glGenTextures(1)
gl.glBindTexture(gl.GL_TEXTURE_2D, texture_id)
# Set texture parameters
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR)
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE)
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE)
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)
# Load the texture
GL.glTexImage2D(
GL.GL_TEXTURE_2D,
gl.glTexImage2D(
gl.GL_TEXTURE_2D,
0,
GL.GL_RGB32F,
gl.GL_RGB32F,
width,
height,
0,
GL.GL_RGB,
GL.GL_FLOAT,
gl.GL_RGB,
gl.GL_FLOAT,
hdr_image,
)
# Set up the viewport and projection
window_width = GLUT.glutGet(GLUT.GLUT_WINDOW_WIDTH)
window_height = GLUT.glutGet(GLUT.GLUT_WINDOW_HEIGHT)
GL.glViewport(0, 0, window_width, window_height)
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glLoadIdentity()
GLU.gluPerspective(45.0, window_width / float(window_height), 0.1, 100.0)
GL.glMatrixMode(GL.GL_MODELVIEW)
GL.glLoadIdentity()
gl.glViewport(
0,
0,
glut.glutGet(glut.GLUT_WINDOW_WIDTH),
glut.glutGet(glut.GLUT_WINDOW_HEIGHT),
)
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glLoadIdentity()
glu.gluPerspective(
45.0,
glut.glutGet(glut.GLUT_WINDOW_WIDTH)
/ float(glut.glutGet(glut.GLUT_WINDOW_HEIGHT)),
0.1,
100.0,
)
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glLoadIdentity()
# Apply camera transformations
GL.glTranslatef(0.0, 0.0, -STATE.distance)
GL.glRotatef(STATE.angle_y, 1.0, 0.0, 0.0)
GL.glRotatef(STATE.angle_x, 0.0, 1.0, 0.0)
gl.glTranslatef(0.0, 0.0, -camera_distance)
gl.glRotatef(camera_angle_y, 1.0, 0.0, 0.0)
gl.glRotatef(camera_angle_x, 0.0, 1.0, 0.0)
# Draw a textured sphere to simulate being inside the HDR environment
quadric = GLU.gluNewQuadric()
GLU.gluQuadricTexture(quadric, GL.GL_TRUE)
GLU.gluSphere(quadric, 50.0, 50, 50)
GLU.gluDeleteQuadric(quadric)
quadric = glu.gluNewQuadric()
glu.gluQuadricTexture(quadric, gl.GL_TRUE)
glu.gluSphere(quadric, 50.0, 50, 50)
glu.gluDeleteQuadric(quadric)
# Disable texture mapping
GL.glDisable(GL.GL_TEXTURE_2D)
gl.glDisable(gl.GL_TEXTURE_2D)
GLUT.glutSwapBuffers()
glut.glutSwapBuffers()
def mouse_motion(x: int, y: int) -> None:
"""Turn the camera by however far the pointer moved since the last event."""
if STATE.left_down:
dx = x - STATE.last_x
dy = y - STATE.last_y
STATE.angle_x += dx * _DEGREES_PER_PIXEL
STATE.angle_y += dy * _DEGREES_PER_PIXEL
STATE.last_x = x
STATE.last_y = y
GLUT.glutPostRedisplay()
def mouse_motion(x, y):
global mouse_last_x, mouse_last_y, camera_angle_x, camera_angle_y
if mouse_left_down:
dx = x - mouse_last_x
dy = y - mouse_last_y
camera_angle_x += dx * 0.1
camera_angle_y += dy * 0.1
mouse_last_x = x
mouse_last_y = y
glut.glutPostRedisplay()
def mouse_button(button: int, state: int, x: int, y: int) -> None:
"""Start a drag on left-button press and end it on release."""
if button == GLUT.GLUT_LEFT_BUTTON:
if state == GLUT.GLUT_DOWN:
STATE.left_down = True
# These two were assigned without a `global` declaration before, so
# they went to locals and were thrown away: the first motion event
# of every drag measured from wherever the previous drag ended.
STATE.last_x = x
STATE.last_y = y
elif state == GLUT.GLUT_UP:
STATE.left_down = False
def mouse_button(button, state, x, y):
global mouse_left_down
if button == glut.GLUT_LEFT_BUTTON:
if state == glut.GLUT_DOWN:
mouse_left_down = True
mouse_last_x = x
mouse_last_y = y
elif state == glut.GLUT_UP:
mouse_left_down = False
def main(filepath: str) -> None:
"""Load `filepath` and hand control to the GLUT main loop."""
def main(filepath):
try:
width, height, hdr_map = load_hdr_environment_map(filepath)
except OSError:
# Covers the not-found, not-readable and unreadable-EXR cases above.
# Anything else is a real fault and should surface as a traceback.
logger.exception("Could not load '%s'", filepath)
return
print("HDR Map Loaded. Dimensions:", width, "x", height)
logger.info("HDR Map Loaded. Dimensions: %s x %s", width, height)
# Initialize GLUT and create window
glut.glutInit()
glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGB | glut.GLUT_DEPTH)
glut.glutInitWindowSize(800, 600) # Set initial window size
glut.glutCreateWindow(b"HDR Environment Map")
# Initialize GLUT and create window
GLUT.glutInit()
GLUT.glutInitDisplayMode(GLUT.GLUT_DOUBLE | GLUT.GLUT_RGB | GLUT.GLUT_DEPTH)
GLUT.glutInitWindowSize(800, 600) # Set initial window size
GLUT.glutCreateWindow(b"HDR Environment Map")
# Set display callback
glut.glutDisplayFunc(lambda: display_hdr_image(width, height, hdr_map))
# Set display callback
GLUT.glutDisplayFunc(lambda: display_hdr_image(width, height, hdr_map))
# Set mouse callbacks
glut.glutMotionFunc(mouse_motion)
glut.glutMouseFunc(mouse_button)
# Set mouse callbacks
GLUT.glutMotionFunc(mouse_motion)
GLUT.glutMouseFunc(mouse_button)
# Start the GLUT main loop
GLUT.glutMainLoop()
# Start the GLUT main loop
glut.glutMainLoop()
except Exception as e:
print(e)
# Example usage
if __name__ == "__main__":
logging.basicConfig(format="%(message)s", level=logging.INFO)
main("lilienstein_4k.exr")
filepath = "lilienstein_4k.exr"
main(filepath)

View File

@ -1,119 +0,0 @@
#!/usr/bin/env python3
"""Vectors, photons and the two surfaces the standalone photon mapper traces.
Split out of `main.py` so each file stays under this repo's 250-line cap; the
classes are unchanged.
"""
from __future__ import annotations
import numpy as np
# A ray whose direction is this close to parallel with a plane never hits it.
_PARALLEL_EPSILON = 1e-6
# Define basic vector operations
class Vector3:
"""A 3D vector, with just the operations this renderer needs."""
def __init__(self, x: float, y: float, z: float) -> None:
"""Store the three components."""
self.x = x
self.y = y
self.z = z
def __add__(self, other: Vector3) -> Vector3:
"""Return the component-wise sum."""
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other: Vector3) -> Vector3:
"""Return the component-wise difference."""
return Vector3(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, scalar: float) -> Vector3:
"""Return this vector scaled by `scalar`."""
return Vector3(self.x * scalar, self.y * scalar, self.z * scalar)
def dot(self, other: Vector3) -> float:
"""Return the dot product with `other`."""
return self.x * other.x + self.y * other.y + self.z * other.z
def norm(self) -> float:
"""Return the length of this vector."""
return float(np.sqrt(self.dot(self)))
def normalize(self) -> Vector3:
"""Return a new vector of unit length pointing the same way."""
n = self.norm()
return Vector3(self.x / n, self.y / n, self.z / n)
# Define the photon
class Photon:
"""A packet of light energy travelling in a straight line."""
def __init__(
self, position: Vector3, direction: Vector3, power: np.ndarray
) -> None:
"""Store where the photon is, where it is going, and what it carries."""
self.position = position
self.direction = direction
self.power = power
# Define a simple sphere
class Sphere:
"""A sphere of uniform colour."""
def __init__(self, center: Vector3, radius: float, color: np.ndarray) -> None:
"""Store the sphere's geometry and colour."""
self.center = center
self.radius = radius
self.color = color
def intersect(
self, ray_origin: Vector3, ray_direction: Vector3
) -> tuple[float, Vector3, Vector3] | None:
"""Return the nearest hit as (distance, point, normal), or None."""
# Solve quadratic equation for intersection
oc = ray_origin - self.center
a = ray_direction.dot(ray_direction)
b = 2.0 * oc.dot(ray_direction)
c = oc.dot(oc) - self.radius * self.radius
discriminant = b * b - 4 * a * c
if discriminant < 0:
return None # No intersection
t = (-b - np.sqrt(discriminant)) / (2.0 * a)
if t < 0:
t = (-b + np.sqrt(discriminant)) / (2.0 * a)
if t < 0:
return None
hit_point = ray_origin + ray_direction * t
normal = (hit_point - self.center).normalize()
return (t, hit_point, normal)
# Define a simple plane
class Plane:
"""An infinite plane of uniform colour."""
def __init__(self, point: Vector3, normal: Vector3, color: np.ndarray) -> None:
"""Store a point on the plane, its (normalised) normal, and its colour."""
self.point = point
self.normal = normal.normalize()
self.color = color
def intersect(
self, ray_origin: Vector3, ray_direction: Vector3
) -> tuple[float, Vector3, Vector3] | None:
"""Return the nearest hit as (distance, point, normal), or None."""
denom = self.normal.dot(ray_direction)
if abs(denom) > _PARALLEL_EPSILON:
t = (self.point - ray_origin).dot(self.normal) / denom
if t >= 0:
hit_point = ray_origin + ray_direction * t
return (t, hit_point, self.normal)
return None
Surface = Sphere | Plane

300
Programming/TRAK/code/photonmapping/python/main.py Executable file → Normal file
View File

@ -1,32 +1,88 @@
#!/usr/bin/env python3
"""Standalone photon mapper: scatter photons from the light, then gather them.
The lab version, kept whole: the scene, the light and the photon map are
module-level state, and running the file emits photons, renders a 100x100
image and shows it. `Programming/TRAK/photon_mapping.py` is the later
parameterised rewrite of the same algorithm.
"""
from __future__ import annotations
import logging
import time
from typing import cast
import matplotlib.pyplot as plt
import numpy as np
from geometry import Photon, Plane, Sphere, Surface, Vector3
logger = logging.getLogger(__name__)
PHOTONS = 0
# Shadow rays start this far off the surface they were cast from.
_SHADOW_OFFSET = 1e-5
# Fraction of its power a photon keeps across one diffuse bounce.
_BOUNCE_ABSORPTION = 0.8
# Define basic vector operations
class Vector3:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector3(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, scalar):
return Vector3(self.x * scalar, self.y * scalar, self.z * scalar)
def dot(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def norm(self):
return np.sqrt(self.dot(self))
def normalize(self):
n = self.norm()
return Vector3(self.x / n, self.y / n, self.z / n)
# Define the photon
class Photon:
def __init__(self, position, direction, power):
self.position = position
self.direction = direction
self.power = power
# Define a simple sphere
class Sphere:
def __init__(self, center, radius, color):
self.center = center
self.radius = radius
self.color = color
def intersect(self, ray_origin, ray_direction):
# Solve quadratic equation for intersection
oc = ray_origin - self.center
a = ray_direction.dot(ray_direction)
b = 2.0 * oc.dot(ray_direction)
c = oc.dot(oc) - self.radius * self.radius
discriminant = b * b - 4 * a * c
if discriminant < 0:
return None # No intersection
t = (-b - np.sqrt(discriminant)) / (2.0 * a)
if t < 0:
t = (-b + np.sqrt(discriminant)) / (2.0 * a)
if t < 0:
return None
hit_point = ray_origin + ray_direction * t
normal = (hit_point - self.center).normalize()
return (t, hit_point, normal)
# Define a simple plane
class Plane:
def __init__(self, point, normal, color):
self.point = point
self.normal = normal.normalize()
self.color = color
def intersect(self, ray_origin, ray_direction):
denom = self.normal.dot(ray_direction)
if abs(denom) > 1e-6:
t = (self.point - ray_origin).dot(self.normal) / denom
if t >= 0:
hit_point = ray_origin + ray_direction * t
return (t, hit_point, self.normal)
return None
# One generator for the whole module, matching the module-level scene below.
_rng = np.random.default_rng()
# Scene setup
sphere = Sphere(Vector3(0, 0, -5), 1.0, np.array([1, 0, 0])) # Red sphere
@ -34,14 +90,14 @@ plane = Plane(
Vector3(0, -1, 0), Vector3(0, 1, 0), np.array([0.5, 0.5, 0.5])
) # Gray plane
objects: list[Surface] = [sphere, plane]
objects = [sphere, plane]
# Light source
light_position = Vector3(-5, 5, -5)
light_power = np.array([1, 1, 1]) * 1000 # Intense white light
# Photon map
photon_map: list[tuple[Vector3, np.ndarray]] = []
photon_map = []
# Parameters
num_photons = 10000 # Number of photons to emit
@ -49,26 +105,75 @@ max_depth = 5 # Maximum number of bounces
gather_radius = 0.5 # Radius for radiance estimation
def random_unit_vector() -> Vector3:
"""Draw a direction uniformly over the sphere."""
theta = _rng.uniform(0, 2 * np.pi)
z = _rng.uniform(-1, 1)
def emit_photons():
for _ in range(num_photons):
# Emit photons in random directions from the light source
direction = random_unit_vector()
power = light_power / num_photons
photon = Photon(light_position, direction, power)
trace_photon(photon, 0)
def trace_photon(photon, depth):
global PHOTONS
PHOTONS += 1
if depth > max_depth:
return
closest_t = np.inf
hit_object = None
hit_info = None
# Find the nearest intersection
for obj in objects:
result = obj.intersect(photon.position, photon.direction)
if result:
t, hit_point, normal = result
if t < closest_t:
closest_t = t
hit_object = obj
hit_info = (hit_point, normal)
if hit_object:
hit_point, normal = hit_info
photon_map.append((hit_point, photon.power))
# Diffuse reflection
new_direction = random_hemisphere_direction(normal)
photon.position = hit_point
photon.direction = new_direction
# Absorb some power
photon.power = photon.power * 0.8 # Simple absorption
trace_photon(photon, depth + 1)
def random_unit_vector():
theta = np.random.uniform(0, 2 * np.pi)
z = np.random.uniform(-1, 1)
r = np.sqrt(1 - z * z)
return Vector3(r * np.cos(theta), r * np.sin(theta), z)
def random_hemisphere_direction(normal: Vector3) -> Vector3:
"""Draw a direction uniformly over the hemisphere around `normal`."""
direction = random_unit_vector()
if direction.dot(normal) < 0:
direction = Vector3(-direction.x, -direction.y, -direction.z)
return direction
def random_hemisphere_direction(normal):
dir = random_unit_vector()
if dir.dot(normal) < 0:
dir = Vector3(-dir.x, -dir.y, -dir.z)
return dir
def nearest_hit(
ray_origin: Vector3, ray_direction: Vector3
) -> tuple[Surface, Vector3, Vector3] | None:
"""Return the closest surface the ray meets, with its point and normal."""
def render_image(width, height):
aspect_ratio = width / height
fov = np.pi / 3 # 60 degrees field of view
image = np.zeros((height, width, 3))
for y in range(height):
for x in range(width):
# Convert pixel coordinate to camera ray
px = (2 * (x + 0.5) / width - 1) * np.tan(fov / 2) * aspect_ratio
py = (1 - 2 * (y + 0.5) / height) * np.tan(fov / 2)
ray_origin = Vector3(0, 0, 0)
ray_direction = Vector3(px, py, -1).normalize()
color = trace_ray(ray_origin, ray_direction)
image[y, x, :] = np.clip(color, 0, 1)
return image
def trace_ray(ray_origin, ray_direction):
closest_t = np.inf
hit_object = None
hit_info = None
@ -80,59 +185,35 @@ def nearest_hit(
if t < closest_t:
closest_t = t
hit_object = obj
hit_info = (hit_point, normal)
if hit_object is None or hit_info is None:
return None
return (hit_object, hit_info[0], hit_info[1])
hit_info = (hit_point, normal, obj.color)
if hit_object:
hit_point, normal, color = hit_info
direct_light = compute_direct_light(hit_point, normal)
indirect_light = estimate_radiance(hit_point, normal)
return color * (direct_light + indirect_light)
return np.array([0, 0, 0]) # Background color
def trace_photon(photon: Photon, depth: int) -> int:
"""Bounce one photon, recording each landing, and return the traces made.
The count is what the original `global PHOTONS` accumulated: one per call,
bounces included.
"""
if depth > max_depth:
return 1
hit = nearest_hit(photon.position, photon.direction)
if hit is None:
return 1
_, hit_point, normal = hit
photon_map.append((hit_point, photon.power))
# Diffuse reflection
photon.position = hit_point
photon.direction = random_hemisphere_direction(normal)
# Absorb some power
photon.power = photon.power * _BOUNCE_ABSORPTION # Simple absorption
return 1 + trace_photon(photon, depth + 1)
def emit_photons() -> int:
"""Emit `num_photons` from the light and return the total traces made."""
traces = 0
for _ in range(num_photons):
# Emit photons in random directions from the light source
direction = random_unit_vector()
power = light_power / num_photons
traces += trace_photon(Photon(light_position, direction, power), 0)
return traces
def compute_direct_light(point: Vector3, normal: Vector3) -> np.ndarray:
"""Return the light arriving straight from the source, or black if shadowed."""
def compute_direct_light(point, normal):
# Simple Lambertian reflection from light source
direction_to_light = (light_position - point).normalize()
# Shadow ray
shadow_origin = point + normal * _SHADOW_OFFSET
shadow_origin = point + normal * 1e-5
shadow_ray = direction_to_light
in_shadow = False
for obj in objects:
if obj.intersect(shadow_origin, direction_to_light):
return np.array([0, 0, 0])
result = obj.intersect(shadow_origin, shadow_ray)
if result:
in_shadow = True
break
if in_shadow:
return np.array([0, 0, 0])
intensity = max(0, normal.dot(direction_to_light))
return intensity * light_power / (4 * np.pi * (light_position - point).norm() ** 2)
def estimate_radiance(point: Vector3, normal: Vector3) -> np.ndarray:
"""Gather the photons within `gather_radius` of `point` into a radiance."""
def estimate_radiance(point, normal):
# Gather photons within the gather_radius
accumulated_power = np.array([0.0, 0.0, 0.0])
for photon_pos, photon_power in photon_map:
distance = (photon_pos - point).norm()
@ -143,62 +224,27 @@ def estimate_radiance(point: Vector3, normal: Vector3) -> np.ndarray:
return accumulated_power / (area * num_photons)
def trace_ray(ray_origin: Vector3, ray_direction: Vector3) -> np.ndarray:
"""Shade one camera ray with direct light plus gathered photons."""
hit = nearest_hit(ray_origin, ray_direction)
if hit is None:
return np.array([0, 0, 0]) # Background color
hit_object, hit_point, normal = hit
direct_light = compute_direct_light(hit_point, normal)
indirect_light = estimate_radiance(hit_point, normal)
return cast("np.ndarray", hit_object.color * (direct_light + indirect_light))
# Main execution
if __name__ == "__main__":
print("Emitting photons...")
emit_photons()
def render_image(width: int, height: int) -> np.ndarray:
"""Shoot one camera ray per pixel and return the `height` x `width` image."""
aspect_ratio = width / height
fov = np.pi / 3 # 60 degrees field of view
image = np.zeros((height, width, 3))
for y in range(height):
for x in range(width):
# Convert pixel coordinate to camera ray
px = (2 * (x + 0.5) / width - 1) * np.tan(fov / 2) * aspect_ratio
py = (1 - 2 * (y + 0.5) / height) * np.tan(fov / 2)
ray_direction = Vector3(px, py, -1).normalize()
image[y, x, :] = np.clip(trace_ray(Vector3(0, 0, 0), ray_direction), 0, 1)
return image
def main() -> None:
"""Emit photons, render the image and show it."""
logger.info("Emitting photons...")
photon_traces = emit_photons()
logger.info("Rendering image...")
print("Rendering image...")
width = 100
height = 100
t0 = time.time()
image = render_image(width, height)
logger.info(
"Render Took: %ss\nresolution: %sx%s\nphotons (emitted): %s\n"
"photons (reflected): %s\nphotons (total): %s\nrays: %s",
round(time.time() - t0, 2),
width,
height,
num_photons,
photon_traces - num_photons,
photon_traces,
width * height,
print(
f"Render Took: {round(time.time() - t0, 2)}s\n"
f"resolution: {width}x{height}\n"
f"photons (emitted): {num_photons}\n"
f"photons (reflected): {PHOTONS - num_photons}\n"
f"photons (total): {PHOTONS}\n"
f"rays: {width * height}"
)
# Display the image
plt.imshow(image)
plt.axis("off")
plt.show()
# Main execution
if __name__ == "__main__":
logging.basicConfig(format="%(message)s", level=logging.INFO)
main()

11
Programming/TRAK/lab6.py Executable file → Normal file
View File

@ -1,11 +1,2 @@
#!/usr/bin/env python3
"""Lab 6 driver: run another script in this directory by path.
`script_path` was filled in by hand during the lab, which is why it is empty
here -- the file is kept as submitted.
"""
import runpy
script_path = "" # path to script
runpy.run_path(script_path, run_name="__main__")
exec(compile(open(script_path).read(), script_path, "exec"))

57
Programming/TRAK/main.py Executable file → Normal file
View File

@ -1,25 +1,14 @@
#!/usr/bin/env python3
"""Entry point: render a scene with one of the three algorithms in this course.
The algorithm, scene, resolution and output path all default to `config.ini`
and are overridable on the command line.
"""
import argparse
import importlib
import logging
from pathlib import Path
import os
import matplotlib.pyplot as plt
from photon_mapping import render_photon_mapping
from rendering import ray_trace
from utils import load_config, parse_resolution
logger = logging.getLogger(__name__)
def main() -> None:
"""Parse the command line over `config.ini` defaults and run the renderer."""
def main():
# default config
config = load_config("config.ini")
@ -109,64 +98,58 @@ def main() -> None:
# Run the selected algorithm
if args.algorithm == "ray_tracing0":
logger.info("Starting ray tracing zero...")
print("Starting ray tracing zero...")
# ray_trace(args.scene, args.environment_map, image_width=width, image_height=height, output_file="output_ray_traced.png")
ray_trace(
args.num_spheres,
args.environment,
args.environment_map,
image_width=width,
# na razie generujemy w kodzie, ale potem trzeba będzie obj wczytywać
image_height=height,
output_file=Path("outputs") / args.output,
image_height=height, # na razie generujemy w kodzie, ale potem trzeba będzie obj wczytywać
output_file="output_ray_traced.png",
)
elif args.algorithm == "ray_tracing":
logger.info("Starting ray tracing...")
print("Starting ray tracing...")
try:
logger.info("%s", args.scene)
print(args.scene)
scene_module = importlib.import_module(f"scenes.{args.scene}")
except ModuleNotFoundError:
logger.info(
"Error: Scene '%s' not found in the 'scenes' directory.", args.scene
)
print(f"Error: Scene '{args.scene}' not found in the 'scenes' directory.")
return
try:
scene = scene_module.setup_scene(
width=width, height=height, environment=f"{args.environment}"
)
except AttributeError:
logger.info(
"Error: Scene '%s' does not define a `setup_scene` function.",
args.scene,
print(
f"Error: Scene '{args.scene}' does not define a `setup_scene` function."
)
return
# Renderowanie
logger.info(
"Rendering scene '%s' with %s samples per pixel...",
args.scene,
args.samples_per_pixel,
print(
f"Rendering scene '{args.scene}' with {args.samples_per_pixel} samples per pixel..."
)
img = scene.render(samples_per_pixel=args.samples_per_pixel)
output_path = Path("outputs") / args.output
output_path = os.path.join("outputs", args.output)
img.save(output_path)
logger.info("Image saved to %s", output_path)
print(f"Image saved to {output_path}")
if args.show:
img.show()
elif args.algorithm == "photon_mapping":
logger.info("Starting photon mapping...")
print("Starting photon mapping...")
image = render_photon_mapping(
width, height, args.num_photons, args.max_depth, args.gather_radius
)
plt.imshow(image)
plt.axis("off")
output_path = Path("outputs") / args.output
output_path = os.path.join("outputs", args.output)
plt.savefig(output_path)
logger.info("Image saved to %s", output_path)
print(f"Image saved to {output_path}")
if args.show:
plt.show()
else:
logger.info("Unknown algorithm: %s", args.algorithm)
print(f"Unknown algorithm: {args.algorithm}")
return
if __name__ == "__main__":
logging.basicConfig(format="%(message)s", level=logging.INFO)
main()

View File

@ -1,114 +0,0 @@
#!/usr/bin/env python3
"""Vectors, photons and the two surfaces the photon mapper traces.
Split out of `photon_mapping.py` so each file stays under this repo's
250-line cap; the classes are unchanged.
"""
from __future__ import annotations
import numpy as np
# A ray whose direction is this close to parallel with a plane never hits it.
_PARALLEL_EPSILON = 1e-6
class Vector3:
"""A 3D vector, with just the operations this renderer needs."""
def __init__(self, x: float, y: float, z: float) -> None:
"""Store the three components."""
self.x = x
self.y = y
self.z = z
def __add__(self, other: Vector3) -> Vector3:
"""Return the component-wise sum."""
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other: Vector3) -> Vector3:
"""Return the component-wise difference."""
return Vector3(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, scalar: float) -> Vector3:
"""Return this vector scaled by `scalar`."""
return Vector3(self.x * scalar, self.y * scalar, self.z * scalar)
def dot(self, other: Vector3) -> float:
"""Return the dot product with `other`."""
return self.x * other.x + self.y * other.y + self.z * other.z
def norm(self) -> float:
"""Return the length of this vector."""
return float(np.sqrt(self.dot(self)))
def normalize(self) -> Vector3:
"""Return a new vector of unit length pointing the same way."""
n = self.norm()
return Vector3(self.x / n, self.y / n, self.z / n)
class Photon:
"""A packet of light energy travelling in a straight line."""
def __init__(
self, position: Vector3, direction: Vector3, power: np.ndarray
) -> None:
"""Store where the photon is, where it is going, and what it carries."""
self.position = position
self.direction = direction
self.power = power
class Sphere:
"""A sphere of uniform colour."""
def __init__(self, center: Vector3, radius: float, color: np.ndarray) -> None:
"""Store the sphere's geometry and colour."""
self.center = center
self.radius = radius
self.color = color
def intersect(
self, ray_origin: Vector3, ray_direction: Vector3
) -> tuple[float, Vector3, Vector3] | None:
"""Return the nearest hit as (distance, point, normal), or None."""
oc = ray_origin - self.center
a = ray_direction.dot(ray_direction)
b = 2.0 * oc.dot(ray_direction)
c = oc.dot(oc) - self.radius * self.radius
discriminant = b * b - 4 * a * c
if discriminant < 0:
return None
t = (-b - np.sqrt(discriminant)) / (2.0 * a)
if t < 0:
t = (-b + np.sqrt(discriminant)) / (2.0 * a)
if t < 0:
return None
hit_point = ray_origin + ray_direction * t
normal = (hit_point - self.center).normalize()
return (t, hit_point, normal)
class Plane:
"""An infinite plane of uniform colour."""
def __init__(self, point: Vector3, normal: Vector3, color: np.ndarray) -> None:
"""Store a point on the plane, its (normalised) normal, and its colour."""
self.point = point
self.normal = normal.normalize()
self.color = color
def intersect(
self, ray_origin: Vector3, ray_direction: Vector3
) -> tuple[float, Vector3, Vector3] | None:
"""Return the nearest hit as (distance, point, normal), or None."""
denom = self.normal.dot(ray_direction)
if abs(denom) > _PARALLEL_EPSILON:
t = (self.point - ray_origin).dot(self.normal) / denom
if t >= 0:
hit_point = ray_origin + ray_direction * t
return (t, hit_point, self.normal)
return None
Surface = Sphere | Plane

284
Programming/TRAK/photon_mapping.py Executable file → Normal file
View File

@ -1,150 +1,181 @@
#!/usr/bin/env python3
"""A two-pass photon mapper: scatter photons from the light, then gather them.
The first pass emits `num_photons` from the light and records every surface
they land on. The second pass shoots one camera ray per pixel and shades each
hit with direct light plus the photons gathered within `gather_radius`.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import cast
import numpy as np
from photon_geometry import Photon, Plane, Sphere, Surface, Vector3
# Shadow rays start this far off the surface they were cast from.
_SHADOW_OFFSET = 1e-5
# Fraction of its power a photon keeps across one diffuse bounce.
_BOUNCE_ABSORPTION = 0.8
# Define basic vector operations
class Vector3:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector3(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, scalar):
return Vector3(self.x * scalar, self.y * scalar, self.z * scalar)
def dot(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def norm(self):
return np.sqrt(self.dot(self))
def normalize(self):
n = self.norm()
return Vector3(self.x / n, self.y / n, self.z / n)
@dataclass
class Scene:
"""Everything the two passes share: the geometry, the light, the photons."""
objects: list[Surface]
rng: np.random.Generator
light_position: Vector3
light_power: np.ndarray
gather_radius: float
photon_map: list[tuple[Vector3, np.ndarray]]
class Photon:
def __init__(self, position, direction, power):
self.position = position
self.direction = direction
self.power = power
def random_unit_vector(rng: np.random.Generator) -> Vector3:
"""Draw a direction uniformly over the sphere."""
theta = rng.uniform(0, 2 * np.pi)
z = rng.uniform(-1, 1)
r = np.sqrt(1 - z * z)
return Vector3(r * np.cos(theta), r * np.sin(theta), z)
class Sphere:
def __init__(self, center, radius, color):
self.center = center
self.radius = radius
self.color = color
def intersect(self, ray_origin, ray_direction):
oc = ray_origin - self.center
a = ray_direction.dot(ray_direction)
b = 2.0 * oc.dot(ray_direction)
c = oc.dot(oc) - self.radius * self.radius
discriminant = b * b - 4 * a * c
if discriminant < 0:
return None
t = (-b - np.sqrt(discriminant)) / (2.0 * a)
if t < 0:
t = (-b + np.sqrt(discriminant)) / (2.0 * a)
if t < 0:
return None
hit_point = ray_origin + ray_direction * t
normal = (hit_point - self.center).normalize()
return (t, hit_point, normal)
def random_hemisphere_direction(rng: np.random.Generator, normal: Vector3) -> Vector3:
"""Draw a direction uniformly over the hemisphere around `normal`."""
direction = random_unit_vector(rng)
if direction.dot(normal) < 0:
direction = Vector3(-direction.x, -direction.y, -direction.z)
return direction
class Plane:
def __init__(self, point, normal, color):
self.point = point
self.normal = normal.normalize()
self.color = color
def nearest_hit(
objects: list[Surface], ray_origin: Vector3, ray_direction: Vector3
) -> tuple[Surface, Vector3, Vector3] | None:
"""Return the closest surface the ray meets, with its point and normal."""
closest_t = np.inf
hit_object = None
hit_info = None
for obj in objects:
result = obj.intersect(ray_origin, ray_direction)
if result:
t, hit_point, normal = result
if t < closest_t:
closest_t = t
hit_object = obj
hit_info = (hit_point, normal)
if hit_object is None or hit_info is None:
def intersect(self, ray_origin, ray_direction):
denom = self.normal.dot(ray_direction)
if abs(denom) > 1e-6:
t = (self.point - ray_origin).dot(self.normal) / denom
if t >= 0:
hit_point = ray_origin + ray_direction * t
return (t, hit_point, self.normal)
return None
return (hit_object, hit_info[0], hit_info[1])
def trace_photon(scene: Scene, photon: Photon, depth: int, max_depth: int) -> None:
"""Bounce one photon through the scene, recording every surface it lands on."""
if depth > max_depth:
return
hit = nearest_hit(scene.objects, photon.position, photon.direction)
if hit is not None:
_, hit_point, normal = hit
scene.photon_map.append((hit_point, photon.power))
photon.position = hit_point
photon.direction = random_hemisphere_direction(scene.rng, normal)
photon.power = photon.power * _BOUNCE_ABSORPTION
trace_photon(scene, photon, depth + 1, max_depth)
def render_photon_mapping(width, height, num_photons, max_depth, gather_radius):
# Photon mapping logic
photon_map = []
sphere = Sphere(Vector3(0, 0, -5), 1.0, np.array([1, 0, 0])) # Red sphere
plane = Plane(
Vector3(0, -1, 0), Vector3(0, 1, 0), np.array([0.5, 0.5, 0.5])
) # Gray plane
objects = [sphere, plane]
light_position = Vector3(-5, 5, -5)
light_power = np.array([1, 1, 1]) * 1000
def emit_photons(scene: Scene, num_photons: int, max_depth: int) -> None:
"""Run the scatter pass: emit `num_photons` from the light and trace each."""
for _ in range(num_photons):
direction = random_unit_vector(scene.rng)
power = scene.light_power / num_photons
photon = Photon(scene.light_position, direction, power)
trace_photon(scene, photon, 0, max_depth)
def emit_photons():
for _ in range(num_photons):
direction = random_unit_vector()
power = light_power / num_photons
photon = Photon(light_position, direction, power)
trace_photon(photon, 0)
def trace_photon(photon, depth):
if depth > max_depth:
return
closest_t = np.inf
hit_object = None
hit_info = None
for obj in objects:
result = obj.intersect(photon.position, photon.direction)
if result:
t, hit_point, normal = result
if t < closest_t:
closest_t = t
hit_object = obj
hit_info = (hit_point, normal)
if hit_object:
hit_point, normal = hit_info
photon_map.append((hit_point, photon.power))
new_direction = random_hemisphere_direction(normal)
photon.position = hit_point
photon.direction = new_direction
photon.power = photon.power * 0.8
trace_photon(photon, depth + 1)
def compute_direct_light(scene: Scene, point: Vector3, normal: Vector3) -> np.ndarray:
"""Return the light arriving straight from the source, or black if shadowed."""
direction_to_light = (scene.light_position - point).normalize()
shadow_origin = point + normal * _SHADOW_OFFSET
for obj in scene.objects:
if obj.intersect(shadow_origin, direction_to_light):
return np.array([0, 0, 0])
intensity = max(0, normal.dot(direction_to_light))
distance_squared = (scene.light_position - point).norm() ** 2
return intensity * scene.light_power / (4 * np.pi * distance_squared)
def random_unit_vector():
theta = np.random.uniform(0, 2 * np.pi)
z = np.random.uniform(-1, 1)
r = np.sqrt(1 - z * z)
return Vector3(r * np.cos(theta), r * np.sin(theta), z)
def random_hemisphere_direction(normal):
dir = random_unit_vector()
if dir.dot(normal) < 0:
dir = Vector3(-dir.x, -dir.y, -dir.z)
return dir
def estimate_radiance(scene: Scene, point: Vector3, normal: Vector3) -> np.ndarray:
"""Gather the photons within `gather_radius` of `point` into a radiance."""
accumulated_power = np.array([0.0, 0.0, 0.0])
for photon_pos, photon_power in scene.photon_map:
distance = (photon_pos - point).norm()
if distance < scene.gather_radius:
weight = max(0, normal.dot((photon_pos - point).normalize()))
accumulated_power += photon_power * weight
area = np.pi * scene.gather_radius**2
return accumulated_power / area
def trace_ray(scene: Scene, ray_origin: Vector3, ray_direction: Vector3) -> np.ndarray:
"""Shade one camera ray with direct light plus gathered photons."""
hit = nearest_hit(scene.objects, ray_origin, ray_direction)
if hit is None:
def trace_ray(ray_origin, ray_direction):
closest_t = np.inf
hit_object = None
hit_info = None
for obj in objects:
result = obj.intersect(ray_origin, ray_direction)
if result:
t, hit_point, normal = result
if t < closest_t:
closest_t = t
hit_object = obj
hit_info = (hit_point, normal, obj.color)
if hit_object:
hit_point, normal, color = hit_info
direct_light = compute_direct_light(hit_point, normal)
indirect_light = estimate_radiance(hit_point, normal)
return color * (direct_light + indirect_light)
return np.array([0, 0, 0])
hit_object, hit_point, normal = hit
direct_light = compute_direct_light(scene, hit_point, normal)
indirect_light = estimate_radiance(scene, hit_point, normal)
return cast("np.ndarray", hit_object.color * (direct_light + indirect_light))
def compute_direct_light(point, normal):
direction_to_light = (light_position - point).normalize()
shadow_origin = point + normal * 1e-5
shadow_ray = direction_to_light
in_shadow = False
for obj in objects:
result = obj.intersect(shadow_origin, shadow_ray)
if result:
in_shadow = True
break
if in_shadow:
return np.array([0, 0, 0])
intensity = max(0, normal.dot(direction_to_light))
return (
intensity * light_power / (4 * np.pi * (light_position - point).norm() ** 2)
)
def render_photon_mapping(
width: int, height: int, num_photons: int, max_depth: int, gather_radius: float
) -> np.ndarray:
"""Render the fixed red-sphere-over-grey-plane scene and return the image."""
scene = Scene(
objects=[
Sphere(Vector3(0, 0, -5), 1.0, np.array([1, 0, 0])), # Red sphere
Plane(Vector3(0, -1, 0), Vector3(0, 1, 0), np.array([0.5, 0.5, 0.5])),
],
rng=np.random.default_rng(),
light_position=Vector3(-5, 5, -5),
light_power=np.array([1, 1, 1]) * 1000,
gather_radius=gather_radius,
photon_map=[],
)
emit_photons(scene, num_photons, max_depth)
def estimate_radiance(point, normal):
accumulated_power = np.array([0.0, 0.0, 0.0])
for photon_pos, photon_power in photon_map:
distance = (photon_pos - point).norm()
if distance < gather_radius:
weight = max(0, normal.dot((photon_pos - point).normalize()))
accumulated_power += photon_power * weight
area = np.pi * gather_radius**2
return accumulated_power / area
emit_photons()
aspect_ratio = width / height
fov = np.pi / 3
@ -153,8 +184,9 @@ def render_photon_mapping(
for x in range(width):
px = (2 * (x + 0.5) / width - 1) * np.tan(fov / 2) * aspect_ratio
py = (1 - 2 * (y + 0.5) / height) * np.tan(fov / 2)
ray_origin = Vector3(0, 0, 0)
ray_direction = Vector3(px, py, -1).normalize()
color = trace_ray(scene, Vector3(0, 0, 0), ray_direction)
color = trace_ray(ray_origin, ray_direction)
image[y, x, :] = np.clip(color, 0, 1)
return image

View File

@ -1,233 +0,0 @@
#!/usr/bin/env python3
"""Ray/geometry intersection and Phong shading for the `ray_tracing0` renderer.
These were nested closures inside `rendering.ray_trace`, which is what made
that one function 460 lines long. They are pure now: the scene and the light
constants are passed in rather than captured, so each can be read on its own.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, cast
import numpy as np
# A scene object is a plain dict tagged with "type": "sphere" or "plane".
SceneObject = dict[str, Any]
# A ray whose direction is this close to parallel with a plane never hits it.
_PARALLEL_EPSILON = 1e-6
# Shadow and reflection rays start this far off the surface, so that the
# surface they just left does not intersect them at t=0.
SURFACE_OFFSET = 0.0001
@dataclass(frozen=True)
class Lighting:
"""The single point light and the Phong coefficients every surface uses."""
position: np.ndarray
color: np.ndarray
ambient: float
diffuse_c: float
specular_c: float
specular_k: int
def normalize(vector: np.ndarray) -> np.ndarray:
"""Scale `vector` to unit length, in place, and return it."""
vector /= np.linalg.norm(vector)
return vector
def intersect_plane(
ray_origin: np.ndarray,
ray_direction: np.ndarray,
plane_point: np.ndarray,
plane_normal: np.ndarray,
) -> float:
"""Distance along the ray to the plane, or +inf if it never reaches it."""
denom = np.dot(ray_direction, plane_normal)
if np.abs(denom) < _PARALLEL_EPSILON:
return np.inf
d = np.dot(plane_point - ray_origin, plane_normal) / denom
if d < 0:
return np.inf
return float(d)
def calculate_sphere_intersection(a: float, b: float, c: float, disc: float) -> float:
"""Solve `a*t^2 + b*t + c` for the nearest root ahead of the ray origin.
`disc` is the discriminant, passed in because the caller already has it.
The root is taken via the numerically stable `q` form rather than the
textbook quadratic formula, which loses precision when `b` dominates.
"""
if disc > 0:
distance_squared = np.sqrt(disc)
q = (-b - distance_squared) / 2.0 if b < 0 else (-b + distance_squared) / 2.0
t0 = q / a
t1 = c / q
t0, t1 = min(t0, t1), max(t0, t1)
if t1 >= 0:
return float(t1) if t0 < 0 else float(t0)
return np.inf
def intersect_sphere(
ray_origin: np.ndarray,
ray_direction: np.ndarray,
sphere_center: np.ndarray,
sphere_radius: float,
) -> float:
"""Distance along the ray to the sphere, or +inf if it misses."""
a = np.dot(ray_direction, ray_direction)
origin_to_center = ray_origin - sphere_center
b = 2 * np.dot(ray_direction, origin_to_center)
radius_squared = sphere_radius * sphere_radius
c = np.dot(origin_to_center, origin_to_center) - radius_squared
disc = b * b - 4 * a * c
return calculate_sphere_intersection(a, b, c, disc)
def intersect(
ray_origin: np.ndarray, ray_direction: np.ndarray, object_: SceneObject
) -> float:
"""Dispatch to the plane or sphere intersection for `object_`."""
if object_["type"] == "plane":
return intersect_plane(
ray_origin, ray_direction, object_["position"], object_["normal"]
)
return intersect_sphere(
ray_origin, ray_direction, object_["position"], object_["radius"]
)
def get_normal(object_: SceneObject, intersection_point: np.ndarray) -> np.ndarray:
"""Surface normal of `object_` at `intersection_point`."""
if object_["type"] == "sphere":
return normalize(intersection_point - object_["position"])
if object_["type"] == "plane":
return cast("np.ndarray", object_["normal"])
msg = f"Unknown object type: {object_['type']}"
raise ValueError(msg)
def get_color(object_: SceneObject, intersection_point: np.ndarray) -> np.ndarray:
"""Return the colour of `object_`: either a constant or a function of position."""
color = object_["color"]
if not hasattr(color, "__len__"):
color = color(intersection_point)
return cast("np.ndarray", color)
def find_intersection(
scene: list[SceneObject], ray_origin: np.ndarray, ray_direction: np.ndarray
) -> tuple[float, int]:
"""Return the distance to the nearest hit and that object's scene index.
The index is -1 when the ray hits nothing, in which case the distance is
+inf and callers stop.
"""
t = np.inf
obj_idx = -1
for index, object_ in enumerate(scene):
t_obj = intersect(ray_origin, ray_direction, object_)
if t_obj < t:
t, obj_idx = t_obj, index
return t, obj_idx
def is_shadowed(
scene: list[SceneObject],
lighting: Lighting,
intersection_point: np.ndarray,
normal: np.ndarray,
obj_idx: int,
) -> bool:
"""Report whether anything but object `obj_idx` blocks the light here."""
to_light = normalize(lighting.position - intersection_point)
shadow_intersections = [
intersect(intersection_point + normal * SURFACE_OFFSET, to_light, obj_sh)
for k, obj_sh in enumerate(scene)
if k != obj_idx
]
return bool(shadow_intersections) and min(shadow_intersections) < np.inf
def compute_color(
lighting: Lighting,
object_: SceneObject,
intersection_point: np.ndarray,
normal: np.ndarray,
ray_origin: np.ndarray,
) -> tuple[SceneObject, np.ndarray, np.ndarray, np.ndarray]:
"""Shade the hit with Blinn-Phong and return it alongside the hit geometry."""
color = get_color(object_, intersection_point)
to_light = normalize(lighting.position - intersection_point)
to_origin = normalize(ray_origin - intersection_point)
color_ray = lighting.ambient
diffuse_intensity = object_.get("diffuse_c", lighting.diffuse_c) * max(
np.dot(normal, to_light), 0
)
color_ray += diffuse_intensity * color
half_vector = normalize(to_light + to_origin)
specular_intensity = (
object_.get("specular_c", lighting.specular_c)
* max(np.dot(normal, half_vector), 0) ** lighting.specular_k
)
color_ray += specular_intensity * lighting.color
return object_, intersection_point, normal, color_ray
def trace_ray(
scene: list[SceneObject],
lighting: Lighting,
ray_origin: np.ndarray,
ray_direction: np.ndarray,
) -> tuple[SceneObject, np.ndarray, np.ndarray, np.ndarray] | None:
"""Trace one ray and return its hit, or None if it misses or lands in shadow."""
t, obj_idx = find_intersection(scene, ray_origin, ray_direction)
if t == np.inf:
return None
object_ = scene[obj_idx]
intersection_point = ray_origin + ray_direction * t
normal = get_normal(object_, intersection_point)
if is_shadowed(scene, lighting, intersection_point, normal, obj_idx):
return None
return compute_color(lighting, object_, intersection_point, normal, ray_origin)
def make_sphere(
position: list[float], radius: float, color: np.ndarray
) -> SceneObject:
"""Build a sphere scene object."""
return {
"type": "sphere",
"position": np.array(position),
"radius": np.array(radius),
"color": np.array(color),
"reflection": 0.5,
}
def make_plane(
position: list[float],
normal: list[float],
color_a: np.ndarray,
color_b: np.ndarray,
) -> SceneObject:
"""Build a plane scene object with a checkerboard of `color_a`/`color_b`."""
return {
"type": "plane",
"position": np.array(position),
"normal": np.array(normal),
"color": lambda point: (
color_a if (int(point[0] * 2) % 2) == (int(point[2] * 2) % 2) else color_b
),
"diffuse_c": 0.75,
"specular_c": 0.5,
"reflection": 0.25,
}

518
Programming/TRAK/rendering.py Executable file → Normal file
View File

@ -1,52 +1,382 @@
#!/usr/bin/env python3
"""Renders an image using raytracing.
"""Renders an image using raytracing."""
The geometry and shading live in `raytracer`; what is left here is the scene
this lab builds (a checkerboard plane and a row of spheres) and the pixel loop
that shoots one primary ray per pixel and reflects it up to `DEPTH_MAX` times.
"""
from __future__ import annotations
import logging
import time
from typing import TYPE_CHECKING
import matplotlib.pyplot as plt
import numpy as np
from raytracer import (
SURFACE_OFFSET,
Lighting,
SceneObject,
make_plane,
make_sphere,
normalize,
trace_ray,
)
if TYPE_CHECKING:
from pathlib import Path
logger = logging.getLogger(__name__)
# Default light and material parameters.
AMBIENT = 0.05
DIFFUSE_C = 1.0
SPECULAR_C = 1.0
SPECULAR_K = 50
DEPTH_MAX = 5 # Maximum number of light reflections.
# Progress is logged every this many pixel columns.
_PROGRESS_EVERY = 10
def build_scene(num_spheres: int) -> list[SceneObject]:
"""Lay out a checkerboard plane and `num_spheres` spheres in a receding row."""
def ray_trace(
num_spheres, environment, image_width=400, image_height=300, output_file="fig.png"
):
IMAGE_WIDTH = image_width
IMAGE_HEIGHT = image_height
def normalize(vector):
"""Normalize a vector.
Parameters
----------
vector (numpy.ndarray): The input vector to be normalized.
Returns
-------
numpy.ndarray: The normalized vector.
"""
vector /= np.linalg.norm(vector)
return vector
def intersect_plane(ray_origin, ray_direction, plane_point, plane_normal):
"""Calculate the intersection of a ray with a plane.
Parameters
----------
ray_origin (numpy.ndarray): A 3D point representing the origin of the ray.
ray_direction (numpy.ndarray): A normalized 3D vector representing the
direction of the ray.
plane_point (numpy.ndarray): A 3D point representing a point on the plane.
plane_normal (numpy.ndarray): A normalized 3D vector representing
the normal of the plane.
Returns
-------
float: The distance from the origin ray_origin to the intersection
point with the plane.
Returns +inf if there is no intersection or if the intersection is
behind the origin.
"""
denom = np.dot(ray_direction, plane_normal)
if np.abs(denom) < 1e-6:
return np.inf
d = np.dot(plane_point - ray_origin, plane_normal) / denom
if d < 0:
return np.inf
return d
def intersect_sphere(ray_origin, ray_direction, sphere_center, sphere_radius):
"""Calculate the intersection of a ray with a sphere.
Parameters
----------
ray_origin (numpy.ndarray): A 3D point representing the origin of the ray.
ray_direction (numpy.ndarray): A normalized 3D vector representing the
direction of the ray.
sphere_center (numpy.ndarray): A 3D point representing
the center of the sphere.
sphere_radius (float): The radius of the sphere.
Returns
-------
float: The distance from the origin ray_origin to the intersection
point with the sphere.
Returns +inf if there is no intersection or if the intersection is
behind the origin.
"""
a = np.dot(ray_direction, ray_direction)
origin_to_center = ray_origin - sphere_center
b = 2 * np.dot(ray_direction, origin_to_center)
radius_squared = sphere_radius * sphere_radius
c = np.dot(origin_to_center, origin_to_center) - radius_squared
disc = b * b - 4 * a * c
return calculate_sphere_intersection(a, b, c, disc)
def calculate_sphere_intersection(a, b, c, disc):
"""Calculate the
intersection distance of a ray with a sphere using the quadratic formula.
Parameters
----------
a (float): Coefficient of t^2 in the quadratic equation.
b (float): Coefficient of t in the quadratic equation.
c (float): Constant term in the quadratic equation.
disc (float): Discriminant of the quadratic equation.
Returns
-------
float:
The distance from the origin to the intersection point with the sphere.
Returns +inf if there is no intersection
or if the intersection is behind the origin.
"""
if disc > 0:
distance_squared = np.sqrt(disc)
# q is used to find the roots of the quadratic equation
if b < 0:
q = (-b - distance_squared) / 2.0
else:
q = (-b + distance_squared) / 2.0
t0 = q / a
t1 = c / q
t0, t1 = min(t0, t1), max(t0, t1)
if t1 >= 0:
return t1 if t0 < 0 else t0
return np.inf
def intersect(ray_origin, ray_direction, object_):
"""Calculate the intersection of a ray with an object.
Parameters
----------
ray_origin (numpy.ndarray): A 3D point representing the origin of the ray.
ray_direction (numpy.ndarray): A normalized 3D vector representing the
direction of the ray.
obj (dict): A dictionary representing the object with keys
'type', 'position', 'normal' (for planes), and 'radius' (for spheres).
Returns
-------
float: The distance from the origin ray_origin to the intersection
point with the object.
Returns +inf if there is no intersection or if the intersection is
behind the origin.
"""
if object_["type"] == "plane":
return intersect_plane(
ray_origin, ray_direction, object_["position"], object_["normal"]
)
# object_['type'] == 'sphere':
return intersect_sphere(
ray_origin, ray_direction, object_["position"], object_["radius"]
)
def get_normal(object_, intersection_point):
"""Calculate the normal at the intersection point on the object.
Parameters
----------
obj (dict): A dictionary representing the object with keys
'type' and 'position'.
intersection_point (numpy.ndarray): A 3D point representing the
intersection point on the object.
Returns
-------
numpy.ndarray: The normal vector at the intersection point.
"""
if object_["type"] == "sphere":
normal = normalize(intersection_point - object_["position"])
elif object_["type"] == "plane":
normal = object_["normal"]
else:
raise ValueError(f"Unknown object type: {object_['type']}")
return normal
def get_color(object_, intersection_point):
"""Get the color of the object at the intersection point.
Parameters
----------
object_ (dict): A dictionary representing the object with a key 'color'.
intersection_point (numpy.ndarray): A 3D point representing the
intersection point on the object.
Returns
-------
numpy.ndarray: The color of the object at the intersection point.
"""
color = object_["color"]
if not hasattr(color, "__len__"):
color = color(intersection_point)
return color
def trace_ray(ray_origin, ray_direction):
"""Trace a ray and find the color at the intersection point.
Parameters
----------
ray_origin (numpy.ndarray): A 3D point representing the origin of the ray.
ray_direction (numpy.ndarray):
A normalized 3D vector representing the direction of the ray.
Returns
-------
tuple: A tuple containing the object,
intersection point, normal at the intersection,
and the color at the intersection point.
Returns None if there is no intersection.
"""
t, obj_idx = find_intersection(ray_origin, ray_direction)
if t == np.inf:
return None
object_, intersection_point = get_intersection_details(
ray_origin, ray_direction, t, obj_idx
)
normal, color = (
get_normal(object_, intersection_point),
get_color(object_, intersection_point),
)
if is_shadowed(intersection_point, normal, obj_idx):
return None
return compute_color(object_, intersection_point, normal, color, ray_origin)
def find_intersection(ray_origin, ray_direction):
"""Find the intersection of a ray with the objects in the scene.
Parameters
----------
ray_origin (numpy.ndarray): A 3D point representing the origin of the ray.
ray_direction (numpy.ndarray):
A normalized 3D vector representing the direction of the ray.
Returns
-------
tuple: A tuple containing the distance to the intersection point
and the index of the intersected object.
"""
t = np.inf
obj_idx = -1
for index, object_ in enumerate(scene):
t_obj = intersect(ray_origin, ray_direction, object_)
if t_obj < t:
t, obj_idx = t_obj, index
return t, obj_idx
def get_intersection_details(ray_origin, ray_direction, t, obj_idx):
"""Get the details of the intersection point on the object.
Parameters
----------
ray_origin (numpy.ndarray): A 3D point representing the origin of the ray.
ray_direction (numpy.ndarray):
A normalized 3D vector representing the direction of the ray.
t (float): The distance to the intersection point.
obj_idx (int): The index of the intersected object in the scene.
Returns
-------
tuple: A tuple containing the intersected object
and the intersection point.
"""
object_ = scene[obj_idx]
intersection_point = ray_origin + ray_direction * t
return object_, intersection_point
def is_shadowed(intersection_point, normal, obj_idx):
"""Determine if the intersection point is in shadow.
Parameters
----------
intersection_point (numpy.ndarray):
A 3D point representing the intersection point on the object.
normal (numpy.ndarray): The normal vector at the intersection point.
obj_idx (int): The index of the intersected object in the scene.
Returns
-------
bool: True if the intersection point is in shadow, False otherwise.
"""
to_light = normalize(L - intersection_point)
shadow_intersections = [
intersect(intersection_point + normal * 0.0001, to_light, obj_sh)
for k, obj_sh in enumerate(scene)
if k != obj_idx
]
return shadow_intersections and min(shadow_intersections) < np.inf
def compute_color(object_, intersection_point, normal, color, ray_origin):
"""Compute the color at the intersection point using shading techniques.
Parameters
----------
object_ (dict): A dictionary representing the intersected object.
intersection_point (numpy.ndarray):
A 3D point representing the intersection point on the object.
normal (numpy.ndarray): The normal vector at the intersection point.
color (numpy.ndarray): The base color of the object.
ray_origin (numpy.ndarray): A 3D point representing the origin of the ray.
Returns
-------
tuple:
A tuple containing the intersected object, intersection point, normal,
and the computed color.
"""
to_light = normalize(L - intersection_point)
to_origin = normalize(ray_origin - intersection_point)
color_ray = AMBIENT
diffuse_intensity = object_.get("diffuse_c", DIFFUSE_C) * max(
np.dot(normal, to_light), 0
)
color_ray += diffuse_intensity * color
half_vector = normalize(to_light + to_origin)
specular_intensity = (
object_.get("specular_c", SPECULAR_C)
* max(np.dot(normal, half_vector), 0) ** SPECULAR_K
)
color_ray += specular_intensity * color_light
return object_, intersection_point, normal, color_ray
def add_sphere(position, radius, color):
"""Create a dictionary representing a sphere object.
Parameters
----------
position (list or numpy.ndarray):
A 3D point representing the position of the sphere.
radius (float): The radius of the sphere.
color (list or numpy.ndarray): The color of the sphere.
Returns
-------
dict: A dictionary representing the sphere object.
"""
return {
"type": "sphere",
"position": np.array(position),
"radius": np.array(radius),
"color": np.array(color),
"reflection": 0.5,
}
def add_plane(position, normal):
"""Create a dictionary representing a plane object.
Parameters
----------
position (list or numpy.ndarray):
A 3D point representing a point on the plane.
normal (list or numpy.ndarray):
A normalized 3D vector representing the normal of the plane.
Returns
-------
dict: A dictionary representing the plane object.
"""
return {
"type": "plane",
"position": np.array(position),
"normal": np.array(normal),
"color": lambda M: (
color_plane0
if (int(M[0] * 2) % 2) == (int(M[2] * 2) % 2)
else color_plane1
),
"diffuse_c": 0.75,
"specular_c": 0.5,
"reflection": 0.25,
}
scene = []
# List of objects.
color_plane0 = 1.0 * np.ones(3)
color_plane1 = 0.0 * np.ones(3)
scene = [make_plane([0.0, -0.5, 0.0], [0.0, 1.0, 0.0], color_plane0, color_plane1)]
scene.append(add_plane([0.0, -0.5, 0.0], [0.0, 1.0, 0.0]))
base_radius = 1 / np.sqrt(num_spheres) # Im więcej kul, tym mniejsze
base_distance = 4.5 / num_spheres
@ -60,87 +390,67 @@ def build_scene(num_spheres: int) -> list[SceneObject]:
color = np.array([i / num_spheres, (num_spheres - i) / num_spheres, 0.5])
# Dodanie kuli do sceny
scene.append(make_sphere([x, y, z], base_radius, color))
scene.append(add_sphere([x, y, z], base_radius, color))
return scene
# Light position and color.
L = np.array([5.0, 5.0, -10.0])
color_light = np.ones(3)
# Default light and material parameters.
AMBIENT = 0.05
DIFFUSE_C = 1.0
SPECULAR_C = 1.0
SPECULAR_K = 50
def ray_trace(
num_spheres: int,
_environment: str,
image_width: int = 400,
image_height: int = 300,
output_file: str | Path = "fig.png",
) -> None:
"""Render `num_spheres` spheres over a checkerboard and write `output_file`.
`_environment` is accepted for symmetry with the other two algorithms in
`main.py` and ignored: this renderer has no environment map.
"""
scene = build_scene(num_spheres)
lighting = Lighting(
position=np.array([5.0, 5.0, -10.0]),
color=np.ones(3),
ambient=AMBIENT,
diffuse_c=DIFFUSE_C,
specular_c=SPECULAR_C,
specular_k=SPECULAR_K,
)
color = np.zeros(3) # Current color.
DEPTH_MAX = 5 # Maximum number of light reflections.
col = np.zeros(3) # Current color.
camera_origin = np.array([0.0, 0.35, -1.0]) # Camera.
camera_target = np.array([0.0, 0.0, 0.0]) # Camera pointing to.
img = np.zeros((image_height, image_width, 3))
Q = np.array([0.0, 0.0, 0.0]) # Camera pointing to.
img = np.zeros((IMAGE_HEIGHT, IMAGE_WIDTH, 3))
aspect = float(image_width) / image_height
r = float(IMAGE_WIDTH) / IMAGE_HEIGHT
# Screen coordinates: x0, y0, x1, y1.
screen = (-1.0, -1.0 / aspect + 0.25, 1.0, 1.0 / aspect + 0.25)
S = (-1.0, -1.0 / r + 0.25, 1.0, 1.0 / r + 0.25)
render_time = time.time()
renderTime = time.time()
reflections = 0
rays = 0
primary_rays = 0
initialRays = 0
# Loop through all pixels.
for i, x in enumerate(np.linspace(screen[0], screen[2], image_width)):
if i % _PROGRESS_EVERY == 0:
logger.info("%s %%", round(i / float(image_width) * 100, 2))
for j, y in enumerate(np.linspace(screen[1], screen[3], image_height)):
color[:] = 0
camera_target[:2] = (x, y)
ray_origin = camera_origin
ray_direction = normalize(camera_target - camera_origin)
depth = 0
reflection = 1.0
primary_rays += 1
for i, x in enumerate(np.linspace(S[0], S[2], IMAGE_WIDTH)):
if i % 10 == 0:
print(round(i / float(IMAGE_WIDTH) * 100, 2), "%")
for j, y in enumerate(np.linspace(S[1], S[3], IMAGE_HEIGHT)):
col[:] = 0
Q[:2] = (x, y)
D = normalize(Q - camera_origin)
DEPTH = 0
rayO, rayD = camera_origin, D
REFLECTION = 1.0
initialRays += 1
# Loop through initial and secondary rays.
while depth < DEPTH_MAX:
traced = trace_ray(scene, lighting, ray_origin, ray_direction)
while DEPTH < DEPTH_MAX:
traced = trace_ray(rayO, rayD)
rays += 1
if not traced:
break
reflections += 1
obj, hit_point, hit_normal, color_ray = traced
obj, M, N, col_ray = traced
# Reflection: create a new ray.
ray_origin = hit_point + hit_normal * SURFACE_OFFSET
ray_direction = normalize(
ray_direction - 2 * np.dot(ray_direction, hit_normal) * hit_normal
)
depth += 1
color += reflection * color_ray
reflection *= obj.get("reflection", 1.0)
img[image_height - j - 1, i, :] = np.clip(color, 0, 1)
render_time = time.time() - render_time
rayO, rayD = M + N * 0.0001, normalize(rayD - 2 * np.dot(rayD, N) * N)
DEPTH += 1
col += REFLECTION * col_ray
REFLECTION *= obj.get("reflection", 1.0)
img[IMAGE_HEIGHT - j - 1, i, :] = np.clip(col, 0, 1)
renderTime = time.time() - renderTime
plt.imsave(output_file, img)
logger.info(
"Image saved as %s\nresolution: %sx%s\nrender time: %s s\nreflections: %s\n"
"rays (initial): %s\nrays (secondary): %s\nrays (total): %s",
output_file,
image_width,
image_height,
round(render_time, 2),
reflections,
primary_rays,
rays - primary_rays,
rays,
print(
f"Image saved as {output_file}\n"
f"resolution: {IMAGE_WIDTH}x{IMAGE_HEIGHT}\n"
f"render time: {round(renderTime, 2)} s\n"
f"reflections: {reflections}\n"
f"rays (initial): {initialRays}\n"
f"rays (secondary): {rays - initialRays}\n"
f"rays (total): {rays}"
)

View File

@ -1 +0,0 @@
"""Scene definitions, each exposing a `setup_scene(width, height, environment)`."""

View File

@ -1,35 +1,14 @@
"""The Cornell box: a closed room lit by a ceiling panel.
The reference scene for global illumination -- the colour bleeding from the
red and green walls onto the white ones is the whole point of it.
"""
from sightpy import (
Cuboid,
Diffuse,
Emissive,
Plane,
Refractive,
Scene,
Sphere,
rgb,
vec3,
)
from sightpy import *
def setup_scene(
width: int = 400, height: int = 300, environment: str | None = None
) -> Scene:
"""Build the Cornell box at `width` x `height`.
# define materials to use
def setup_scene(width=400, height=300, environment=None):
`environment` is accepted so every scene has one interface, and ignored:
the box is closed, so no background is ever visible.
"""
del environment
Sc = Scene(ambient_color=rgb(0.00, 0.00, 0.00))
scene = Scene(ambient_color=rgb(0.00, 0.00, 0.00))
angle = -0
scene.add_Camera(
Sc.add_Camera(
screen_width=width,
screen_height=height,
look_from=vec3(278, 278, 800),
@ -44,10 +23,11 @@ def setup_scene(
red_diffuse = Diffuse(diff_color=rgb(0.65, 0.05, 0.05))
white_diffuse = Diffuse(diff_color=rgb(0.73, 0.73, 0.73))
emissive_white = Emissive(color=rgb(15.0, 15.0, 15.0))
emissive_blue = Emissive(color=rgb(2.0, 2.0, 3.5))
blue_glass = Refractive(n=vec3(1.5 + 0.05e-8j, 1.5 + 0.02e-8j, 1.5 + 0.0j))
# this is the light
scene.add(
Sc.add(
Plane(
material=emissive_white,
center=vec3(213 + 130 / 2, 554, -227.0 - 105 / 2),
@ -59,7 +39,7 @@ def setup_scene(
importance_sampled=True,
)
scene.add(
Sc.add(
Plane(
material=white_diffuse,
center=vec3(555 / 2, 555 / 2, -555.0),
@ -70,7 +50,7 @@ def setup_scene(
)
)
scene.add(
Sc.add(
Plane(
material=green_diffuse,
center=vec3(-0.0, 555 / 2, -555 / 2),
@ -81,7 +61,7 @@ def setup_scene(
)
)
scene.add(
Sc.add(
Plane(
material=red_diffuse,
center=vec3(555.0, 555 / 2, -555 / 2),
@ -92,7 +72,7 @@ def setup_scene(
)
)
scene.add(
Sc.add(
Plane(
material=white_diffuse,
center=vec3(555 / 2, 555, -555 / 2),
@ -103,7 +83,7 @@ def setup_scene(
)
)
scene.add(
Sc.add(
Plane(
material=white_diffuse,
center=vec3(555 / 2, 0.0, -555 / 2),
@ -123,9 +103,9 @@ def setup_scene(
shadow=False,
)
cb.rotate(θ=15, u=vec3(0, 1, 0))
scene.add(cb)
Sc.add(cb)
scene.add(
Sc.add(
Sphere(
material=blue_glass,
center=vec3(370.5, 165 / 2, -65 - 185 / 2),
@ -136,4 +116,4 @@ def setup_scene(
importance_sampled=True,
)
return scene
return Sc

View File

@ -1,22 +1,14 @@
"""One soap bubble in front of a blurred backdrop.
The colours come from thin-film interference, not from a texture: the shell
is a few hundred nanometres thick, so different wavelengths cancel at
different angles.
"""
import numpy as np
from sightpy import Scene, Sphere, ThinFilmInterference, rgb, vec3
from sightpy import *
def setup_scene(
width: int = 400, height: int = 300, environment: str = "lake.png"
) -> Scene:
"""Build the soap-bubble scene at `width` x `height` over `environment`."""
scene = Scene(ambient_color=rgb(0.01, 0.01, 0.01))
# define materials to use
def setup_scene(width=400, height=300, environment="lake.png"):
# Set Scene
Sc = Scene(ambient_color=rgb(0.01, 0.01, 0.01))
angle = -np.pi * 0.5
scene.add_Camera(
Sc.add_Camera(
screen_height=height,
screen_width=width,
look_from=vec3(4.0 * np.sin(angle), 0.00, 4.0 * np.cos(angle)),
@ -24,7 +16,7 @@ def setup_scene(
)
soap_bubble = ThinFilmInterference(thickness=330, noise=60.0)
scene.add(
Sc.add(
Sphere(
material=soap_bubble,
center=vec3(1.0, 0.0, 1.5),
@ -34,6 +26,6 @@ def setup_scene(
)
)
scene.add_Background(environment, blur=10.0)
Sc.add_Background(environment, blur=10.0)
return scene
return Sc

View File

@ -1,17 +1,9 @@
"""Three coloured glass spheres on a checkered floor, over a photo backdrop.
Each sphere filters a different channel, so the floor seen through them shows
what the refractive material does to each colour separately.
"""
import numpy as np
from sightpy import Glossy, Plane, Refractive, Scene, Sphere, image, rgb, vec3
from sightpy import *
def setup_scene(
width: int = 400, height: int = 300, environment: str = "miramar.jpeg"
) -> Scene:
"""Build the three-sphere scene at `width` x `height` over `environment`."""
# define materials to use
def setup_scene(width=400, height=300, environment="miramar.jpeg"):
blue_glass = Refractive(
n=vec3(1.5 + 4e-8j, 1.5 + 4e-8j, 1.5 + 0.0j)
) # n = index of refraction
@ -28,19 +20,19 @@ def setup_scene(
# Set Scene
scene = Scene(ambient_color=rgb(0.05, 0.05, 0.05))
Sc = Scene(ambient_color=rgb(0.05, 0.05, 0.05))
angle = np.pi / 2 * 0.3
scene.add_Camera(
Sc.add_Camera(
look_from=vec3(2.5 * np.sin(angle), 0.25, 2.5 * np.cos(angle) - 1.5),
look_at=vec3(0.0, 0.25, -1.5),
screen_width=width,
screen_height=height,
)
scene.add_DirectionalLight(Ldir=vec3(0.52, 0.45, -0.5), color=rgb(0.15, 0.15, 0.15))
Sc.add_DirectionalLight(Ldir=vec3(0.52, 0.45, -0.5), color=rgb(0.15, 0.15, 0.15))
scene.add(
Sc.add(
Sphere(
material=blue_glass,
center=vec3(-1.2, 0.0, -1.5),
@ -49,7 +41,7 @@ def setup_scene(
max_ray_depth=3,
)
)
scene.add(
Sc.add(
Sphere(
material=green_glass,
center=vec3(0.0, 0.0, -1.5),
@ -58,7 +50,7 @@ def setup_scene(
max_ray_depth=3,
)
)
scene.add(
Sc.add(
Sphere(
material=red_glass,
center=vec3(1.2, 0.0, -1.5),
@ -68,7 +60,7 @@ def setup_scene(
)
)
scene.add(
Sc.add(
Plane(
material=floor,
center=vec3(0, -0.5, -3.0),
@ -81,6 +73,6 @@ def setup_scene(
)
# see sightpy/backgrounds
scene.add_Background(environment)
Sc.add_Background(environment)
return scene
return Sc

View File

@ -1,16 +1,8 @@
"""A rotated block of green glass standing on a checkered floor.
The floor is deliberately close and low-repeat, so the refraction through the
block is easy to compare against the undistorted tiles beside it.
"""
from sightpy import Cuboid, Glossy, Plane, Refractive, Scene, image, rgb, vec3
from sightpy import *
def setup_scene(
width: int = 400, height: int = 300, environment: str = "stormydays.png"
) -> Scene:
"""Build the glass-cuboid scene at `width` x `height` over `environment`."""
# define materials to use
def setup_scene(width=400, height=300, environment="stormydays.png"):
floor = Glossy(
diff_color=image("checkered_floor.png", repeat=2.0),
roughness=0.2,
@ -20,17 +12,17 @@ def setup_scene(
) # n = index of refraction
green_glass = Refractive(n=vec3(1.5 + 4e-8j, 1.5 + 0.0j, 1.5 + 4e-8j))
scene = Scene()
scene.add_Camera(
Sc = Scene()
Sc.add_Camera(
look_from=vec3(0.0, 0.25, 1.0),
look_at=vec3(0.0, 0.25, -3.0),
screen_width=width,
screen_height=height,
)
scene.add_DirectionalLight(Ldir=vec3(0.0, 0.5, 0.5), color=rgb(0.5, 0.5, 0.5))
Sc.add_DirectionalLight(Ldir=vec3(0.0, 0.5, 0.5), color=rgb(0.5, 0.5, 0.5))
scene.add(
Sc.add(
Plane(
material=floor,
center=vec3(0, -0.5, -3.0),
@ -52,9 +44,9 @@ def setup_scene(
max_ray_depth=5,
)
cb.rotate(θ=30, u=vec3(0, 1, 0))
scene.add(cb)
Sc.add(cb)
# see sightpy/backgrounds
scene.add_Background(environment)
Sc.add_Background(environment)
return scene
return Sc

View File

@ -1,17 +1,8 @@
"""Two metal spheres -- gold and bluish -- on a checkered floor.
Both use the Glossy material, so this is the scene where the complex index of
refraction and the roughness parameter are easiest to read off the render.
"""
import numpy as np
from sightpy import Glossy, Plane, Scene, Sphere, image, rgb, vec3
from sightpy import *
def setup_scene(
width: int = 400, height: int = 300, environment: str = "stormydays.png"
) -> Scene:
"""Build the two-sphere scene at `width` x `height` over `environment`."""
# define materials to use
def setup_scene(width=400, height=300, environment="stormydays.png"):
gold_metal = Glossy(
diff_color=rgb(1.0, 0.572, 0.184),
n=vec3(0.15 + 3.58j, 0.4 + 2.37j, 1.54 + 1.91j),
@ -36,19 +27,19 @@ def setup_scene(
)
# Set Scene
scene = Scene(ambient_color=rgb(0.05, 0.05, 0.05))
Sc = Scene(ambient_color=rgb(0.05, 0.05, 0.05))
angle = -np.pi / 2 * 0.3
scene.add_Camera(
Sc.add_Camera(
look_from=vec3(2.5 * np.sin(angle), 0.25, 2.5 * np.cos(angle) - 1.5),
look_at=vec3(0.0, 0.25, -3.0),
screen_width=width,
screen_height=height,
)
scene.add_DirectionalLight(Ldir=vec3(0.52, 0.45, -0.5), color=rgb(0.15, 0.15, 0.15))
Sc.add_DirectionalLight(Ldir=vec3(0.52, 0.45, -0.5), color=rgb(0.15, 0.15, 0.15))
scene.add(
Sc.add(
Sphere(
material=gold_metal,
center=vec3(-0.75, 0.1, -3.0),
@ -56,7 +47,7 @@ def setup_scene(
max_ray_depth=3,
)
)
scene.add(
Sc.add(
Sphere(
material=bluish_metal,
center=vec3(1.25, 0.1, -3.0),
@ -65,7 +56,7 @@ def setup_scene(
)
)
scene.add(
Sc.add(
Plane(
material=floor,
center=vec3(0, -0.5, -3.0),
@ -78,6 +69,6 @@ def setup_scene(
)
# see sightpy/backgrounds
scene.add_Background(environment)
Sc.add_Background(environment)
return scene
return Sc

22
Programming/TRAK/utils.py Executable file → Normal file
View File

@ -1,25 +1,17 @@
#!/usr/bin/env python3
"""Configuration and CLI-argument helpers shared by the renderer entry point."""
from configparser import ConfigParser
def load_config(config_path: str) -> ConfigParser:
"""Read `config_path` and return the parsed configuration.
A missing file is not an error: ``ConfigParser.read`` ignores it and the
caller falls back to argparse defaults.
"""
def load_config(config_path):
config = ConfigParser()
config.read(config_path)
return config
def parse_resolution(resolution: str) -> tuple[int, int]:
"""Split a ``WIDTHxHEIGHT`` string into its two integer components."""
def parse_resolution(resolution):
try:
width, height = map(int, resolution.lower().split("x"))
except ValueError as err:
msg = "Resolution must be in the format WIDTHxHEIGHT, e.g., 1920x1080."
raise ValueError(msg) from err
return width, height
return width, height
except ValueError:
raise ValueError(
"Resolution must be in the format WIDTHxHEIGHT, e.g., 1920x1080."
)

View File

@ -5,15 +5,8 @@ Coursework for TWM (Techniki Wizyjne / machine vision), lab 4.
| Path | What it is |
|---|---|
| `TWM_KerasIntro.ipynb` | The submitted notebook — the deliverable. |
| `TWM_KerasIntro.py` | An `nbconvert` export of the notebook's **CIFAR-10 section only**. |
| `twm.py` | Prints the TensorFlow version the notebook will run against. |
| `TWM_KerasIntro.py` | An `nbconvert` export of that notebook. Derived, not edited by hand. |
| `twm.py` | Helper code used by the notebook. |
The notebook is the source of truth. The `.py` is kept because it makes that
section's code reviewable and diffable, but it is not a full export: it covers
28 of the notebook's 81 code cells, all of them from the CIFAR-10 half, and it
has been edited since. Treat the two as separate artifacts rather than
regenerating one from the other.
Both need a GPU. The notebook's first cell calls `sys.exit()` when TensorFlow
reports no physical GPU device, and running it end to end downloads MNIST,
CIFAR-10 and a slice of the Quick, Draw! bitmaps into `data/`.
The `.py` export is kept because it is what makes the notebook's code
reviewable and diffable; edit the notebook, then re-export.

View File

@ -89,16 +89,10 @@
"source": [
"import itertools\n",
"import random # for generating random numbers\n",
"import sys\n",
"import urllib.request\n",
"from dataclasses import dataclass\n",
"from pathlib import Path\n",
"\n",
"import matplotlib.pyplot as plt # MATLAB like plotting routines\n",
"import numpy as np # advanced math library\n",
"import seaborn as sns\n",
"import tensorflow as tf\n",
"from keras import Model\n",
"from keras.datasets import mnist # MNIST dataset is included in Keras%\n",
"from keras.layers import (\n",
" Activation,\n",
@ -107,14 +101,9 @@
") # Types of layers to be used in our model\n",
"from keras.models import Sequential # Model type to be used\n",
"from keras.utils import to_categorical # NumPy related tools\n",
"from matplotlib import patheffects\n",
"from sklearn.manifold import TSNE\n",
"from sklearn.metrics import confusion_matrix\n",
"from sklearn.preprocessing import OneHotEncoder\n",
"\n",
"# print() would need a logging handler configured to survive this file being\n",
"# exported and run as a script; sys.stdout.write shows the same text in a cell.\n",
"sys.stdout.write(f\"{tf.__version__}\\n\")"
"print(tf.__version__)"
]
},
{
@ -140,14 +129,13 @@
},
"outputs": [],
"source": [
"# The MNIST data is split between 60,000 28 x 28 pixel training images\n",
"# and 10,000 28 x 28 pixel images\n",
"# The MNIST data is split between 60,000 28 x 28 pixel training images and 10,000 28 x 28 pixel images\n",
"(X_train, y_train), (X_test, y_test) = mnist.load_data()\n",
"\n",
"sys.stdout.write(f\"X_train shape {X_train.shape}\\n\")\n",
"sys.stdout.write(f\"y_train shape {y_train.shape}\\n\")\n",
"sys.stdout.write(f\"X_test shape {X_test.shape}\\n\")\n",
"sys.stdout.write(f\"y_test shape {y_test.shape}\\n\")"
"print(\"X_train shape\", X_train.shape)\n",
"print(\"y_train shape\", y_train.shape)\n",
"print(\"X_test shape\", X_test.shape)\n",
"print(\"y_test shape\", y_test.shape)"
]
},
{
@ -174,28 +162,20 @@
"source": [
"plt.rcParams[\"figure.figsize\"] = (9, 9) # Make the figures a bit bigger\n",
"\n",
"CLASS_COUNT = 10\n",
"\n",
"\n",
"def visualize_classes(images: np.ndarray, labels: np.ndarray) -> None:\n",
" \"\"\"Show ten samples of each class as one wide strip.\n",
"\n",
" The strips are collected in a list and concatenated once. Growing the\n",
" result in place only bound it in the loop's `else` branch, which reads as\n",
" a use-before-assignment and is what ruff flagged.\n",
" \"\"\"\n",
" strips = []\n",
" for class_id in range(CLASS_COUNT):\n",
" img_batch = images[labels == class_id][0:10]\n",
" strips.append(\n",
" np.reshape(\n",
" img_batch,\n",
" (img_batch.shape[0] * img_batch.shape[1], img_batch.shape[2]),\n",
" )\n",
"def visualize_classes(X, y):\n",
" for i in range(10):\n",
" img_batch = X[y == i][0:10]\n",
" img_batch = np.reshape(\n",
" img_batch, (img_batch.shape[0] * img_batch.shape[1], img_batch.shape[2])\n",
" )\n",
" if i > 0:\n",
" img = np.concatenate([img, img_batch], axis=1)\n",
" else:\n",
" img = img_batch\n",
" plt.figure(figsize=(10, 20))\n",
" plt.axis(\"off\")\n",
" plt.imshow(np.concatenate(strips, axis=1), cmap=\"gray\")\n",
" plt.imshow(img, cmap=\"gray\")\n",
"\n",
"\n",
"visualize_classes(X_train, y_train)"
@ -223,14 +203,12 @@
"outputs": [],
"source": [
"# just a little function for pretty printing a matrix\n",
"def matprint(mat: np.ndarray, fmt: str = \"g\") -> None:\n",
" \"\"\"Print `mat` with every column padded to its own widest entry.\"\"\"\n",
"def matprint(mat, fmt=\"g\"):\n",
" col_maxes = [max([len((\"{:\" + fmt + \"}\").format(x)) for x in col]) for col in mat.T]\n",
" for row in mat:\n",
" for i, value in enumerate(row):\n",
" # Two trailing spaces and no newline: this builds one line per row.\n",
" sys.stdout.write((\"{:\" + str(col_maxes[i]) + fmt + \"} \").format(value))\n",
" sys.stdout.write(\"\\n\")\n",
" for x in mat:\n",
" for i, y in enumerate(x):\n",
" print((\"{:\" + str(col_maxes[i]) + fmt + \"}\").format(y), end=\" \")\n",
" print()\n",
"\n",
"\n",
"# now print!\n",
@ -279,42 +257,44 @@
},
"outputs": [],
"source": [
"import matplotlib.patheffects as PathEffects\n",
"import seaborn as sns\n",
"from sklearn.manifold import TSNE\n",
"\n",
"RS = 19238\n",
"\n",
"class_names = [str(clid) for clid in range(CLASS_COUNT)]\n",
"class_names = [str(clid) for clid in range(10)]\n",
"\n",
"\n",
"def scatter(points: np.ndarray, colors: np.ndarray) -> None:\n",
" \"\"\"Scatter 2D `points` coloured by class, with each class labelled once.\"\"\"\n",
"def scatter(x, colors):\n",
" # We choose a color palette with seaborn.\n",
" palette = np.array(sns.color_palette(\"hls\", CLASS_COUNT))\n",
" palette = np.array(sns.color_palette(\"hls\", 10))\n",
"\n",
" # We create a scatter plot.\n",
" plt.figure(figsize=(8, 8))\n",
" f = plt.figure(figsize=(8, 8))\n",
" ax = plt.subplot(aspect=\"equal\")\n",
" ax.scatter(points[:, 0], points[:, 1], lw=0, s=40, c=palette[colors.astype(\"int\")])\n",
" sc = ax.scatter(x[:, 0], x[:, 1], lw=0, s=40, c=palette[colors.astype(\"int\")])\n",
" plt.xlim(-25, 25)\n",
" plt.ylim(-25, 25)\n",
" ax.axis(\"off\")\n",
" ax.axis(\"tight\")\n",
"\n",
" # We add the labels for each digit.\n",
" for i in range(CLASS_COUNT):\n",
" txts = []\n",
" for i in range(10):\n",
" # Position of each label.\n",
" xtext, ytext = np.median(points[colors == i, :], axis=0)\n",
" xtext, ytext = np.median(x[colors == i, :], axis=0)\n",
" txt = ax.text(xtext, ytext, class_names[i], fontsize=15)\n",
" txt.set_path_effects(\n",
" [patheffects.Stroke(linewidth=5, foreground=\"w\"), patheffects.Normal()]\n",
" [PathEffects.Stroke(linewidth=5, foreground=\"w\"), PathEffects.Normal()]\n",
" )\n",
" txts.append(txt)\n",
"\n",
"\n",
"def plot_tsne(features: np.ndarray, labels: np.ndarray) -> None:\n",
" \"\"\"Project `features` to two dimensions with t-SNE and scatter them.\"\"\"\n",
" sys.stdout.write(\"calculating tsne ...\\n\")\n",
" proj = TSNE(random_state=RS, learning_rate=200, init=\"random\").fit_transform(\n",
" features\n",
" )\n",
" scatter(proj, labels)"
"def plot_tsne(X, y):\n",
" print(\"calculating tsne ...\")\n",
" proj = TSNE(random_state=RS, learning_rate=200, init=\"random\").fit_transform(X)\n",
" scatter(proj, y)"
]
},
{
@ -384,8 +364,8 @@
")\n",
"X_test /= 255\n",
"\n",
"sys.stdout.write(f\"Training matrix shape {X_train.shape}\\n\")\n",
"sys.stdout.write(f\"Testing matrix shape {X_test.shape}\\n\")"
"print(\"Training matrix shape\", X_train.shape)\n",
"print(\"Testing matrix shape\", X_test.shape)"
]
},
{
@ -467,8 +447,7 @@
"outputs": [],
"source": [
"# The first hidden layer is a set of 512 nodes (artificial neurons).\n",
"# Each node will receive an element from each input vector and apply some\n",
"# weight and bias to it.\n",
"# Each node will receive an element from each input vector and apply some weight and bias to it.\n",
"\n",
"model.add(\n",
" Dense(512, input_shape=(784,))\n",
@ -483,11 +462,10 @@
},
"outputs": [],
"source": [
"# An \"activation\" is a non-linear function applied to the output of the layer\n",
"# above. It checks the new value of the node, and decides whether that\n",
"# artifical neuron has fired.\n",
"# The Rectified Linear Unit (ReLU) converts all negative inputs to nodes in the\n",
"# next layer to be zero. Those inputs are then not considered to be fired.\n",
"# An \"activation\" is a non-linear function applied to the output of the layer above.\n",
"# It checks the new value of the node, and decides whether that artifical neuron has fired.\n",
"# The Rectified Linear Unit (ReLU) converts all negative inputs to nodes in the next layer to be zero.\n",
"# Those inputs are then not considered to be fired.\n",
"# Positive values of a node are unchanged.\n",
"\n",
"model.add(Activation(\"relu\"))"
@ -534,9 +512,8 @@
"outputs": [],
"source": [
"# The second hidden layer appears identical to our first layer.\n",
"# However, instead of each of the 512-node receiving 784-inputs from the input\n",
"# image data, they receive 512 inputs from the output of the first 512-node\n",
"# layer.\n",
"# However, instead of each of the 512-node receiving 784-inputs from the input image data,\n",
"# they receive 512 inputs from the output of the first 512-node layer.\n",
"\n",
"model.add(Dense(512))\n",
"model.add(Activation(\"relu\"))\n",
@ -560,10 +537,9 @@
},
"outputs": [],
"source": [
"# The final layer of 10 neurons in fully-connected to the previous 512-node\n",
"# layer. The final layer of a FCN should be equal to the number of desired\n",
"# classes (10 in this case).\n",
"model.add(Dense(CLASS_COUNT))"
"# The final layer of 10 neurons in fully-connected to the previous 512-node layer.\n",
"# The final layer of a FCN should be equal to the number of desired classes (10 in this case).\n",
"model.add(Dense(10))"
]
},
{
@ -574,8 +550,8 @@
},
"outputs": [],
"source": [
"# The \"softmax\" activation represents a probability distribution over K\n",
"# different possible outcomes. Its values are all non-negative and sum to 1.\n",
"# The \"softmax\" activation represents a probability distribution over K different possible outcomes.\n",
"# Its values are all non-negative and sum to 1.\n",
"\n",
"model.add(Activation(\"softmax\"))"
]
@ -734,8 +710,8 @@
"outputs": [],
"source": [
"score = model.evaluate(X_test, Y_test)\n",
"sys.stdout.write(f\"Test score: {score[0]}\\n\")\n",
"sys.stdout.write(f\"Test accuracy: {score[1]}\\n\")"
"print(\"Test score:\", score[0])\n",
"print(\"Test accuracy:\", score[1])"
]
},
{
@ -747,24 +723,18 @@
"outputs": [],
"source": [
"def plot_confusion_matrix(\n",
" cm: np.ndarray,\n",
" classes: list[str],\n",
" *,\n",
" normalize: bool = False,\n",
" title: str = \"Confusion matrix\",\n",
" cmap: object = plt.cm.Blues,\n",
") -> None:\n",
" \"\"\"Print and plot the confusion matrix.\n",
"\n",
" cm, classes, normalize=False, title=\"Confusion matrix\", cmap=plt.cm.Blues\n",
"):\n",
" \"\"\"This function prints and plots the confusion matrix.\n",
" Normalization can be applied by setting `normalize=True`.\n",
" \"\"\"\n",
" if normalize:\n",
" cm = cm.astype(\"float\") / cm.sum(axis=1)[:, np.newaxis]\n",
" sys.stdout.write(\"Normalized confusion matrix\\n\")\n",
" print(\"Normalized confusion matrix\")\n",
" else:\n",
" sys.stdout.write(\"Confusion matrix, without normalization\\n\")\n",
" print(\"Confusion matrix, without normalization\")\n",
"\n",
" sys.stdout.write(f\"{cm}\\n\")\n",
" print(cm)\n",
"\n",
" plt.imshow(cm, interpolation=\"nearest\", cmap=cmap)\n",
" plt.title(title)\n",
@ -786,17 +756,7 @@
"\n",
" plt.ylabel(\"True label\")\n",
" plt.xlabel(\"Predicted label\")\n",
" plt.tight_layout()\n",
"\n",
"\n",
"@dataclass(frozen=True)\n",
"class Samples:\n",
" \"\"\"A model's output, with the images and true labels it was scored on.\"\"\"\n",
"\n",
" scores: np.ndarray\n",
" images: np.ndarray\n",
" labels: np.ndarray\n",
" names: list[str] | None = None"
" plt.tight_layout()"
]
},
{
@ -875,34 +835,29 @@
},
"outputs": [],
"source": [
"def show_samples(indices: np.ndarray, samples: Samples, *, count: int = 3) -> None:\n",
" \"\"\"Plot a `count` x `count` grid of digits, titled predicted vs expected.\"\"\"\n",
"def show_samples(indices, preds, images, labels, count=3, names=[]):\n",
" plt.figure()\n",
" for i, sample in enumerate(indices[: count**2]):\n",
" pred_id = int(np.argmax(samples.scores[sample]))\n",
" real_id = int(samples.labels[sample])\n",
" pred_score = samples.scores[sample][pred_id]\n",
" real_score = samples.scores[sample][real_id]\n",
" pred_id = int(np.argmax(preds[sample]))\n",
" real_id = int(labels[sample])\n",
" pred_score = preds[sample][pred_id]\n",
" real_score = preds[sample][real_id]\n",
" plt.subplot(count, count, i + 1)\n",
" plt.imshow(\n",
" samples.images[sample].reshape(28, 28), cmap=\"gray\", interpolation=\"none\"\n",
" )\n",
" plt.imshow(images[sample].reshape(28, 28), cmap=\"gray\", interpolation=\"none\")\n",
" plt.axis(\"off\")\n",
" if samples.names:\n",
" predicted_label: str | int = samples.names[pred_id]\n",
" real_label: str | int = samples.names[real_id]\n",
" if len(names) > 0:\n",
" plt.title(\n",
" f\"P: {names[pred_id]} ({pred_score:.2f})\\nE: {names[real_id]} ({real_score:.2f})\"\n",
" )\n",
" else:\n",
" predicted_label = pred_id\n",
" real_label = real_id\n",
" plt.title(\n",
" f\"P: {predicted_label} ({pred_score:.2f})\\n\"\n",
" f\"E: {real_label} ({real_score:.2f})\"\n",
" )\n",
" plt.title(\n",
" f\"P: {pred_id} ({pred_score:.2f})\\nE: {real_id} ({real_score:.2f})\"\n",
" )\n",
"\n",
" plt.tight_layout()\n",
"\n",
"\n",
"show_samples(correct_indices, Samples(predict, X_test, y_test), count=5)"
"show_samples(correct_indices, predict, X_test, y_test, 5)"
]
},
{
@ -927,7 +882,7 @@
},
"outputs": [],
"source": [
"show_samples(incorrect_indices, Samples(predict, X_test, y_test), count=5)"
"show_samples(incorrect_indices, predict, X_test, y_test, 5)"
]
},
{
@ -1084,8 +1039,7 @@
"outputs": [],
"source": [
"# Again, do some formatting\n",
"# Except we do not flatten each image into a 784-length vector because we want\n",
"# to perform convolutions first\n",
"# Except we do not flatten each image into a 784-length vector because we want to perform convolutions first\n",
"\n",
"X_train = X_train.reshape(\n",
" 60000, 28, 28, 1\n",
@ -1100,8 +1054,8 @@
")\n",
"X_test /= 255\n",
"\n",
"sys.stdout.write(f\"Training matrix shape {X_train.shape}\\n\")\n",
"sys.stdout.write(f\"Testing matrix shape {X_test.shape}\\n\")"
"print(\"Training matrix shape\", X_train.shape)\n",
"print(\"Testing matrix shape\", X_test.shape)"
]
},
{
@ -1213,9 +1167,8 @@
"outputs": [],
"source": [
"# We can then feed our augmented data in batches\n",
"# Besides loss function considerations as before, this method actually results\n",
"# in significant memory savings because we are actually LOADING the data into\n",
"# the network in batches before processing each batch\n",
"# Besides loss function considerations as before, this method actually results in significant memory savings\n",
"# because we are actually LOADING the data into the network in batches before processing each batch\n",
"\n",
"# Before the data was all loaded into memory, but then processed in batches.\n",
"\n",
@ -1264,8 +1217,8 @@
"outputs": [],
"source": [
"score = model.evaluate(X_test, Y_test)\n",
"sys.stdout.write(f\"Test score: {score[0]}\\n\")\n",
"sys.stdout.write(f\"Test accuracy: {score[1]}\\n\")"
"print(\"Test score:\", score[0])\n",
"print(\"Test accuracy:\", score[1])"
]
},
{
@ -1318,7 +1271,7 @@
},
"outputs": [],
"source": [
"show_samples(correct_indices, Samples(predict, X_test, y_test), count=5)"
"show_samples(correct_indices, predict, X_test, y_test, 5)"
]
},
{
@ -1334,7 +1287,7 @@
},
"outputs": [],
"source": [
"show_samples(incorrect_indices, Samples(predict, X_test, y_test), count=5)"
"show_samples(incorrect_indices, predict, X_test, y_test, 5)"
]
},
{
@ -1356,16 +1309,15 @@
},
"outputs": [],
"source": [
"def visualize2(\n",
" model: Sequential, layer: object, img: np.ndarray, r: int, c: int\n",
") -> None:\n",
" \"\"\"Plot the `r` x `c` feature maps `layer` produces for a single image.\"\"\"\n",
"def visualize2(model, layer, img, r, c):\n",
" from keras import Model\n",
"\n",
" # expand dimensions so that it represents a single 'sample'\n",
" img = np.expand_dims(img, axis=0)\n",
" outputs = [layer.output]\n",
" feature_model = Model(inputs=model.inputs, outputs=outputs)\n",
" model = Model(inputs=model.inputs, outputs=outputs)\n",
" # get feature map for first hidden layer\n",
" feature_maps = feature_model.predict(img)\n",
" feature_maps = model.predict(img)\n",
" for fmap in feature_maps:\n",
" # plot all 64 maps in an 8x8 squares\n",
" ix = 1\n",
@ -1457,34 +1409,31 @@
"outputs": [],
"source": [
"# Loading the specified subset of digits from the MNIST dataset\n",
"def get_mnist(\n",
" digits: list[int],\n",
") -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n",
" \"\"\"Reload MNIST keeping only `digits`, scaled to [0, 1] with a channel axis.\"\"\"\n",
"def get_mnist(digits):\n",
" # Reload the MNIST data\n",
" (x_train, y_train), (x_test, y_test) = mnist.load_data()\n",
" (X_train, y_train), (X_test, y_test) = mnist.load_data()\n",
"\n",
" train_ids = np.isin(y_train, digits).ravel()\n",
" test_ids = np.isin(y_test, digits).ravel()\n",
" x_train = x_train[train_ids]\n",
" x_test = x_test[test_ids]\n",
" train_ids = np.in1d(y_train, digits)\n",
" test_ids = np.in1d(y_test, digits)\n",
" X_train = X_train[train_ids]\n",
" X_test = X_test[test_ids]\n",
" y_train = y_train[train_ids]\n",
" y_test = y_test[test_ids]\n",
"\n",
" x_train = np.expand_dims(x_train, axis=-1)\n",
" x_test = np.expand_dims(x_test, axis=-1)\n",
" X_train = np.expand_dims(X_train, axis=-1)\n",
" X_test = np.expand_dims(X_test, axis=-1)\n",
"\n",
" x_train = x_train.astype(\n",
" X_train = X_train.astype(\n",
" \"float32\"\n",
" ) # change integers to 32-bit floating point numbers\n",
" x_test = x_test.astype(\"float32\")\n",
" X_test = X_test.astype(\"float32\")\n",
"\n",
" x_train /= (\n",
" X_train /= (\n",
" 255 # normalize each value for each pixel for the entire vector for each input\n",
" )\n",
" x_test /= 255\n",
" X_test /= 255\n",
"\n",
" return x_train, y_train, x_test, y_test"
" return X_train, y_train, X_test, y_test"
]
},
{
@ -1496,8 +1445,7 @@
"outputs": [],
"source": [
"# Preparing the base model\n",
"def prepare_model(input_shape: tuple[int, ...], class_count: int) -> Sequential:\n",
" \"\"\"Build the three-convolution-block CNN this section reuses.\"\"\"\n",
"def prepare_model(input_shape, class_count):\n",
" model = Sequential() # Linear stacking of layers\n",
"\n",
" # Convolution Layer 1\n",
@ -1537,11 +1485,12 @@
"outputs": [],
"source": [
"# One-hot encoding of non-consecutive labels\n",
"def one_hot(labels: np.ndarray) -> np.ndarray:\n",
" \"\"\"One-hot encode `labels`, which need not be 0..n-1.\"\"\"\n",
"def one_hot(labels):\n",
" from sklearn.preprocessing import OneHotEncoder\n",
"\n",
" encoder = OneHotEncoder(categories=\"auto\")\n",
" column = labels.reshape(-1, 1)\n",
" output = encoder.fit_transform(column)\n",
" l = labels.reshape(-1, 1)\n",
" output = encoder.fit_transform(l)\n",
" return output.toarray()"
]
},
@ -1553,25 +1502,23 @@
},
"outputs": [],
"source": [
"def test_model(\n",
" model: Sequential,\n",
" x_test: np.ndarray,\n",
" y_test_onehot: np.ndarray,\n",
" y_test: np.ndarray,\n",
" digits: list[int],\n",
") -> None:\n",
" \"\"\"Score `model` on the test split and plot its confusion matrix.\"\"\"\n",
" score = model.evaluate(x_test, y_test_onehot)\n",
" sys.stdout.write(f\"Test score: {score[0]}\\n\")\n",
" sys.stdout.write(f\"Test accuracy: {score[1]}\\n\")\n",
"def test_model(model, X_test, Y_test, y_test, digits):\n",
" score = model.evaluate(X_test, Y_test)\n",
" print(\"Test score:\", score[0])\n",
" print(\"Test accuracy:\", score[1])\n",
"\n",
" # The predict_classes function outputs the highest probability class\n",
" # according to the trained classifier for each input example.\n",
" predicted = model.predict(x_test)\n",
" predicted = model.predict(X_test)\n",
" predicted_classes = np.argmax(predicted, axis=1)\n",
"\n",
" actual_classes = [digits[x] for x in predicted_classes]\n",
"\n",
" # Check which items we got right / wrong\n",
" correct_indices = np.nonzero(actual_classes == y_test)[0]\n",
"\n",
" incorrect_indices = np.nonzero(actual_classes != y_test)[0]\n",
"\n",
" cnf_matrix = confusion_matrix(y_test, actual_classes)\n",
"\n",
" class_names = [str(i) for i in digits]\n",
@ -1701,10 +1648,7 @@
"outputs": [],
"source": [
"# Extract specified range of layers to a new sequential model\n",
"def extract_layers(\n",
" main_model: Sequential, starting_layer_ix: int, ending_layer_ix: int\n",
") -> Sequential:\n",
" \"\"\"Return a new Sequential holding layers `starting_layer_ix`..`ending_layer_ix`.\"\"\"\n",
"def extract_layers(main_model, starting_layer_ix, ending_layer_ix):\n",
" # create an empty model\n",
" new_model = Sequential()\n",
" for ix in range(starting_layer_ix, ending_layer_ix + 1):\n",
@ -1948,50 +1892,46 @@
},
"outputs": [],
"source": [
"# The scheme is spelled out at each use site rather than folded into this\n",
"# constant, so that the URL handed to urlopen is visibly https and nothing\n",
"# else -- which is what S310 asks for.\n",
"QUICKDRAW_HOST = \"storage.googleapis.com/quickdraw_dataset/full/numpy_bitmap\"\n",
"import os\n",
"import urllib\n",
"\n",
"\n",
"def download_and_load(\n",
" class_names: list[str],\n",
" test_split: float = 0.2,\n",
" max_items_per_class: int = 10000,\n",
") -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n",
" \"\"\"Fetch the Quick, Draw! bitmaps for `class_names` and split them.\"\"\"\n",
" root = Path(\"data\")\n",
" root.mkdir(parents=True, exist_ok=True)\n",
"def download_and_load(class_names, test_split=0.2, max_items_per_class=10000):\n",
" root = \"data\"\n",
" if not os.path.exists(root):\n",
" os.makedirs(root)\n",
"\n",
" sys.stdout.write(\"downloading ...\\n\")\n",
" print(\"downloading ...\")\n",
" base = \"https://storage.googleapis.com/quickdraw_dataset/full/numpy_bitmap/\"\n",
" for c in class_names:\n",
" cc = c.replace(\"_\", \"%20\")\n",
" path = f\"https://{QUICKDRAW_HOST}/{cc}.npy\"\n",
" sys.stdout.write(f\"{path}\\n\")\n",
" destination = root / f\"{cc}.npy\"\n",
" if not destination.exists():\n",
" with urllib.request.urlopen(path) as response:\n",
" destination.write_bytes(response.read())\n",
" path = base + cc + \".npy\"\n",
" print(path)\n",
" if not os.path.exists(f\"{root}/{cc}.npy\"):\n",
" urllib.request.urlretrieve(path, f\"{root}/{cc}.npy\")\n",
" else:\n",
" sys.stdout.write(\"Already downloaded\\n\")\n",
" sys.stdout.write(\"loading ...\\n\")\n",
" print(\"Already downloaded\")\n",
" print(\"loading ...\")\n",
"\n",
" # initialize variables\n",
" x = np.empty([0, 784])\n",
" y = np.empty([0])\n",
"\n",
" # load each data file\n",
" for idx, name in enumerate(class_names):\n",
" quoted = name.replace(\"_\", \"%20\")\n",
" data = np.load(root / f\"{quoted}.npy\")\n",
" for idx, file in enumerate(class_names):\n",
" file = file.replace(\"_\", \"%20\")\n",
" data = np.load(f\"{root}/{file}.npy\")\n",
" data = data[0:max_items_per_class, :]\n",
" labels = np.full(data.shape[0], idx)\n",
"\n",
" x = np.concatenate((x, data), axis=0)\n",
" y = np.append(y, labels)\n",
"\n",
" data = None\n",
" labels = None\n",
"\n",
" # randomize the dataset\n",
" permutation = np.random.default_rng().permutation(y.shape[0])\n",
" permutation = np.random.permutation(y.shape[0])\n",
" x = x[permutation, :]\n",
" y = y[permutation]\n",
"\n",
@ -2007,8 +1947,8 @@
" x_train = x[test_size : x.shape[0], :]\n",
" y_train = y[test_size : y.shape[0]]\n",
"\n",
" sys.stdout.write(f\"Training Data : {x_train.shape[0]}\\n\")\n",
" sys.stdout.write(f\"Testing Data : {x_test.shape[0]}\\n\")\n",
" print(\"Training Data : \", x_train.shape[0])\n",
" print(\"Testing Data : \", x_test.shape[0])\n",
" return x_train, y_train, x_test, y_test"
]
},
@ -2037,7 +1977,9 @@
},
"outputs": [],
"source": [
"all_class_names = Path(\"categories.txt\").read_text().splitlines()\n",
"with open(\"categories.txt\") as f:\n",
" all_class_names = f.readlines()\n",
"\n",
"\n",
"random.seed(RANDOM_SEED)\n",
"\n",
@ -2048,11 +1990,10 @@
"# select random 10 classes\n",
"class_names = random.sample(all_class_names, nb_classes)\n",
"\n",
"# The lab also suggests a deliberately hard fixed set instead of a random one:\n",
"# wheel, pizza, smiley_face, apple, potato, basketball, soccer_ball, brain,\n",
"# clock and circle.\n",
"# you can also try those \"hard\" classes instead\n",
"# class_names = ['wheel', 'pizza', 'smiley_face', 'apple', 'potato', 'basketball', 'soccer_ball', 'brain', 'clock', 'circle']\n",
"\n",
"sys.stdout.write(f\"{class_names}\\n\")\n",
"print(class_names)\n",
"\n",
"X_train, y_train, X_test, y_test = download_and_load(class_names)\n",
"\n",
@ -2184,8 +2125,8 @@
"outputs": [],
"source": [
"score = model.evaluate(X_test, Y_test)\n",
"sys.stdout.write(f\"Test score: {score[0]}\\n\")\n",
"sys.stdout.write(f\"Test accuracy: {score[1]}\\n\")"
"print(\"Test score:\", score[0])\n",
"print(\"Test accuracy:\", score[1])"
]
},
{
@ -2225,7 +2166,7 @@
},
"outputs": [],
"source": [
"show_samples(correct_indices, Samples(predicted, X_test, y_test, class_names), count=5)"
"show_samples(correct_indices, predicted, X_test, y_test, 5, class_names)"
]
},
{
@ -2236,9 +2177,7 @@
},
"outputs": [],
"source": [
"show_samples(\n",
" incorrect_indices, Samples(predicted, X_test, y_test, class_names), count=5\n",
")"
"show_samples(incorrect_indices, predicted, X_test, y_test, 5, class_names)"
]
},
{
@ -2286,8 +2225,8 @@
"y_train = y_train.reshape((1, -1))[0]\n",
"y_test = y_test.reshape((1, -1))[0]\n",
"\n",
"sys.stdout.write(f\"Training matrix shape {X_train.shape} {y_train.shape}\\n\")\n",
"sys.stdout.write(f\"Testing matrix shape {X_test.shape} {y_test.shape}\\n\")\n",
"print(\"Training matrix shape\", X_train.shape, y_train.shape)\n",
"print(\"Testing matrix shape\", X_test.shape, y_test.shape)\n",
"\n",
"# one-hot format classes\n",
"\n",
@ -2332,22 +2271,23 @@
},
"outputs": [],
"source": [
"strips = []\n",
"for class_id in range(CLASS_COUNT):\n",
" img_batch = X_train[y_train == class_id][0:10]\n",
" strips.append(\n",
" np.reshape(\n",
" img_batch,\n",
" (\n",
" img_batch.shape[0] * img_batch.shape[1],\n",
" img_batch.shape[2],\n",
" img_batch.shape[3],\n",
" ),\n",
" )\n",
"for i in range(10):\n",
" img_batch = X_train[y_train == i][0:10]\n",
" img_batch = np.reshape(\n",
" img_batch,\n",
" (\n",
" img_batch.shape[0] * img_batch.shape[1],\n",
" img_batch.shape[2],\n",
" img_batch.shape[3],\n",
" ),\n",
" )\n",
" if i > 0:\n",
" img = np.concatenate([img, img_batch], axis=1)\n",
" else:\n",
" img = img_batch\n",
"plt.figure(figsize=(10, 20))\n",
"plt.axis(\"off\")\n",
"plt.imshow(np.concatenate(strips, axis=1), cmap=\"gray\")"
"plt.imshow(img, cmap=\"gray\")"
]
},
{
@ -2370,8 +2310,7 @@
},
"outputs": [],
"source": [
"def generate_model() -> Sequential:\n",
" \"\"\"Build the minimal variant: one conv layer straight into the classifier.\"\"\"\n",
"def generate_model():\n",
" model = Sequential() # Linear stacking of layers\n",
"\n",
" # Convolution Layer 1\n",
@ -2396,8 +2335,7 @@
" return model\n",
"\n",
"\n",
"def generate_model_default() -> Sequential:\n",
" \"\"\"Build the same architecture again, kept as the baseline to compare against.\"\"\"\n",
"def generate_model_default():\n",
" model = Sequential() # Linear stacking of layers\n",
"\n",
" # Convolution Layer 1\n",
@ -2422,8 +2360,7 @@
" return model\n",
"\n",
"\n",
"def generate_model_gemini() -> Sequential:\n",
" \"\"\"Build the variant Gemini proposed: two conv blocks and heavy dropout.\"\"\"\n",
"def generate_model_gemini():\n",
" model = Sequential()\n",
"\n",
" # Convolutional Layers with Max Pooling\n",
@ -2449,8 +2386,7 @@
" return model\n",
"\n",
"\n",
"def generate_model_chat() -> Sequential:\n",
" \"\"\"Build the variant ChatGPT proposed: four conv layers with batch norm.\"\"\"\n",
"def generate_model_chat():\n",
" model = Sequential() # Linear stacking of layers\n",
"\n",
" # Convolution Layer 1\n",
@ -2594,14 +2530,14 @@
},
"outputs": [],
"source": [
"for trained in models:\n",
" score = trained.evaluate(X_test, Y_test)\n",
" sys.stdout.write(f\"Test score: {score[0]}\\n\")\n",
" sys.stdout.write(f\"Test accuracy: {score[1]}\\n\")\n",
"for model in models:\n",
" score = model.evaluate(X_test, Y_test)\n",
" print(\"Test score:\", score[0])\n",
" print(\"Test accuracy:\", score[1])\n",
"\n",
" # The predict_classes function outputs the highest probability class\n",
" # according to the trained classifier for each input example.\n",
" predicted = trained.predict(X_test)\n",
" predicted = model.predict(X_test)\n",
" predicted_classes = np.argmax(predicted, axis=1)\n",
"\n",
" # Check which items we got right / wrong\n",
@ -2611,7 +2547,7 @@
"\n",
" cnf_matrix = confusion_matrix(y_test, predicted_classes)\n",
"\n",
" class_names = [str(i) for i in range(CLASS_COUNT)]\n",
" class_names = [str(i) for i in range(10)]\n",
"\n",
" # Plot non-normalized confusion matrix\n",
" plt.figure()\n",
@ -2633,27 +2569,24 @@
},
"outputs": [],
"source": [
"def show_samples_rgb(indices: np.ndarray, samples: Samples, *, count: int = 3) -> None:\n",
" \"\"\"Plot a `count` x `count` grid of RGB samples, predicted vs expected.\"\"\"\n",
"def show_samples_rgb(indices, preds, images, labels, count=3, names=[]):\n",
" plt.figure()\n",
" for i, sample in enumerate(indices[: count**2]):\n",
" pred_id = int(np.argmax(samples.scores[sample]))\n",
" real_id = int(samples.labels[sample])\n",
" pred_score = samples.scores[sample][pred_id]\n",
" real_score = samples.scores[sample][real_id]\n",
" pred_id = int(np.argmax(preds[sample]))\n",
" real_id = int(labels[sample])\n",
" pred_score = preds[sample][pred_id]\n",
" real_score = preds[sample][real_id]\n",
" plt.subplot(count, count, i + 1)\n",
" plt.imshow(samples.images[sample], interpolation=\"none\")\n",
" plt.imshow(images[sample], interpolation=\"none\")\n",
" plt.axis(\"off\")\n",
" if samples.names:\n",
" predicted_label: str | int = samples.names[pred_id]\n",
" real_label: str | int = samples.names[real_id]\n",
" if len(names) > 0:\n",
" plt.title(\n",
" f\"P: {names[pred_id]} ({pred_score:.2f})\\nE: {names[real_id]} ({real_score:.2f})\"\n",
" )\n",
" else:\n",
" predicted_label = pred_id\n",
" real_label = real_id\n",
" plt.title(\n",
" f\"P: {predicted_label} ({pred_score:.2f})\\n\"\n",
" f\"E: {real_label} ({real_score:.2f})\"\n",
" )\n",
" plt.title(\n",
" f\"P: {pred_id} ({pred_score:.2f})\\nE: {real_id} ({real_score:.2f})\"\n",
" )\n",
"\n",
" plt.tight_layout()"
]
@ -2679,9 +2612,7 @@
},
"outputs": [],
"source": [
"show_samples_rgb(\n",
" correct_indices, Samples(predicted, X_test, y_test, cifar_names), count=5\n",
")"
"show_samples_rgb(correct_indices, predicted, X_test, y_test, 5, cifar_names)"
]
},
{
@ -2705,9 +2636,7 @@
},
"outputs": [],
"source": [
"show_samples_rgb(\n",
" incorrect_indices, Samples(predicted, X_test, y_test, cifar_names), count=5\n",
")"
"show_samples_rgb(incorrect_indices, predicted, X_test, y_test, 5, cifar_names)"
]
}
],

230
Programming/twm_4/TWM_KerasIntro.py Executable file → Normal file
View File

@ -1,24 +1,25 @@
#!/usr/bin/env python3
"""CIFAR-10 half of the lab notebook, exported so the code can be diffed.
# # CIFAR-10
Four CNN variants are built and only `model_chat` is trained, then evaluated
with a confusion matrix and sample grids of its right and wrong answers.
# ## Ładowanie zbioru danych
Needs a GPU: the script exits early without one, exactly as the notebook does.
`print` is `sys.stdout.write` here so the output is identical to the notebook's
without a logging handler having to be configured first.
"""
# In[ ]:
import sys
import tensorflow as tf
# Check if GPU is available
print(tf.config.list_physical_devices("GPU"))
if tf.config.list_physical_devices("GPU"):
print("GPU is available")
else:
print("GPU is not available")
sys.exit()
from __future__ import annotations
import itertools
import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from keras.datasets import cifar10
from keras.layers import (
Activation,
@ -35,59 +36,20 @@ from sklearn.metrics import confusion_matrix
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.image import ImageDataGenerator
if TYPE_CHECKING:
from collections.abc import Sequence
from matplotlib.colors import Colormap
# CIFAR-10 has ten classes, and the training split has 40000 images once the
# generator has held back its 20% for validation.
NUM_CLASSES = 10
BATCH_SIZE = 128
TRAIN_IMAGES = 40000
VALID_IMAGES = 10000
EPOCHS = 20
# ## Ładowanie zbioru danych
# Check if GPU is available
sys.stdout.write(f"{tf.config.list_physical_devices('GPU')}\n")
if tf.config.list_physical_devices("GPU"):
sys.stdout.write("GPU is available\n")
else:
sys.stdout.write("GPU is not available\n")
sys.exit()
@dataclass(frozen=True)
class Predictions:
"""A model's output, with the images and true labels it was produced from."""
scores: np.ndarray
images: np.ndarray
labels: np.ndarray
names: Sequence[str] | None = None
def plot_confusion_matrix(
cm: np.ndarray,
classes: Sequence[str],
*,
normalize: bool = False,
title: str = "Confusion matrix",
cmap: Colormap = plt.cm.Blues,
) -> None:
"""Print and plot the confusion matrix.
cm, classes, normalize=False, title="Confusion matrix", cmap=plt.cm.Blues
):
"""This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype("float") / cm.sum(axis=1)[:, np.newaxis]
sys.stdout.write("Normalized confusion matrix\n")
print("Normalized confusion matrix")
else:
sys.stdout.write("Confusion matrix, without normalization\n")
print("Confusion matrix, without normalization")
sys.stdout.write(f"{cm}\n")
print(cm)
plt.imshow(cm, interpolation="nearest", cmap=cmap)
plt.title(title)
@ -125,13 +87,15 @@ X_test /= 255
y_train = y_train.reshape((1, -1))[0]
y_test = y_test.reshape((1, -1))[0]
sys.stdout.write(f"Training matrix shape {X_train.shape} {y_train.shape}\n")
sys.stdout.write(f"Testing matrix shape {X_test.shape} {y_test.shape}\n")
print("Training matrix shape", X_train.shape, y_train.shape)
print("Testing matrix shape", X_test.shape, y_test.shape)
# one-hot format classes
Y_train = to_categorical(y_train, NUM_CLASSES)
Y_test = to_categorical(y_test, NUM_CLASSES)
nb_classes = 10
Y_train = to_categorical(y_train, nb_classes)
Y_test = to_categorical(y_test, nb_classes)
cifar_names = [
"airplane",
@ -149,23 +113,23 @@ cifar_names = [
# ## Podgląd zbioru treningowego
# Ten samples of each class, stacked into one wide strip. Built as a list and
# concatenated once: growing `img` in place only bound it in the loop's `else`
# branch, which reads as a use-before-assignment and is what ruff flagged.
strips = []
for class_id in range(NUM_CLASSES):
img_batch = X_train[y_train == class_id][0:10]
strips.append(
np.reshape(
img_batch,
(
img_batch.shape[0] * img_batch.shape[1],
img_batch.shape[2],
img_batch.shape[3],
),
)
# In[ ]:
for i in range(10):
img_batch = X_train[y_train == i][0:10]
img_batch = np.reshape(
img_batch,
(
img_batch.shape[0] * img_batch.shape[1],
img_batch.shape[2],
img_batch.shape[3],
),
)
img = np.concatenate(strips, axis=1)
if i > 0:
img = np.concatenate([img, img_batch], axis=1)
else:
img = img_batch
plt.figure(figsize=(10, 20))
plt.axis("off")
plt.imshow(img, cmap="gray")
@ -173,9 +137,10 @@ plt.imshow(img, cmap="gray")
# ## Przygotowanie modelu
# In[ ]:
def generate_model() -> Sequential:
"""Build the minimal variant: one conv layer straight into the classifier."""
def generate_model():
model = Sequential() # Linear stacking of layers
# Convolution Layer 1
@ -189,7 +154,7 @@ def generate_model() -> Sequential:
# ...
# Fully Connected Layer
model.add(Dense(NUM_CLASSES)) # final 10 FC nodes
model.add(Dense(10)) # final 10 FC nodes
model.add(Activation("softmax")) # softmax activation
model.summary()
@ -200,8 +165,7 @@ def generate_model() -> Sequential:
return model
def generate_model_default() -> Sequential:
"""Build the same architecture again, kept as the baseline to compare against."""
def generate_model_default():
model = Sequential() # Linear stacking of layers
# Convolution Layer 1
@ -215,7 +179,7 @@ def generate_model_default() -> Sequential:
# ...
# Fully Connected Layer
model.add(Dense(NUM_CLASSES)) # final 10 FC nodes
model.add(Dense(10)) # final 10 FC nodes
model.add(Activation("softmax")) # softmax activation
model.summary()
@ -226,8 +190,7 @@ def generate_model_default() -> Sequential:
return model
def generate_model_gemini() -> Sequential:
"""Build the variant Gemini proposed: two conv blocks and heavy dropout."""
def generate_model_gemini():
model = Sequential()
# Convolutional Layers with Max Pooling
@ -241,7 +204,7 @@ def generate_model_gemini() -> Sequential:
model.add(Flatten())
model.add(Dense(128, activation="relu"))
model.add(Dropout(0.5)) # Regularization
model.add(Dense(NUM_CLASSES, activation="softmax"))
model.add(Dense(10, activation="softmax"))
# Model Compilation
model.compile(
@ -253,11 +216,7 @@ def generate_model_gemini() -> Sequential:
return model
def generate_model_chat() -> Sequential:
"""Build the variant ChatGPT proposed: four conv layers with batch norm.
This is the only one that actually gets trained below.
"""
def generate_model_chat():
model = Sequential() # Linear stacking of layers
# Convolution Layer 1
@ -292,7 +251,7 @@ def generate_model_chat() -> Sequential:
model.add(Dropout(0.6))
# Output Layer
model.add(Dense(NUM_CLASSES)) # final 10 FC nodes
model.add(Dense(10)) # final 10 FC nodes
model.add(Activation("softmax")) # softmax activation
model.summary()
@ -304,6 +263,9 @@ def generate_model_chat() -> Sequential:
return model
# In[ ]:
model = generate_model()
model_default = generate_model_default()
model_gemini = generate_model_gemini()
@ -313,6 +275,9 @@ models = [model_chat]
# ## Trening
# In[ ]:
gen = ImageDataGenerator(
rotation_range=8,
width_shift_range=0.08,
@ -322,35 +287,38 @@ gen = ImageDataGenerator(
validation_split=0.2,
)
train_generator = gen.flow(X_train, Y_train, batch_size=BATCH_SIZE, subset="training")
valid_generator = gen.flow(X_train, Y_train, batch_size=BATCH_SIZE, subset="validation")
train_generator = gen.flow(X_train, Y_train, batch_size=128, subset="training")
valid_generator = gen.flow(X_train, Y_train, batch_size=128, subset="validation")
# In[ ]:
# Max 20 epoch
for trained in models:
trained.fit(
for model in models:
model.fit(
train_generator,
steps_per_epoch=TRAIN_IMAGES // BATCH_SIZE,
epochs=EPOCHS,
steps_per_epoch=40000 // 128,
epochs=20,
verbose=1,
validation_data=valid_generator,
validation_steps=VALID_IMAGES // BATCH_SIZE,
validation_steps=10000 // 128,
)
# ## Test
for evaluated in models:
score = evaluated.evaluate(X_test, Y_test)
sys.stdout.write(f"Test score: {score[0]}\n")
sys.stdout.write(f"Test accuracy: {score[1]}\n")
# In[ ]:
for model in models:
score = model.evaluate(X_test, Y_test)
print("Test score:", score[0])
print("Test accuracy:", score[1])
# The predict_classes function outputs the highest probability class
# according to the trained classifier for each input example.
predicted = evaluated.predict(X_test)
predicted = model.predict(X_test)
predicted_classes = np.argmax(predicted, axis=1)
results = Predictions(
scores=predicted, images=X_test, labels=y_test, names=cifar_names
)
# Check which items we got right / wrong
correct_indices = np.nonzero(predicted_classes == y_test)[0]
@ -359,7 +327,7 @@ for evaluated in models:
cnf_matrix = confusion_matrix(y_test, predicted_classes)
class_names = [str(i) for i in range(NUM_CLASSES)]
class_names = [str(i) for i in range(10)]
# Plot non-normalized confusion matrix
plt.figure()
@ -370,38 +338,42 @@ for evaluated in models:
plt.show()
def show_samples_rgb(
indices: np.ndarray, results: Predictions, *, count: int = 3
) -> None:
"""Plot a `count` x `count` grid of samples, titled predicted vs expected."""
# In[ ]:
def show_samples_rgb(indices, preds, images, labels, count=3, names=[]):
plt.figure()
for i, sample in enumerate(indices[: count**2]):
pred_id = int(np.argmax(results.scores[sample]))
real_id = int(results.labels[sample])
pred_score = results.scores[sample][pred_id]
real_score = results.scores[sample][real_id]
pred_id = int(np.argmax(preds[sample]))
real_id = int(labels[sample])
pred_score = preds[sample][pred_id]
real_score = preds[sample][real_id]
plt.subplot(count, count, i + 1)
plt.imshow(results.images[sample], interpolation="none")
plt.imshow(images[sample], interpolation="none")
plt.axis("off")
if results.names:
predicted_label: str | int = results.names[pred_id]
real_label: str | int = results.names[real_id]
if len(names) > 0:
plt.title(
f"P: {names[pred_id]} ({pred_score:.2f})\nE: {names[real_id]} ({real_score:.2f})"
)
else:
predicted_label = pred_id
real_label = real_id
plt.title(
f"P: {predicted_label} ({pred_score:.2f})\n"
f"E: {real_label} ({real_score:.2f})"
)
plt.title(
f"P: {pred_id} ({pred_score:.2f})\nE: {real_id} ({real_score:.2f})"
)
plt.tight_layout()
# ## Poprawne klasyfikacje
show_samples_rgb(correct_indices, results, count=5)
# In[ ]:
show_samples_rgb(correct_indices, predicted, X_test, y_test, 5, cifar_names)
# ## Błędne klasyfikacje
show_samples_rgb(incorrect_indices, results, count=5)
# In[ ]:
show_samples_rgb(incorrect_indices, predicted, X_test, y_test, 5, cifar_names)

7
Programming/twm_4/twm.py Executable file → Normal file
View File

@ -1,8 +1,3 @@
#!/usr/bin/env python3
"""Smoke check: report which TensorFlow the notebook will actually run against."""
import sys
import tensorflow as tf
sys.stdout.write(f"{tf.__version__}\n")
print(tf.__version__)

View File

@ -32,43 +32,31 @@ own docs and the rest of this fleet carry. A test asserts by raising.
|---|---|
| Baseline, before any of this | 9,281 |
| After the format + safe-fix pass and excluding `TRAK/sightpy` | 3,686 |
| **Now** | **423** |
| **Now** | **1,183** |
Courses at zero: `WDWR`, `SPD`, `MOM`, `ECRYPT`, `ECRYPT_PROJECT`, `ECOTE`,
`NLP`, `EARIN`, `PORR`, `TRAK`, `twm_4`. What is left, by course:
`NLP`, `EARIN`, `PORR`. What is left, by course:
| Course | ruff | Can it be verified by running? |
|---|---|---|
| `TRAK` | 531 | **Yes** -- `run` ray-traces cornell_box in 37s. `sightpy/` is vendored and excluded; this is kuhy's own code |
| `twm_4` | 228 | No: `jupyter` on PATH is a dead pipx shim. `pip install jupyter` in a venv would fix that |
| `ERSMS-project` | 156 | No: docker-compose course |
| `PSD` | 152 | No: `run.sh` predates the harness and installs packages with sudo |
| `PBAD` | 115 | No: same dead jupyter shim |
`course_run.sh`'s notebook branch is fixed: it executes to a temp
`--output-dir`, probes jupyter by running it rather than by `command -v`, and
`course_main` now fails if a run changed anything git can see under the course
root. `PBAD` is still blocked on jupyter itself -- the binary on PATH is a
pipx shim whose interpreter is gone, so `--probe` reports "needs jupyter".
**A notebook does not need to be executed to be linted.** ruff reads `.ipynb`
natively and rewrites `source` only, so the check that the deliverable is
intact is a hash of everything EXCEPT `source`:
```python
stripped = {k: v for k, v in nb.items() if k != "cells"}
stripped["cells"] = [{k: v for k, v in c.items() if k != "source"} for c in nb["cells"]]
```
That hash was identical across all four passes on `twm_4`. The notebook also
round-trips byte-for-byte through
`json.dumps(nb, indent=1, ensure_ascii=False) + "\n"`, which is what makes
editing cells programmatically safe -- check that before touching PBAD's three.
**Before running the notebook courses, fix `scripts/course_run.sh` first.**
Its notebook branch is `jupyter nbconvert --execute --inplace`, and all four
notebooks are tracked WITH their outputs -- that would overwrite a committed
deliverable. This exact bug has already been found twice (TRAK's
`outputs/output.png`, SPD's `results_*.png`); execute to a temp path instead.
## mypy has NOT been run against any of this
`pyproject.toml` sets `strict = true` and `CLAUDE.md` says the repo runs mypy.
mypy IS installed now (`~/.local/bin/mypy`) -- the earlier note here saying it
was not is out of date. **"Zero findings" in a commit message still means zero
RUFF findings unless it says otherwise**; only `TRAK` has been type-checked.
`pyproject.toml` sets `strict = true` and `CLAUDE.md` says the repo runs mypy,
but mypy is not installed on this machine (pip is externally managed; use a
venv) and no commit so far has type-checked. **"Zero findings" in the commit
messages means zero RUFF findings.** Measured after installing it:
| Course | mypy --strict errors |
|---|---|
@ -76,8 +64,7 @@ RUFF findings unless it says otherwise**; only `TRAK` has been type-checked.
| `ECOTE` | 14 |
| `NLP` | 29 |
| `EARIN/lab1` alone | 46 |
| `TRAK` | **0** -- cleared 2026-08-29 |
| `twm_4` | **0** -- cleared 2026-08-29 |
| `TRAK` | 1 |
| `PSD/zin1` | 5 |
Two structural notes for whoever runs it next:
@ -87,24 +74,15 @@ Two structural notes for whoever runs it next:
- Most errors are `Returning Any` from untyped third-party calls (openai,
pandas) and genuinely-wrong unions this pass introduced by hand, e.g.
`str | bool` returns in `gpt_chunks.reformat`. They are real.
- Point it at the course's own venv or every import is unresolvable:
`mypy --strict --python-executable Programming/<course>/.venv/bin/python <dir>`.
Without that, TRAK reported 4 phantom `matplotlib` import errors on top of
the real ones.
- `pyproject.toml` now carries a `[[tool.mypy.overrides]]` block with
`ignore_missing_imports` for `Imath`, `OpenEXR`, `OpenGL` and `matplotlib`.
Those four ship neither stubs nor `py.typed`; without it mypy cannot import
them at all and reports nothing else about the file. It is not a suppression
of our own code -- do not extend it to anything we wrote.
## Still open
### 1. The 250-line cap: 50 files
### 1. The 250-line cap: 51 files
| Type | Count | Note |
|---|---|---|
| `.txt` | 27 | Blocked -- see `TODO-file-length-250.md` |
| `.py` | 10 | Several GREW during the lint pass, because docstrings and annotations are lines: `NLP/gpt_chunks.py` 911 -> 973, `EARIN/lab2/main.py` 581 -> 647, `PORR/.../linear_algebra_utils.py` 422 -> 553. Split them AFTER the lint work, not during. TRAK is already clear: its three over-cap files were split in the same pass that linted them, each verified by a byte-identical render. `twm_4/TWM_KerasIntro.py` joined the list at 407 lines and should NOT be split: it is an nbconvert export, and a partial one |
| `.py` | 11 | Several GREW during the lint pass, because docstrings and annotations are lines: `NLP/gpt_chunks.py` 911 -> 973, `EARIN/lab2/main.py` 581 -> 647, `PORR/.../linear_algebra_utils.py` 422 -> 553. Split them AFTER the lint work, not during |
| `.cpp` | 9 | |
| `.c` | 4 | |
| `.java` | 2 | |
@ -142,15 +120,6 @@ And run mypy per directory afterwards: it found 12 latent TypeErrors in EARIN
that ruff could not see -- call sites still passing positionally to arguments
the pass had made keyword-only.
Prefer a check the program itself settles. TRAK's `ray_tracing0` path has no
RNG at all, so `main.py --algorithm ray_tracing0 --output ../build/x.png`
renders byte-identically every time: refactoring 109 findings out of
`rendering.py` and splitting it in two was verified by one md5 comparison. The
cornell_box path is stochastic and cannot be used that way -- its ray count
drifts by ~20 between runs on its own. Where an RNG is unavoidable, do the
restructure and the `NPY002` swap as SEPARATE steps: the first must be
bit-identical under an external seed, only the second may move the pixels.
### 6. Disk
`Programming/PORR/code/` holds 3.8 GB of generated .npz caches (poli3 alone is

View File

@ -73,22 +73,6 @@ exclude = [
"^Programming/TRAK/sightpy/",
]
# Third-party packages that ship neither stubs nor a py.typed marker. This is
# not a suppression of our own code: without it mypy cannot import them at all
# and reports nothing else about the file that uses them.
[[tool.mypy.overrides]]
module = [
"Imath.*",
"OpenEXR.*",
"OpenGL.*",
"matplotlib.*",
"keras.*",
"tensorflow.*",
"sklearn.*",
"seaborn.*",
]
ignore_missing_imports = true
[tool.coverage.run]
branch = true
omit = [

View File

@ -29,12 +29,6 @@ readonly COURSE_GATES
_have() { command -v "$1" > /dev/null 2>&1; }
# `command -v` is true for a dead pipx shim: the file is there and executable,
# and only running it shows that the interpreter it points at is gone. That is
# what `jupyter` is on this machine, and it turned a clean "blocked: needs
# jupyter" into a confusing exec failure. Probe by running, not by looking.
_works() { _have "$1" && "$1" --version > /dev/null 2>&1; }
# Report "blocked" with the reason, which is the whole point of the status
# table: "needs X" is useful, "failed" is not.
_blocked() {
@ -49,17 +43,6 @@ _no_code() {
_runnable() { printf '%s\n' "$1"; exit 0; }
# What the course tree looks like to git. Compared before and after a run,
# because executing coursework has twice silently overwritten a submitted
# deliverable -- TRAK's outputs/output.png and SPD's results_*.png -- and
# neither was noticed until a much later `git status`. Gitignored build output
# does not show up here, which is why every runner writes into build/.
# numstat is included so that re-writing an already-modified file still counts.
_tree_state() {
git -C "$COURSE_ROOT" status --porcelain -- "$COURSE_ROOT" 2>/dev/null || true
git -C "$COURSE_ROOT" diff --numstat -- "$COURSE_ROOT" 2>/dev/null || true
}
# First tool present wins; otherwise blocked naming all the candidates.
_require_any() {
local label="$1"; shift
@ -137,17 +120,7 @@ course_main() {
printf 'usage: %s [--probe]\n' "$(basename "$0")"
printf ' --probe report runnable/blocked/no-code without running\n'
;;
"")
local before after
before="$(_tree_state)"
_run
after="$(_tree_state)"
if [[ "$before" != "$after" ]]; then
printf 'FAILED: the run changed files under %s\n' "$COURSE_ROOT" >&2
diff <(printf '%s\n' "$before") <(printf '%s\n' "$after") >&2 || true
return 1
fi
;;
"") _run ;;
*) printf 'unknown option: %s\n' "$1" >&2; return 1 ;;
esac
}

View File

@ -52,7 +52,7 @@ _probe() {
_runnable "compiles each standalone .cpp"
;;
notebook)
_works jupyter || _blocked "needs jupyter"
_have jupyter || _blocked "needs jupyter"
# Being on PATH is not the same as working: this machine has a
# jupyter shim whose pipx venv interpreter is gone, so it fails
# with "bad interpreter". Probe by actually invoking it.

View File

@ -181,20 +181,11 @@ _run() {
printf 'binaries in %s/build\n' "$COURSE_ROOT"
;;
notebook)
_works jupyter || _blocked "needs jupyter"
# NOT --inplace: all four notebooks in this repo are tracked WITH
# their outputs, so executing in place rewrites a deliverable.
# --output-dir sends the executed copy to a temp dir instead.
# It does NOT redirect what the notebook's own code writes -- the
# kernel's cwd is still the notebook's directory -- so the
# before/after tree check in course_main is what actually catches
# a notebook that saves a figure beside itself.
local nb nbtmp
nbtmp="$(mktemp -d)"
_have jupyter || _blocked "needs jupyter"
local nb
while IFS= read -r nb; do
jupyter nbconvert --to notebook --execute --output-dir "$nbtmp" "$nb"
jupyter nbconvert --to notebook --execute --inplace "$nb"
done < <(find "$COURSE_ROOT" -name '*.ipynb' -not -path '*/.ipynb_checkpoints/*' | sort)
rm -rf "$nbtmp"
;;
matlab)
local tool