Compare commits

...

3 Commits

Author SHA1 Message Date
1fd1de2f82 twm_4: zero findings, with the notebook's outputs proved untouched
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (push) Waiting to run
runnability / runnability (push) Waiting to run
228 ruff findings to 0 across the notebook, its partial export and twm.py, and
mypy --strict is clean on both .py files.

A notebook is a deliverable that happens to contain code, so the check that
mattered was not "does it still run" -- it needs a GPU, MNIST, CIFAR-10 and a
slice of Quick, Draw! to run at all -- but "is anything except the code still
exactly as submitted". Hashing every key of the .ipynb EXCEPT cell `source`
gives 60242e116d12549d11c93f7f before the first edit and after the last one,
across four passes and a `ruff format`. The file also round-trips byte-for-byte
through json.dumps(indent=1, ensure_ascii=False), which is what made editing
cells programmatically safe rather than a reformat of all 141 of them; the
diff touches 38.

print() became sys.stdout.write() rather than logging. In a notebook the print
IS the output, and a logger with no handler configured would have silently
emptied every cell -- the exact regression scripts/check_refactor_safety.py
was written for. matprint's `print(x, end="  ")` and bare `print()` are
preserved as writes with and without a trailing newline.

Both `show_samples` and `show_samples_rgb` took (indices, preds, images,
labels, count, names), which is six arguments and a mutable default. They now
take a frozen `Samples` holding the last four, which also removed the same
four-value tuple from seven call sites. Reviewing that diff is how I caught
that I had transcribed `real_score = preds[sample][real_id]` as
`samples.labels[sample]` -- a bug I introduced and then fixed before commit.

Other real things, not just rule satisfaction: `np.in1d` is removed in NumPy 2
(NPY201) and is now `np.isin(...).ravel()`; `test_model` computed
correct_indices and incorrect_indices and used neither; two cells grew `img`
inside a loop so it was only bound by the `else` branch; and the Quick, Draw!
downloader now builds a URL whose https scheme is a literal, which is what
S310 was asking for.

The README claimed the .py was "an nbconvert export of that notebook". It is
an export of the CIFAR-10 section only -- 28 of 81 code cells -- and has been
edited since. It says that now, and says the two are separate artifacts rather
than one being regenerable from the other.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 08:10:31 +02:00
f780d023be A run may no longer change the tree it ran in
Executing coursework has silently overwritten a submitted deliverable twice in
this campaign -- TRAK's outputs/output.png and SPD's results_*.png -- and both
times it was found by a later `git status`, not by the run. `course_main` now
snapshots what git sees under the course root before and after `_run`, and
fails with a diff naming the files if anything moved. Gitignored build output
does not show up there, which is why every runner already writes into build/.

Seen failing before being trusted: a stub whose `_run` appends a newline to
TRAK's config.ini exits 1 and names the file; the same stub without the append
exits 0; and a real `./run.sh run Programming/TRAK` still exits 0 after
rendering, because it writes into build/.

The notebook branch was the specific landmine. `nbconvert --execute --inplace`
rewrites the notebook it just ran, and all four notebooks here are tracked with
their outputs. It now executes to a temp --output-dir. That alone is not
enough, though: nbconvert runs the kernel with its cwd set to the notebook's
own directory, so a cell calling plt.savefig('x.png') still writes beside the
notebook. The tree check above is what actually catches that, which is why it
lives in course_main and applies to every course kind rather than to notebooks.

`_have jupyter` was also the wrong probe. jupyter on this machine is a pipx
shim whose interpreter is gone: `command -v` finds it, and running it exits
127. Both the probe and the runner now use `_works`, which runs `--version`.
`./Programming/twm_4/run.sh --probe` reports "needs jupyter" and exit 78
instead of failing confusingly mid-run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 07:59:15 +02:00
24f800d15a TRAK: zero findings, and a byte-identical render proving it
494 ruff findings to 0, and mypy --strict is clean too -- the first course in
this campaign where that is true of both.

Two real bugs turned up on the way, neither of which ruff can see:

- `main.py` passed `args.environment_map` to `ray_trace`, and argparse only
  ever defined `--environment`. Every `--algorithm ray_tracing0` run died with
  AttributeError before rendering a pixel, so `rendering.py` -- the largest
  file in the course -- had no way to be exercised at all.
- `mouse_button` in the environment-map viewer assigned `mouse_last_x/y`
  without declaring them `global`, so the drag origin went to locals and was
  thrown away. Measured against HEAD: a 10x5 px drag turned the camera by
  11.0/20.5 degrees because it measured from (0, 0); it is 1.0/0.5 now, which
  is what the 0.1 degrees-per-pixel constant says it should be.

Fixing the first one is what made the rest safe. `ray_tracing0` has no RNG
anywhere in it, so it renders byte-identically every time, and the whole
refactor of `rendering.py` is verified by one md5 comparison:
02484bdb6b6c1ddeff317d7e5566580f, 248619 rays, before and after. The
cornell_box path cannot do that -- its ray count drifts by ~20 between
identical runs.

Three files were over the 250-line cap and are now split, geometry away from
the algorithm that uses it: rendering.py 462 -> 137 + raytracer.py,
photon_mapping.py 261 -> 160 + photon_geometry.py, and
code/photonmapping/python/main.py 257 -> 203 + geometry.py. No TRAK source
file is over the cap now.

The two photon mappers do use numpy's legacy global RNG, so NPY002 could not
be bit-identical. Each was done in two steps: restructure first, verified
identical under an external seed (digests 7220370f60206a62 and
21b4771504ab2351, and an identical 828 photon traces), then the swap to
`default_rng` on its own, checked against the before/after distributions.

Verified by running, not by reading:

- cornell_box through `./run.sh run Programming/TRAK`: 24.27s, 13294 rays
- all five scenes build after `from sightpy import *` became explicit imports
- the standalone photon mapper end to end: 81.4s, 38742 photon traces
- the EXR loader byte for byte: a0c3890350ce6101247c6948, 6291456 bytes
- the GLUT viewer under xvfb-run, which drew a real 1024x512 frame

`pyproject.toml` gains a mypy override for Imath, OpenEXR, OpenGL and
matplotlib. Those four ship neither stubs nor py.typed, and without it mypy
cannot import them at all and so reports nothing else about the file.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 07:54:51 +02:00
25 changed files with 1637 additions and 1255 deletions

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

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

View File

@ -0,0 +1,119 @@
#!/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 Normal file → Executable file
View File

@ -1,88 +1,32 @@
#!/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 import time
from typing import cast
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
from geometry import Photon, Plane, Sphere, Surface, Vector3
PHOTONS = 0 logger = logging.getLogger(__name__)
# Shadow rays start this far off the surface they were cast from.
_SHADOW_OFFSET = 1e-5
# Define basic vector operations # Fraction of its power a photon keeps across one diffuse bounce.
class Vector3: _BOUNCE_ABSORPTION = 0.8
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 # Scene setup
sphere = Sphere(Vector3(0, 0, -5), 1.0, np.array([1, 0, 0])) # Red sphere sphere = Sphere(Vector3(0, 0, -5), 1.0, np.array([1, 0, 0])) # Red sphere
@ -90,14 +34,14 @@ plane = Plane(
Vector3(0, -1, 0), Vector3(0, 1, 0), np.array([0.5, 0.5, 0.5]) Vector3(0, -1, 0), Vector3(0, 1, 0), np.array([0.5, 0.5, 0.5])
) # Gray plane ) # Gray plane
objects = [sphere, plane] objects: list[Surface] = [sphere, plane]
# Light source # Light source
light_position = Vector3(-5, 5, -5) light_position = Vector3(-5, 5, -5)
light_power = np.array([1, 1, 1]) * 1000 # Intense white light light_power = np.array([1, 1, 1]) * 1000 # Intense white light
# Photon map # Photon map
photon_map = [] photon_map: list[tuple[Vector3, np.ndarray]] = []
# Parameters # Parameters
num_photons = 10000 # Number of photons to emit num_photons = 10000 # Number of photons to emit
@ -105,75 +49,26 @@ max_depth = 5 # Maximum number of bounces
gather_radius = 0.5 # Radius for radiance estimation gather_radius = 0.5 # Radius for radiance estimation
def emit_photons(): def random_unit_vector() -> Vector3:
for _ in range(num_photons): """Draw a direction uniformly over the sphere."""
# Emit photons in random directions from the light source theta = _rng.uniform(0, 2 * np.pi)
direction = random_unit_vector() z = _rng.uniform(-1, 1)
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) r = np.sqrt(1 - z * z)
return Vector3(r * np.cos(theta), r * np.sin(theta), z) return Vector3(r * np.cos(theta), r * np.sin(theta), z)
def random_hemisphere_direction(normal): def random_hemisphere_direction(normal: Vector3) -> Vector3:
dir = random_unit_vector() """Draw a direction uniformly over the hemisphere around `normal`."""
if dir.dot(normal) < 0: direction = random_unit_vector()
dir = Vector3(-dir.x, -dir.y, -dir.z) if direction.dot(normal) < 0:
return dir direction = Vector3(-direction.x, -direction.y, -direction.z)
return direction
def render_image(width, height): def nearest_hit(
aspect_ratio = width / height ray_origin: Vector3, ray_direction: Vector3
fov = np.pi / 3 # 60 degrees field of view ) -> tuple[Surface, Vector3, Vector3] | None:
image = np.zeros((height, width, 3)) """Return the closest surface the ray meets, with its point and normal."""
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 closest_t = np.inf
hit_object = None hit_object = None
hit_info = None hit_info = None
@ -185,35 +80,59 @@ def trace_ray(ray_origin, ray_direction):
if t < closest_t: if t < closest_t:
closest_t = t closest_t = t
hit_object = obj hit_object = obj
hit_info = (hit_point, normal, obj.color) hit_info = (hit_point, normal)
if hit_object: if hit_object is None or hit_info is None:
hit_point, normal, color = hit_info return None
direct_light = compute_direct_light(hit_point, normal) return (hit_object, hit_info[0], hit_info[1])
indirect_light = estimate_radiance(hit_point, normal)
return color * (direct_light + indirect_light)
return np.array([0, 0, 0]) # Background color
def compute_direct_light(point, normal): 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."""
# Simple Lambertian reflection from light source # Simple Lambertian reflection from light source
direction_to_light = (light_position - point).normalize() direction_to_light = (light_position - point).normalize()
# Shadow ray # Shadow ray
shadow_origin = point + normal * 1e-5 shadow_origin = point + normal * _SHADOW_OFFSET
shadow_ray = direction_to_light
in_shadow = False
for obj in objects: for obj in objects:
result = obj.intersect(shadow_origin, shadow_ray) if obj.intersect(shadow_origin, direction_to_light):
if result: return np.array([0, 0, 0])
in_shadow = True
break
if in_shadow:
return np.array([0, 0, 0])
intensity = max(0, normal.dot(direction_to_light)) intensity = max(0, normal.dot(direction_to_light))
return intensity * light_power / (4 * np.pi * (light_position - point).norm() ** 2) return intensity * light_power / (4 * np.pi * (light_position - point).norm() ** 2)
def estimate_radiance(point, normal): def estimate_radiance(point: Vector3, normal: Vector3) -> np.ndarray:
# Gather photons within the gather_radius """Gather the photons within `gather_radius` of `point` into a radiance."""
accumulated_power = np.array([0.0, 0.0, 0.0]) accumulated_power = np.array([0.0, 0.0, 0.0])
for photon_pos, photon_power in photon_map: for photon_pos, photon_power in photon_map:
distance = (photon_pos - point).norm() distance = (photon_pos - point).norm()
@ -224,27 +143,62 @@ def estimate_radiance(point, normal):
return accumulated_power / (area * num_photons) return accumulated_power / (area * num_photons)
# Main execution def trace_ray(ray_origin: Vector3, ray_direction: Vector3) -> np.ndarray:
if __name__ == "__main__": """Shade one camera ray with direct light plus gathered photons."""
print("Emitting photons...") hit = nearest_hit(ray_origin, ray_direction)
emit_photons() 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))
print("Rendering image...")
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...")
width = 100 width = 100
height = 100 height = 100
t0 = time.time() t0 = time.time()
image = render_image(width, height) image = render_image(width, height)
print( logger.info(
f"Render Took: {round(time.time() - t0, 2)}s\n" "Render Took: %ss\nresolution: %sx%s\nphotons (emitted): %s\n"
f"resolution: {width}x{height}\n" "photons (reflected): %s\nphotons (total): %s\nrays: %s",
f"photons (emitted): {num_photons}\n" round(time.time() - t0, 2),
f"photons (reflected): {PHOTONS - num_photons}\n" width,
f"photons (total): {PHOTONS}\n" height,
f"rays: {width * height}" num_photons,
photon_traces - num_photons,
photon_traces,
width * height,
) )
# Display the image # Display the image
plt.imshow(image) plt.imshow(image)
plt.axis("off") plt.axis("off")
plt.show() plt.show()
# Main execution
if __name__ == "__main__":
logging.basicConfig(format="%(message)s", level=logging.INFO)
main()

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

@ -1,2 +1,11 @@
#!/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 script_path = "" # path to script
exec(compile(open(script_path).read(), script_path, "exec")) runpy.run_path(script_path, run_name="__main__")

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

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

View File

@ -0,0 +1,114 @@
#!/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

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

@ -1,181 +1,150 @@
#!/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 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)
class Photon: @dataclass
def __init__(self, position, direction, power): class Scene:
self.position = position """Everything the two passes share: the geometry, the light, the photons."""
self.direction = direction
self.power = power 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 Sphere: def random_unit_vector(rng: np.random.Generator) -> Vector3:
def __init__(self, center, radius, color): """Draw a direction uniformly over the sphere."""
self.center = center theta = rng.uniform(0, 2 * np.pi)
self.radius = radius z = rng.uniform(-1, 1)
self.color = color r = np.sqrt(1 - z * z)
return Vector3(r * np.cos(theta), r * np.sin(theta), z)
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)
class Plane: def random_hemisphere_direction(rng: np.random.Generator, normal: Vector3) -> Vector3:
def __init__(self, point, normal, color): """Draw a direction uniformly over the hemisphere around `normal`."""
self.point = point direction = random_unit_vector(rng)
self.normal = normal.normalize() if direction.dot(normal) < 0:
self.color = color direction = Vector3(-direction.x, -direction.y, -direction.z)
return direction
def intersect(self, ray_origin, ray_direction):
denom = self.normal.dot(ray_direction) def nearest_hit(
if abs(denom) > 1e-6: objects: list[Surface], ray_origin: Vector3, ray_direction: Vector3
t = (self.point - ray_origin).dot(self.normal) / denom ) -> tuple[Surface, Vector3, Vector3] | None:
if t >= 0: """Return the closest surface the ray meets, with its point and normal."""
hit_point = ray_origin + ray_direction * t closest_t = np.inf
return (t, hit_point, self.normal) 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:
return None return None
return (hit_object, hit_info[0], hit_info[1])
def render_photon_mapping(width, height, num_photons, max_depth, gather_radius): def trace_photon(scene: Scene, photon: Photon, depth: int, max_depth: int) -> None:
# Photon mapping logic """Bounce one photon through the scene, recording every surface it lands on."""
photon_map = [] if depth > max_depth:
sphere = Sphere(Vector3(0, 0, -5), 1.0, np.array([1, 0, 0])) # Red sphere return
plane = Plane( hit = nearest_hit(scene.objects, photon.position, photon.direction)
Vector3(0, -1, 0), Vector3(0, 1, 0), np.array([0.5, 0.5, 0.5]) if hit is not None:
) # Gray plane _, hit_point, normal = hit
objects = [sphere, plane] 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)
light_position = Vector3(-5, 5, -5)
light_power = np.array([1, 1, 1]) * 1000
def emit_photons(): def emit_photons(scene: Scene, num_photons: int, max_depth: int) -> None:
for _ in range(num_photons): """Run the scatter pass: emit `num_photons` from the light and trace each."""
direction = random_unit_vector() for _ in range(num_photons):
power = light_power / num_photons direction = random_unit_vector(scene.rng)
photon = Photon(light_position, direction, power) power = scene.light_power / num_photons
trace_photon(photon, 0) photon = Photon(scene.light_position, direction, power)
trace_photon(scene, photon, 0, max_depth)
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 random_unit_vector(): def compute_direct_light(scene: Scene, point: Vector3, normal: Vector3) -> np.ndarray:
theta = np.random.uniform(0, 2 * np.pi) """Return the light arriving straight from the source, or black if shadowed."""
z = np.random.uniform(-1, 1) direction_to_light = (scene.light_position - point).normalize()
r = np.sqrt(1 - z * z) shadow_origin = point + normal * _SHADOW_OFFSET
return Vector3(r * np.cos(theta), r * np.sin(theta), z) for obj in scene.objects:
if obj.intersect(shadow_origin, direction_to_light):
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 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])
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]) return np.array([0, 0, 0])
intensity = max(0, normal.dot(direction_to_light)) intensity = max(0, normal.dot(direction_to_light))
return ( distance_squared = (scene.light_position - point).norm() ** 2
intensity * light_power / (4 * np.pi * (light_position - point).norm() ** 2) return intensity * scene.light_power / (4 * np.pi * distance_squared)
)
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() 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:
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 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)
aspect_ratio = width / height aspect_ratio = width / height
fov = np.pi / 3 fov = np.pi / 3
@ -184,9 +153,8 @@ def render_photon_mapping(width, height, num_photons, max_depth, gather_radius):
for x in range(width): for x in range(width):
px = (2 * (x + 0.5) / width - 1) * np.tan(fov / 2) * aspect_ratio px = (2 * (x + 0.5) / width - 1) * np.tan(fov / 2) * aspect_ratio
py = (1 - 2 * (y + 0.5) / height) * np.tan(fov / 2) py = (1 - 2 * (y + 0.5) / height) * np.tan(fov / 2)
ray_origin = Vector3(0, 0, 0)
ray_direction = Vector3(px, py, -1).normalize() ray_direction = Vector3(px, py, -1).normalize()
color = trace_ray(ray_origin, ray_direction) color = trace_ray(scene, Vector3(0, 0, 0), ray_direction)
image[y, x, :] = np.clip(color, 0, 1) image[y, x, :] = np.clip(color, 0, 1)
return image return image

233
Programming/TRAK/raytracer.py Executable file
View File

@ -0,0 +1,233 @@
#!/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 Normal file → Executable file
View File

@ -1,382 +1,52 @@
#!/usr/bin/env python3 #!/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 import time
from typing import TYPE_CHECKING
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np 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 ray_trace( def build_scene(num_spheres: int) -> list[SceneObject]:
num_spheres, environment, image_width=400, image_height=300, output_file="fig.png" """Lay out a checkerboard plane and `num_spheres` spheres in a receding row."""
):
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_plane0 = 1.0 * np.ones(3)
color_plane1 = 0.0 * np.ones(3) color_plane1 = 0.0 * np.ones(3)
scene.append(add_plane([0.0, -0.5, 0.0], [0.0, 1.0, 0.0])) scene = [make_plane([0.0, -0.5, 0.0], [0.0, 1.0, 0.0], color_plane0, color_plane1)]
base_radius = 1 / np.sqrt(num_spheres) # Im więcej kul, tym mniejsze base_radius = 1 / np.sqrt(num_spheres) # Im więcej kul, tym mniejsze
base_distance = 4.5 / num_spheres base_distance = 4.5 / num_spheres
@ -390,67 +60,87 @@ def ray_trace(
color = np.array([i / num_spheres, (num_spheres - i) / num_spheres, 0.5]) color = np.array([i / num_spheres, (num_spheres - i) / num_spheres, 0.5])
# Dodanie kuli do sceny # Dodanie kuli do sceny
scene.append(add_sphere([x, y, z], base_radius, color)) scene.append(make_sphere([x, y, z], base_radius, color))
# Light position and color. return scene
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
DEPTH_MAX = 5 # Maximum number of light reflections. def ray_trace(
col = np.zeros(3) # Current color. 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.
camera_origin = np.array([0.0, 0.35, -1.0]) # Camera. camera_origin = np.array([0.0, 0.35, -1.0]) # Camera.
Q = np.array([0.0, 0.0, 0.0]) # Camera pointing to. camera_target = np.array([0.0, 0.0, 0.0]) # Camera pointing to.
img = np.zeros((IMAGE_HEIGHT, IMAGE_WIDTH, 3)) img = np.zeros((image_height, image_width, 3))
r = float(IMAGE_WIDTH) / IMAGE_HEIGHT aspect = float(image_width) / image_height
# Screen coordinates: x0, y0, x1, y1. # Screen coordinates: x0, y0, x1, y1.
S = (-1.0, -1.0 / r + 0.25, 1.0, 1.0 / r + 0.25) screen = (-1.0, -1.0 / aspect + 0.25, 1.0, 1.0 / aspect + 0.25)
renderTime = time.time() render_time = time.time()
reflections = 0 reflections = 0
rays = 0 rays = 0
initialRays = 0 primary_rays = 0
# Loop through all pixels. # Loop through all pixels.
for i, x in enumerate(np.linspace(S[0], S[2], IMAGE_WIDTH)): for i, x in enumerate(np.linspace(screen[0], screen[2], image_width)):
if i % 10 == 0: if i % _PROGRESS_EVERY == 0:
print(round(i / float(IMAGE_WIDTH) * 100, 2), "%") logger.info("%s %%", round(i / float(image_width) * 100, 2))
for j, y in enumerate(np.linspace(S[1], S[3], IMAGE_HEIGHT)): for j, y in enumerate(np.linspace(screen[1], screen[3], image_height)):
col[:] = 0 color[:] = 0
Q[:2] = (x, y) camera_target[:2] = (x, y)
D = normalize(Q - camera_origin) ray_origin = camera_origin
DEPTH = 0 ray_direction = normalize(camera_target - camera_origin)
rayO, rayD = camera_origin, D depth = 0
REFLECTION = 1.0 reflection = 1.0
initialRays += 1 primary_rays += 1
# Loop through initial and secondary rays. # Loop through initial and secondary rays.
while DEPTH < DEPTH_MAX: while depth < DEPTH_MAX:
traced = trace_ray(rayO, rayD) traced = trace_ray(scene, lighting, ray_origin, ray_direction)
rays += 1 rays += 1
if not traced: if not traced:
break break
reflections += 1 reflections += 1
obj, M, N, col_ray = traced obj, hit_point, hit_normal, color_ray = traced
# Reflection: create a new ray. # Reflection: create a new ray.
rayO, rayD = M + N * 0.0001, normalize(rayD - 2 * np.dot(rayD, N) * N) ray_origin = hit_point + hit_normal * SURFACE_OFFSET
DEPTH += 1 ray_direction = normalize(
col += REFLECTION * col_ray ray_direction - 2 * np.dot(ray_direction, hit_normal) * hit_normal
REFLECTION *= obj.get("reflection", 1.0) )
img[IMAGE_HEIGHT - j - 1, i, :] = np.clip(col, 0, 1) depth += 1
renderTime = time.time() - renderTime 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
plt.imsave(output_file, img) plt.imsave(output_file, img)
print( logger.info(
f"Image saved as {output_file}\n" "Image saved as %s\nresolution: %sx%s\nrender time: %s s\nreflections: %s\n"
f"resolution: {IMAGE_WIDTH}x{IMAGE_HEIGHT}\n" "rays (initial): %s\nrays (secondary): %s\nrays (total): %s",
f"render time: {round(renderTime, 2)} s\n" output_file,
f"reflections: {reflections}\n" image_width,
f"rays (initial): {initialRays}\n" image_height,
f"rays (secondary): {rays - initialRays}\n" round(render_time, 2),
f"rays (total): {rays}" reflections,
primary_rays,
rays - primary_rays,
rays,
) )

View File

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

View File

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

View File

@ -1,14 +1,22 @@
from sightpy import * """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
# define materials to use def setup_scene(
def setup_scene(width=400, height=300, environment="lake.png"): width: int = 400, height: int = 300, environment: str = "lake.png"
# Set Scene ) -> Scene:
"""Build the soap-bubble scene at `width` x `height` over `environment`."""
Sc = Scene(ambient_color=rgb(0.01, 0.01, 0.01)) scene = Scene(ambient_color=rgb(0.01, 0.01, 0.01))
angle = -np.pi * 0.5 angle = -np.pi * 0.5
Sc.add_Camera( scene.add_Camera(
screen_height=height, screen_height=height,
screen_width=width, screen_width=width,
look_from=vec3(4.0 * np.sin(angle), 0.00, 4.0 * np.cos(angle)), look_from=vec3(4.0 * np.sin(angle), 0.00, 4.0 * np.cos(angle)),
@ -16,7 +24,7 @@ def setup_scene(width=400, height=300, environment="lake.png"):
) )
soap_bubble = ThinFilmInterference(thickness=330, noise=60.0) soap_bubble = ThinFilmInterference(thickness=330, noise=60.0)
Sc.add( scene.add(
Sphere( Sphere(
material=soap_bubble, material=soap_bubble,
center=vec3(1.0, 0.0, 1.5), center=vec3(1.0, 0.0, 1.5),
@ -26,6 +34,6 @@ def setup_scene(width=400, height=300, environment="lake.png"):
) )
) )
Sc.add_Background(environment, blur=10.0) scene.add_Background(environment, blur=10.0)
return Sc return scene

View File

@ -1,9 +1,17 @@
from sightpy import * """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
# define materials to use def setup_scene(
def setup_scene(width=400, height=300, environment="miramar.jpeg"): width: int = 400, height: int = 300, environment: str = "miramar.jpeg"
) -> Scene:
"""Build the three-sphere scene at `width` x `height` over `environment`."""
blue_glass = Refractive( blue_glass = Refractive(
n=vec3(1.5 + 4e-8j, 1.5 + 4e-8j, 1.5 + 0.0j) n=vec3(1.5 + 4e-8j, 1.5 + 4e-8j, 1.5 + 0.0j)
) # n = index of refraction ) # n = index of refraction
@ -20,19 +28,19 @@ def setup_scene(width=400, height=300, environment="miramar.jpeg"):
# Set Scene # Set Scene
Sc = Scene(ambient_color=rgb(0.05, 0.05, 0.05)) scene = Scene(ambient_color=rgb(0.05, 0.05, 0.05))
angle = np.pi / 2 * 0.3 angle = np.pi / 2 * 0.3
Sc.add_Camera( scene.add_Camera(
look_from=vec3(2.5 * np.sin(angle), 0.25, 2.5 * np.cos(angle) - 1.5), 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), look_at=vec3(0.0, 0.25, -1.5),
screen_width=width, screen_width=width,
screen_height=height, screen_height=height,
) )
Sc.add_DirectionalLight(Ldir=vec3(0.52, 0.45, -0.5), color=rgb(0.15, 0.15, 0.15)) scene.add_DirectionalLight(Ldir=vec3(0.52, 0.45, -0.5), color=rgb(0.15, 0.15, 0.15))
Sc.add( scene.add(
Sphere( Sphere(
material=blue_glass, material=blue_glass,
center=vec3(-1.2, 0.0, -1.5), center=vec3(-1.2, 0.0, -1.5),
@ -41,7 +49,7 @@ def setup_scene(width=400, height=300, environment="miramar.jpeg"):
max_ray_depth=3, max_ray_depth=3,
) )
) )
Sc.add( scene.add(
Sphere( Sphere(
material=green_glass, material=green_glass,
center=vec3(0.0, 0.0, -1.5), center=vec3(0.0, 0.0, -1.5),
@ -50,7 +58,7 @@ def setup_scene(width=400, height=300, environment="miramar.jpeg"):
max_ray_depth=3, max_ray_depth=3,
) )
) )
Sc.add( scene.add(
Sphere( Sphere(
material=red_glass, material=red_glass,
center=vec3(1.2, 0.0, -1.5), center=vec3(1.2, 0.0, -1.5),
@ -60,7 +68,7 @@ def setup_scene(width=400, height=300, environment="miramar.jpeg"):
) )
) )
Sc.add( scene.add(
Plane( Plane(
material=floor, material=floor,
center=vec3(0, -0.5, -3.0), center=vec3(0, -0.5, -3.0),
@ -73,6 +81,6 @@ def setup_scene(width=400, height=300, environment="miramar.jpeg"):
) )
# see sightpy/backgrounds # see sightpy/backgrounds
Sc.add_Background(environment) scene.add_Background(environment)
return Sc return scene

View File

@ -1,8 +1,16 @@
from sightpy import * """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
# define materials to use def setup_scene(
def setup_scene(width=400, height=300, environment="stormydays.png"): width: int = 400, height: int = 300, environment: str = "stormydays.png"
) -> Scene:
"""Build the glass-cuboid scene at `width` x `height` over `environment`."""
floor = Glossy( floor = Glossy(
diff_color=image("checkered_floor.png", repeat=2.0), diff_color=image("checkered_floor.png", repeat=2.0),
roughness=0.2, roughness=0.2,
@ -12,17 +20,17 @@ def setup_scene(width=400, height=300, environment="stormydays.png"):
) # n = index of refraction ) # n = index of refraction
green_glass = Refractive(n=vec3(1.5 + 4e-8j, 1.5 + 0.0j, 1.5 + 4e-8j)) green_glass = Refractive(n=vec3(1.5 + 4e-8j, 1.5 + 0.0j, 1.5 + 4e-8j))
Sc = Scene() scene = Scene()
Sc.add_Camera( scene.add_Camera(
look_from=vec3(0.0, 0.25, 1.0), look_from=vec3(0.0, 0.25, 1.0),
look_at=vec3(0.0, 0.25, -3.0), look_at=vec3(0.0, 0.25, -3.0),
screen_width=width, screen_width=width,
screen_height=height, screen_height=height,
) )
Sc.add_DirectionalLight(Ldir=vec3(0.0, 0.5, 0.5), color=rgb(0.5, 0.5, 0.5)) scene.add_DirectionalLight(Ldir=vec3(0.0, 0.5, 0.5), color=rgb(0.5, 0.5, 0.5))
Sc.add( scene.add(
Plane( Plane(
material=floor, material=floor,
center=vec3(0, -0.5, -3.0), center=vec3(0, -0.5, -3.0),
@ -44,9 +52,9 @@ def setup_scene(width=400, height=300, environment="stormydays.png"):
max_ray_depth=5, max_ray_depth=5,
) )
cb.rotate(θ=30, u=vec3(0, 1, 0)) cb.rotate(θ=30, u=vec3(0, 1, 0))
Sc.add(cb) scene.add(cb)
# see sightpy/backgrounds # see sightpy/backgrounds
Sc.add_Background(environment) scene.add_Background(environment)
return Sc return scene

View File

@ -1,8 +1,17 @@
from sightpy import * """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
# define materials to use def setup_scene(
def setup_scene(width=400, height=300, environment="stormydays.png"): width: int = 400, height: int = 300, environment: str = "stormydays.png"
) -> Scene:
"""Build the two-sphere scene at `width` x `height` over `environment`."""
gold_metal = Glossy( gold_metal = Glossy(
diff_color=rgb(1.0, 0.572, 0.184), diff_color=rgb(1.0, 0.572, 0.184),
n=vec3(0.15 + 3.58j, 0.4 + 2.37j, 1.54 + 1.91j), n=vec3(0.15 + 3.58j, 0.4 + 2.37j, 1.54 + 1.91j),
@ -27,19 +36,19 @@ def setup_scene(width=400, height=300, environment="stormydays.png"):
) )
# Set Scene # Set Scene
Sc = Scene(ambient_color=rgb(0.05, 0.05, 0.05)) scene = Scene(ambient_color=rgb(0.05, 0.05, 0.05))
angle = -np.pi / 2 * 0.3 angle = -np.pi / 2 * 0.3
Sc.add_Camera( scene.add_Camera(
look_from=vec3(2.5 * np.sin(angle), 0.25, 2.5 * np.cos(angle) - 1.5), 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), look_at=vec3(0.0, 0.25, -3.0),
screen_width=width, screen_width=width,
screen_height=height, screen_height=height,
) )
Sc.add_DirectionalLight(Ldir=vec3(0.52, 0.45, -0.5), color=rgb(0.15, 0.15, 0.15)) scene.add_DirectionalLight(Ldir=vec3(0.52, 0.45, -0.5), color=rgb(0.15, 0.15, 0.15))
Sc.add( scene.add(
Sphere( Sphere(
material=gold_metal, material=gold_metal,
center=vec3(-0.75, 0.1, -3.0), center=vec3(-0.75, 0.1, -3.0),
@ -47,7 +56,7 @@ def setup_scene(width=400, height=300, environment="stormydays.png"):
max_ray_depth=3, max_ray_depth=3,
) )
) )
Sc.add( scene.add(
Sphere( Sphere(
material=bluish_metal, material=bluish_metal,
center=vec3(1.25, 0.1, -3.0), center=vec3(1.25, 0.1, -3.0),
@ -56,7 +65,7 @@ def setup_scene(width=400, height=300, environment="stormydays.png"):
) )
) )
Sc.add( scene.add(
Plane( Plane(
material=floor, material=floor,
center=vec3(0, -0.5, -3.0), center=vec3(0, -0.5, -3.0),
@ -69,6 +78,6 @@ def setup_scene(width=400, height=300, environment="stormydays.png"):
) )
# see sightpy/backgrounds # see sightpy/backgrounds
Sc.add_Background(environment) scene.add_Background(environment)
return Sc return scene

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

@ -1,17 +1,25 @@
#!/usr/bin/env python3
"""Configuration and CLI-argument helpers shared by the renderer entry point."""
from configparser import ConfigParser from configparser import ConfigParser
def load_config(config_path): 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.
"""
config = ConfigParser() config = ConfigParser()
config.read(config_path) config.read(config_path)
return config return config
def parse_resolution(resolution): def parse_resolution(resolution: str) -> tuple[int, int]:
"""Split a ``WIDTHxHEIGHT`` string into its two integer components."""
try: try:
width, height = map(int, resolution.lower().split("x")) width, height = map(int, resolution.lower().split("x"))
return width, height except ValueError as err:
except ValueError: msg = "Resolution must be in the format WIDTHxHEIGHT, e.g., 1920x1080."
raise ValueError( raise ValueError(msg) from err
"Resolution must be in the format WIDTHxHEIGHT, e.g., 1920x1080." return width, height
)

View File

@ -5,8 +5,15 @@ Coursework for TWM (Techniki Wizyjne / machine vision), lab 4.
| Path | What it is | | Path | What it is |
|---|---| |---|---|
| `TWM_KerasIntro.ipynb` | The submitted notebook — the deliverable. | | `TWM_KerasIntro.ipynb` | The submitted notebook — the deliverable. |
| `TWM_KerasIntro.py` | An `nbconvert` export of that notebook. Derived, not edited by hand. | | `TWM_KerasIntro.py` | An `nbconvert` export of the notebook's **CIFAR-10 section only**. |
| `twm.py` | Helper code used by the notebook. | | `twm.py` | Prints the TensorFlow version the notebook will run against. |
The `.py` export is kept because it is what makes the notebook's code The notebook is the source of truth. The `.py` is kept because it makes that
reviewable and diffable; edit the notebook, then re-export. 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/`.

View File

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

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

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

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

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

View File

@ -32,31 +32,43 @@ own docs and the rest of this fleet carry. A test asserts by raising.
|---|---| |---|---|
| Baseline, before any of this | 9,281 | | Baseline, before any of this | 9,281 |
| After the format + safe-fix pass and excluding `TRAK/sightpy` | 3,686 | | After the format + safe-fix pass and excluding `TRAK/sightpy` | 3,686 |
| **Now** | **1,183** | | **Now** | **423** |
Courses at zero: `WDWR`, `SPD`, `MOM`, `ECRYPT`, `ECRYPT_PROJECT`, `ECOTE`, Courses at zero: `WDWR`, `SPD`, `MOM`, `ECRYPT`, `ECRYPT_PROJECT`, `ECOTE`,
`NLP`, `EARIN`, `PORR`. What is left, by course: `NLP`, `EARIN`, `PORR`, `TRAK`, `twm_4`. What is left, by course:
| Course | ruff | Can it be verified by running? | | 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 | | `ERSMS-project` | 156 | No: docker-compose course |
| `PSD` | 152 | No: `run.sh` predates the harness and installs packages with sudo | | `PSD` | 152 | No: `run.sh` predates the harness and installs packages with sudo |
| `PBAD` | 115 | No: same dead jupyter shim | | `PBAD` | 115 | No: same dead jupyter shim |
**Before running the notebook courses, fix `scripts/course_run.sh` first.** `course_run.sh`'s notebook branch is fixed: it executes to a temp
Its notebook branch is `jupyter nbconvert --execute --inplace`, and all four `--output-dir`, probes jupyter by running it rather than by `command -v`, and
notebooks are tracked WITH their outputs -- that would overwrite a committed `course_main` now fails if a run changed anything git can see under the course
deliverable. This exact bug has already been found twice (TRAK's root. `PBAD` is still blocked on jupyter itself -- the binary on PATH is a
`outputs/output.png`, SPD's `results_*.png`); execute to a temp path instead. 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.
## mypy has NOT been run against any of this ## mypy has NOT been run against any of this
`pyproject.toml` sets `strict = true` and `CLAUDE.md` says the repo runs mypy, `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 mypy IS installed now (`~/.local/bin/mypy`) -- the earlier note here saying it
venv) and no commit so far has type-checked. **"Zero findings" in the commit was not is out of date. **"Zero findings" in a commit message still means zero
messages means zero RUFF findings.** Measured after installing it: RUFF findings unless it says otherwise**; only `TRAK` has been type-checked.
| Course | mypy --strict errors | | Course | mypy --strict errors |
|---|---| |---|---|
@ -64,7 +76,8 @@ messages means zero RUFF findings.** Measured after installing it:
| `ECOTE` | 14 | | `ECOTE` | 14 |
| `NLP` | 29 | | `NLP` | 29 |
| `EARIN/lab1` alone | 46 | | `EARIN/lab1` alone | 46 |
| `TRAK` | 1 | | `TRAK` | **0** -- cleared 2026-08-29 |
| `twm_4` | **0** -- cleared 2026-08-29 |
| `PSD/zin1` | 5 | | `PSD/zin1` | 5 |
Two structural notes for whoever runs it next: Two structural notes for whoever runs it next:
@ -74,15 +87,24 @@ Two structural notes for whoever runs it next:
- Most errors are `Returning Any` from untyped third-party calls (openai, - Most errors are `Returning Any` from untyped third-party calls (openai,
pandas) and genuinely-wrong unions this pass introduced by hand, e.g. pandas) and genuinely-wrong unions this pass introduced by hand, e.g.
`str | bool` returns in `gpt_chunks.reformat`. They are real. `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 ## Still open
### 1. The 250-line cap: 51 files ### 1. The 250-line cap: 50 files
| Type | Count | Note | | Type | Count | Note |
|---|---|---| |---|---|---|
| `.txt` | 27 | Blocked -- see `TODO-file-length-250.md` | | `.txt` | 27 | Blocked -- see `TODO-file-length-250.md` |
| `.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 | | `.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 |
| `.cpp` | 9 | | | `.cpp` | 9 | |
| `.c` | 4 | | | `.c` | 4 | |
| `.java` | 2 | | | `.java` | 2 | |
@ -120,6 +142,15 @@ 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 that ruff could not see -- call sites still passing positionally to arguments
the pass had made keyword-only. 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 ### 6. Disk
`Programming/PORR/code/` holds 3.8 GB of generated .npz caches (poli3 alone is `Programming/PORR/code/` holds 3.8 GB of generated .npz caches (poli3 alone is

View File

@ -73,6 +73,22 @@ exclude = [
"^Programming/TRAK/sightpy/", "^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] [tool.coverage.run]
branch = true branch = true
omit = [ omit = [

View File

@ -29,6 +29,12 @@ readonly COURSE_GATES
_have() { command -v "$1" > /dev/null 2>&1; } _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 # Report "blocked" with the reason, which is the whole point of the status
# table: "needs X" is useful, "failed" is not. # table: "needs X" is useful, "failed" is not.
_blocked() { _blocked() {
@ -43,6 +49,17 @@ _no_code() {
_runnable() { printf '%s\n' "$1"; exit 0; } _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. # First tool present wins; otherwise blocked naming all the candidates.
_require_any() { _require_any() {
local label="$1"; shift local label="$1"; shift
@ -120,7 +137,17 @@ course_main() {
printf 'usage: %s [--probe]\n' "$(basename "$0")" printf 'usage: %s [--probe]\n' "$(basename "$0")"
printf ' --probe report runnable/blocked/no-code without running\n' printf ' --probe report runnable/blocked/no-code without running\n'
;; ;;
"") _run ;; "")
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
;;
*) printf 'unknown option: %s\n' "$1" >&2; return 1 ;; *) printf 'unknown option: %s\n' "$1" >&2; return 1 ;;
esac esac
} }

View File

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

View File

@ -181,11 +181,20 @@ _run() {
printf 'binaries in %s/build\n' "$COURSE_ROOT" printf 'binaries in %s/build\n' "$COURSE_ROOT"
;; ;;
notebook) notebook)
_have jupyter || _blocked "needs jupyter" _works jupyter || _blocked "needs jupyter"
local nb # 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)"
while IFS= read -r nb; do while IFS= read -r nb; do
jupyter nbconvert --to notebook --execute --inplace "$nb" jupyter nbconvert --to notebook --execute --output-dir "$nbtmp" "$nb"
done < <(find "$COURSE_ROOT" -name '*.ipynb' -not -path '*/.ipynb_checkpoints/*' | sort) done < <(find "$COURSE_ROOT" -name '*.ipynb' -not -path '*/.ipynb_checkpoints/*' | sort)
rm -rf "$nbtmp"
;; ;;
matlab) matlab)
local tool local tool