mirror of
https://github.com/kuhyx/WUT_Computer_Science.git
synced 2026-11-24 21:46:23 +01:00
Compare commits
No commits in common. "1fd1de2f82761d56b4fc579c9f4d6eb62aef3263" and "70937fbdc3335603b8638c7616d4e574dc05612c" have entirely different histories.
1fd1de2f82
...
70937fbdc3
218
Programming/TRAK/code/mapa_srodowiska/main.py
Executable file → Normal file
218
Programming/TRAK/code/mapa_srodowiska/main.py
Executable file → Normal file
@ -1,64 +1,42 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""View an OpenEXR environment map from the inside, on a GLUT-textured sphere.
|
|
||||||
|
|
||||||
Drag with the left mouse button to look around. The image is loaded as
|
|
||||||
32-bit float RGB and uploaded as a `GL_RGB32F` texture, so the high dynamic
|
|
||||||
range survives all the way to the driver.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
import os
|
import os
|
||||||
from dataclasses import dataclass
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import Imath
|
import Imath
|
||||||
import OpenEXR
|
import OpenEXR
|
||||||
from OpenGL import GL, GLU, GLUT
|
import OpenGL.GL as gl
|
||||||
|
import OpenGL.GLU as glu
|
||||||
|
import OpenGL.GLUT as glut
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
# Camera parameters
|
||||||
|
camera_angle_x = 0.0
|
||||||
# How far the camera turns per pixel of mouse drag.
|
camera_angle_y = 0.0
|
||||||
_DEGREES_PER_PIXEL = 0.1
|
camera_distance = 2.0
|
||||||
|
mouse_last_x = 0
|
||||||
|
mouse_last_y = 0
|
||||||
|
mouse_left_down = False
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
def load_hdr_environment_map(filepath):
|
||||||
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.
|
||||||
|
|
||||||
Returns the width, the height, and the pixels as interleaved float RGB,
|
Args:
|
||||||
flipped vertically so that row 0 is the bottom row OpenGL expects.
|
filepath (str): Path to the HDR file.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
tuple: A tuple containing the width, height, and a bytes object representing the HDR environment map in RGB format.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
if not Path(filepath).exists():
|
if not os.path.exists(filepath):
|
||||||
msg = f"File not found: {filepath}"
|
raise FileNotFoundError(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):
|
||||||
msg = f"File is not readable: {filepath}"
|
raise PermissionError(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:
|
||||||
msg = f"Unable to open '{filepath}' for read: {e!s}"
|
raise OSError(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()
|
||||||
@ -99,117 +77,117 @@ def load_hdr_environment_map(filepath: str) -> tuple[int, int, bytes]:
|
|||||||
return width, height, bytes(flipped_hdr_image)
|
return width, height, bytes(flipped_hdr_image)
|
||||||
|
|
||||||
|
|
||||||
def display_hdr_image(width: int, height: int, hdr_image: bytes) -> None:
|
def display_hdr_image(width, height, hdr_image):
|
||||||
"""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)
|
||||||
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
|
||||||
window_width = GLUT.glutGet(GLUT.GLUT_WINDOW_WIDTH)
|
gl.glViewport(
|
||||||
window_height = GLUT.glutGet(GLUT.GLUT_WINDOW_HEIGHT)
|
0,
|
||||||
GL.glViewport(0, 0, window_width, window_height)
|
0,
|
||||||
GL.glMatrixMode(GL.GL_PROJECTION)
|
glut.glutGet(glut.GLUT_WINDOW_WIDTH),
|
||||||
GL.glLoadIdentity()
|
glut.glutGet(glut.GLUT_WINDOW_HEIGHT),
|
||||||
GLU.gluPerspective(45.0, window_width / float(window_height), 0.1, 100.0)
|
)
|
||||||
GL.glMatrixMode(GL.GL_MODELVIEW)
|
gl.glMatrixMode(gl.GL_PROJECTION)
|
||||||
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, -STATE.distance)
|
gl.glTranslatef(0.0, 0.0, -camera_distance)
|
||||||
GL.glRotatef(STATE.angle_y, 1.0, 0.0, 0.0)
|
gl.glRotatef(camera_angle_y, 1.0, 0.0, 0.0)
|
||||||
GL.glRotatef(STATE.angle_x, 0.0, 1.0, 0.0)
|
gl.glRotatef(camera_angle_x, 0.0, 1.0, 0.0)
|
||||||
|
|
||||||
# Draw a textured sphere to simulate being inside the HDR environment
|
# 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: int, y: int) -> None:
|
def mouse_motion(x, y):
|
||||||
"""Turn the camera by however far the pointer moved since the last event."""
|
global mouse_last_x, mouse_last_y, camera_angle_x, camera_angle_y
|
||||||
if STATE.left_down:
|
if mouse_left_down:
|
||||||
dx = x - STATE.last_x
|
dx = x - mouse_last_x
|
||||||
dy = y - STATE.last_y
|
dy = y - mouse_last_y
|
||||||
STATE.angle_x += dx * _DEGREES_PER_PIXEL
|
camera_angle_x += dx * 0.1
|
||||||
STATE.angle_y += dy * _DEGREES_PER_PIXEL
|
camera_angle_y += dy * 0.1
|
||||||
STATE.last_x = x
|
mouse_last_x = x
|
||||||
STATE.last_y = y
|
mouse_last_y = y
|
||||||
GLUT.glutPostRedisplay()
|
glut.glutPostRedisplay()
|
||||||
|
|
||||||
|
|
||||||
def mouse_button(button: int, state: int, x: int, y: int) -> None:
|
def mouse_button(button, state, x, y):
|
||||||
"""Start a drag on left-button press and end it on release."""
|
global mouse_left_down
|
||||||
if button == GLUT.GLUT_LEFT_BUTTON:
|
if button == glut.GLUT_LEFT_BUTTON:
|
||||||
if state == GLUT.GLUT_DOWN:
|
if state == glut.GLUT_DOWN:
|
||||||
STATE.left_down = True
|
mouse_left_down = True
|
||||||
# These two were assigned without a `global` declaration before, so
|
mouse_last_x = x
|
||||||
# they went to locals and were thrown away: the first motion event
|
mouse_last_y = y
|
||||||
# of every drag measured from wherever the previous drag ended.
|
elif state == glut.GLUT_UP:
|
||||||
STATE.last_x = x
|
mouse_left_down = False
|
||||||
STATE.last_y = y
|
|
||||||
elif state == GLUT.GLUT_UP:
|
|
||||||
STATE.left_down = False
|
|
||||||
|
|
||||||
|
|
||||||
def main(filepath: str) -> None:
|
def main(filepath):
|
||||||
"""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)
|
||||||
except OSError:
|
print("HDR Map Loaded. Dimensions:", width, "x", height)
|
||||||
# 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
|
|
||||||
|
|
||||||
logger.info("HDR Map Loaded. Dimensions: %s x %s", width, height)
|
# Initialize GLUT and create window
|
||||||
|
glut.glutInit()
|
||||||
|
glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGB | glut.GLUT_DEPTH)
|
||||||
|
glut.glutInitWindowSize(800, 600) # Set initial window size
|
||||||
|
glut.glutCreateWindow(b"HDR Environment Map")
|
||||||
|
|
||||||
# Initialize GLUT and create window
|
# Set display callback
|
||||||
GLUT.glutInit()
|
glut.glutDisplayFunc(lambda: display_hdr_image(width, height, hdr_map))
|
||||||
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
|
# Set mouse callbacks
|
||||||
GLUT.glutDisplayFunc(lambda: display_hdr_image(width, height, hdr_map))
|
glut.glutMotionFunc(mouse_motion)
|
||||||
|
glut.glutMouseFunc(mouse_button)
|
||||||
|
|
||||||
# Set mouse callbacks
|
# Start the GLUT main loop
|
||||||
GLUT.glutMotionFunc(mouse_motion)
|
glut.glutMainLoop()
|
||||||
GLUT.glutMouseFunc(mouse_button)
|
except Exception as e:
|
||||||
|
print(e)
|
||||||
# Start the GLUT main loop
|
|
||||||
GLUT.glutMainLoop()
|
|
||||||
|
|
||||||
|
|
||||||
# Example usage
|
# Example usage
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
logging.basicConfig(format="%(message)s", level=logging.INFO)
|
filepath = "lilienstein_4k.exr"
|
||||||
main("lilienstein_4k.exr")
|
main(filepath)
|
||||||
|
|||||||
@ -1,119 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""Vectors, photons and the two surfaces the standalone photon mapper traces.
|
|
||||||
|
|
||||||
Split out of `main.py` so each file stays under this repo's 250-line cap; the
|
|
||||||
classes are unchanged.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
|
|
||||||
# A ray whose direction is this close to parallel with a plane never hits it.
|
|
||||||
_PARALLEL_EPSILON = 1e-6
|
|
||||||
|
|
||||||
# Define basic vector operations
|
|
||||||
class Vector3:
|
|
||||||
"""A 3D vector, with just the operations this renderer needs."""
|
|
||||||
|
|
||||||
def __init__(self, x: float, y: float, z: float) -> None:
|
|
||||||
"""Store the three components."""
|
|
||||||
self.x = x
|
|
||||||
self.y = y
|
|
||||||
self.z = z
|
|
||||||
|
|
||||||
def __add__(self, other: Vector3) -> Vector3:
|
|
||||||
"""Return the component-wise sum."""
|
|
||||||
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
|
|
||||||
|
|
||||||
def __sub__(self, other: Vector3) -> Vector3:
|
|
||||||
"""Return the component-wise difference."""
|
|
||||||
return Vector3(self.x - other.x, self.y - other.y, self.z - other.z)
|
|
||||||
|
|
||||||
def __mul__(self, scalar: float) -> Vector3:
|
|
||||||
"""Return this vector scaled by `scalar`."""
|
|
||||||
return Vector3(self.x * scalar, self.y * scalar, self.z * scalar)
|
|
||||||
|
|
||||||
def dot(self, other: Vector3) -> float:
|
|
||||||
"""Return the dot product with `other`."""
|
|
||||||
return self.x * other.x + self.y * other.y + self.z * other.z
|
|
||||||
|
|
||||||
def norm(self) -> float:
|
|
||||||
"""Return the length of this vector."""
|
|
||||||
return float(np.sqrt(self.dot(self)))
|
|
||||||
|
|
||||||
def normalize(self) -> Vector3:
|
|
||||||
"""Return a new vector of unit length pointing the same way."""
|
|
||||||
n = self.norm()
|
|
||||||
return Vector3(self.x / n, self.y / n, self.z / n)
|
|
||||||
|
|
||||||
|
|
||||||
# Define the photon
|
|
||||||
class Photon:
|
|
||||||
"""A packet of light energy travelling in a straight line."""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self, position: Vector3, direction: Vector3, power: np.ndarray
|
|
||||||
) -> None:
|
|
||||||
"""Store where the photon is, where it is going, and what it carries."""
|
|
||||||
self.position = position
|
|
||||||
self.direction = direction
|
|
||||||
self.power = power
|
|
||||||
|
|
||||||
|
|
||||||
# Define a simple sphere
|
|
||||||
class Sphere:
|
|
||||||
"""A sphere of uniform colour."""
|
|
||||||
|
|
||||||
def __init__(self, center: Vector3, radius: float, color: np.ndarray) -> None:
|
|
||||||
"""Store the sphere's geometry and colour."""
|
|
||||||
self.center = center
|
|
||||||
self.radius = radius
|
|
||||||
self.color = color
|
|
||||||
|
|
||||||
def intersect(
|
|
||||||
self, ray_origin: Vector3, ray_direction: Vector3
|
|
||||||
) -> tuple[float, Vector3, Vector3] | None:
|
|
||||||
"""Return the nearest hit as (distance, point, normal), or None."""
|
|
||||||
# Solve quadratic equation for intersection
|
|
||||||
oc = ray_origin - self.center
|
|
||||||
a = ray_direction.dot(ray_direction)
|
|
||||||
b = 2.0 * oc.dot(ray_direction)
|
|
||||||
c = oc.dot(oc) - self.radius * self.radius
|
|
||||||
discriminant = b * b - 4 * a * c
|
|
||||||
if discriminant < 0:
|
|
||||||
return None # No intersection
|
|
||||||
t = (-b - np.sqrt(discriminant)) / (2.0 * a)
|
|
||||||
if t < 0:
|
|
||||||
t = (-b + np.sqrt(discriminant)) / (2.0 * a)
|
|
||||||
if t < 0:
|
|
||||||
return None
|
|
||||||
hit_point = ray_origin + ray_direction * t
|
|
||||||
normal = (hit_point - self.center).normalize()
|
|
||||||
return (t, hit_point, normal)
|
|
||||||
|
|
||||||
|
|
||||||
# Define a simple plane
|
|
||||||
class Plane:
|
|
||||||
"""An infinite plane of uniform colour."""
|
|
||||||
|
|
||||||
def __init__(self, point: Vector3, normal: Vector3, color: np.ndarray) -> None:
|
|
||||||
"""Store a point on the plane, its (normalised) normal, and its colour."""
|
|
||||||
self.point = point
|
|
||||||
self.normal = normal.normalize()
|
|
||||||
self.color = color
|
|
||||||
|
|
||||||
def intersect(
|
|
||||||
self, ray_origin: Vector3, ray_direction: Vector3
|
|
||||||
) -> tuple[float, Vector3, Vector3] | None:
|
|
||||||
"""Return the nearest hit as (distance, point, normal), or None."""
|
|
||||||
denom = self.normal.dot(ray_direction)
|
|
||||||
if abs(denom) > _PARALLEL_EPSILON:
|
|
||||||
t = (self.point - ray_origin).dot(self.normal) / denom
|
|
||||||
if t >= 0:
|
|
||||||
hit_point = ray_origin + ray_direction * t
|
|
||||||
return (t, hit_point, self.normal)
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
Surface = Sphere | Plane
|
|
||||||
300
Programming/TRAK/code/photonmapping/python/main.py
Executable file → Normal file
300
Programming/TRAK/code/photonmapping/python/main.py
Executable file → Normal file
@ -1,32 +1,88 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""Standalone photon mapper: scatter photons from the light, then gather them.
|
|
||||||
|
|
||||||
The lab version, kept whole: the scene, the light and the photon map are
|
|
||||||
module-level state, and running the file emits photons, renders a 100x100
|
|
||||||
image and shows it. `Programming/TRAK/photon_mapping.py` is the later
|
|
||||||
parameterised rewrite of the same algorithm.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
import time
|
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
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
PHOTONS = 0
|
||||||
|
|
||||||
# Shadow rays start this far off the surface they were cast from.
|
|
||||||
_SHADOW_OFFSET = 1e-5
|
|
||||||
|
|
||||||
# Fraction of its power a photon keeps across one diffuse bounce.
|
# Define basic vector operations
|
||||||
_BOUNCE_ABSORPTION = 0.8
|
class Vector3:
|
||||||
|
def __init__(self, x, y, z):
|
||||||
|
self.x = x
|
||||||
|
self.y = y
|
||||||
|
self.z = z
|
||||||
|
|
||||||
|
def __add__(self, other):
|
||||||
|
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
|
||||||
|
|
||||||
|
def __sub__(self, other):
|
||||||
|
return Vector3(self.x - other.x, self.y - other.y, self.z - other.z)
|
||||||
|
|
||||||
|
def __mul__(self, scalar):
|
||||||
|
return Vector3(self.x * scalar, self.y * scalar, self.z * scalar)
|
||||||
|
|
||||||
|
def dot(self, other):
|
||||||
|
return self.x * other.x + self.y * other.y + self.z * other.z
|
||||||
|
|
||||||
|
def norm(self):
|
||||||
|
return np.sqrt(self.dot(self))
|
||||||
|
|
||||||
|
def normalize(self):
|
||||||
|
n = self.norm()
|
||||||
|
return Vector3(self.x / n, self.y / n, self.z / n)
|
||||||
|
|
||||||
|
|
||||||
|
# Define the photon
|
||||||
|
class Photon:
|
||||||
|
def __init__(self, position, direction, power):
|
||||||
|
self.position = position
|
||||||
|
self.direction = direction
|
||||||
|
self.power = power
|
||||||
|
|
||||||
|
|
||||||
|
# Define a simple sphere
|
||||||
|
class Sphere:
|
||||||
|
def __init__(self, center, radius, color):
|
||||||
|
self.center = center
|
||||||
|
self.radius = radius
|
||||||
|
self.color = color
|
||||||
|
|
||||||
|
def intersect(self, ray_origin, ray_direction):
|
||||||
|
# Solve quadratic equation for intersection
|
||||||
|
oc = ray_origin - self.center
|
||||||
|
a = ray_direction.dot(ray_direction)
|
||||||
|
b = 2.0 * oc.dot(ray_direction)
|
||||||
|
c = oc.dot(oc) - self.radius * self.radius
|
||||||
|
discriminant = b * b - 4 * a * c
|
||||||
|
if discriminant < 0:
|
||||||
|
return None # No intersection
|
||||||
|
t = (-b - np.sqrt(discriminant)) / (2.0 * a)
|
||||||
|
if t < 0:
|
||||||
|
t = (-b + np.sqrt(discriminant)) / (2.0 * a)
|
||||||
|
if t < 0:
|
||||||
|
return None
|
||||||
|
hit_point = ray_origin + ray_direction * t
|
||||||
|
normal = (hit_point - self.center).normalize()
|
||||||
|
return (t, hit_point, normal)
|
||||||
|
|
||||||
|
|
||||||
|
# Define a simple plane
|
||||||
|
class Plane:
|
||||||
|
def __init__(self, point, normal, color):
|
||||||
|
self.point = point
|
||||||
|
self.normal = normal.normalize()
|
||||||
|
self.color = color
|
||||||
|
|
||||||
|
def intersect(self, ray_origin, ray_direction):
|
||||||
|
denom = self.normal.dot(ray_direction)
|
||||||
|
if abs(denom) > 1e-6:
|
||||||
|
t = (self.point - ray_origin).dot(self.normal) / denom
|
||||||
|
if t >= 0:
|
||||||
|
hit_point = ray_origin + ray_direction * t
|
||||||
|
return (t, hit_point, self.normal)
|
||||||
|
return None
|
||||||
|
|
||||||
# One generator for the whole module, matching the module-level scene below.
|
|
||||||
_rng = np.random.default_rng()
|
|
||||||
|
|
||||||
# Scene setup
|
# 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
|
||||||
@ -34,14 +90,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: list[Surface] = [sphere, plane]
|
objects = [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: list[tuple[Vector3, np.ndarray]] = []
|
photon_map = []
|
||||||
|
|
||||||
# Parameters
|
# Parameters
|
||||||
num_photons = 10000 # Number of photons to emit
|
num_photons = 10000 # Number of photons to emit
|
||||||
@ -49,26 +105,75 @@ max_depth = 5 # Maximum number of bounces
|
|||||||
gather_radius = 0.5 # Radius for radiance estimation
|
gather_radius = 0.5 # Radius for radiance estimation
|
||||||
|
|
||||||
|
|
||||||
def random_unit_vector() -> Vector3:
|
def emit_photons():
|
||||||
"""Draw a direction uniformly over the sphere."""
|
for _ in range(num_photons):
|
||||||
theta = _rng.uniform(0, 2 * np.pi)
|
# Emit photons in random directions from the light source
|
||||||
z = _rng.uniform(-1, 1)
|
direction = random_unit_vector()
|
||||||
|
power = light_power / num_photons
|
||||||
|
photon = Photon(light_position, direction, power)
|
||||||
|
trace_photon(photon, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def trace_photon(photon, depth):
|
||||||
|
global PHOTONS
|
||||||
|
PHOTONS += 1
|
||||||
|
if depth > max_depth:
|
||||||
|
return
|
||||||
|
closest_t = np.inf
|
||||||
|
hit_object = None
|
||||||
|
hit_info = None
|
||||||
|
# Find the nearest intersection
|
||||||
|
for obj in objects:
|
||||||
|
result = obj.intersect(photon.position, photon.direction)
|
||||||
|
if result:
|
||||||
|
t, hit_point, normal = result
|
||||||
|
if t < closest_t:
|
||||||
|
closest_t = t
|
||||||
|
hit_object = obj
|
||||||
|
hit_info = (hit_point, normal)
|
||||||
|
if hit_object:
|
||||||
|
hit_point, normal = hit_info
|
||||||
|
photon_map.append((hit_point, photon.power))
|
||||||
|
# Diffuse reflection
|
||||||
|
new_direction = random_hemisphere_direction(normal)
|
||||||
|
photon.position = hit_point
|
||||||
|
photon.direction = new_direction
|
||||||
|
# Absorb some power
|
||||||
|
photon.power = photon.power * 0.8 # Simple absorption
|
||||||
|
trace_photon(photon, depth + 1)
|
||||||
|
|
||||||
|
|
||||||
|
def random_unit_vector():
|
||||||
|
theta = np.random.uniform(0, 2 * np.pi)
|
||||||
|
z = np.random.uniform(-1, 1)
|
||||||
r = np.sqrt(1 - z * z)
|
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: Vector3) -> Vector3:
|
def random_hemisphere_direction(normal):
|
||||||
"""Draw a direction uniformly over the hemisphere around `normal`."""
|
dir = random_unit_vector()
|
||||||
direction = random_unit_vector()
|
if dir.dot(normal) < 0:
|
||||||
if direction.dot(normal) < 0:
|
dir = Vector3(-dir.x, -dir.y, -dir.z)
|
||||||
direction = Vector3(-direction.x, -direction.y, -direction.z)
|
return dir
|
||||||
return direction
|
|
||||||
|
|
||||||
|
|
||||||
def nearest_hit(
|
def render_image(width, height):
|
||||||
ray_origin: Vector3, ray_direction: Vector3
|
aspect_ratio = width / height
|
||||||
) -> tuple[Surface, Vector3, Vector3] | None:
|
fov = np.pi / 3 # 60 degrees field of view
|
||||||
"""Return the closest surface the ray meets, with its point and normal."""
|
image = np.zeros((height, width, 3))
|
||||||
|
for y in range(height):
|
||||||
|
for x in range(width):
|
||||||
|
# Convert pixel coordinate to camera ray
|
||||||
|
px = (2 * (x + 0.5) / width - 1) * np.tan(fov / 2) * aspect_ratio
|
||||||
|
py = (1 - 2 * (y + 0.5) / height) * np.tan(fov / 2)
|
||||||
|
ray_origin = Vector3(0, 0, 0)
|
||||||
|
ray_direction = Vector3(px, py, -1).normalize()
|
||||||
|
color = trace_ray(ray_origin, ray_direction)
|
||||||
|
image[y, x, :] = np.clip(color, 0, 1)
|
||||||
|
return image
|
||||||
|
|
||||||
|
|
||||||
|
def trace_ray(ray_origin, ray_direction):
|
||||||
closest_t = np.inf
|
closest_t = np.inf
|
||||||
hit_object = None
|
hit_object = None
|
||||||
hit_info = None
|
hit_info = None
|
||||||
@ -80,59 +185,35 @@ def nearest_hit(
|
|||||||
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)
|
hit_info = (hit_point, normal, obj.color)
|
||||||
if hit_object is None or hit_info is None:
|
if hit_object:
|
||||||
return None
|
hit_point, normal, color = hit_info
|
||||||
return (hit_object, hit_info[0], hit_info[1])
|
direct_light = compute_direct_light(hit_point, normal)
|
||||||
|
indirect_light = estimate_radiance(hit_point, normal)
|
||||||
|
return color * (direct_light + indirect_light)
|
||||||
|
return np.array([0, 0, 0]) # Background color
|
||||||
|
|
||||||
|
|
||||||
def trace_photon(photon: Photon, depth: int) -> int:
|
def compute_direct_light(point, normal):
|
||||||
"""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 * _SHADOW_OFFSET
|
shadow_origin = point + normal * 1e-5
|
||||||
|
shadow_ray = direction_to_light
|
||||||
|
in_shadow = False
|
||||||
for obj in objects:
|
for obj in objects:
|
||||||
if obj.intersect(shadow_origin, direction_to_light):
|
result = obj.intersect(shadow_origin, shadow_ray)
|
||||||
return np.array([0, 0, 0])
|
if result:
|
||||||
|
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: Vector3, normal: Vector3) -> np.ndarray:
|
def estimate_radiance(point, normal):
|
||||||
"""Gather the photons within `gather_radius` of `point` into a radiance."""
|
# Gather photons within the gather_radius
|
||||||
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()
|
||||||
@ -143,62 +224,27 @@ def estimate_radiance(point: Vector3, normal: Vector3) -> np.ndarray:
|
|||||||
return accumulated_power / (area * num_photons)
|
return accumulated_power / (area * num_photons)
|
||||||
|
|
||||||
|
|
||||||
def trace_ray(ray_origin: Vector3, ray_direction: Vector3) -> np.ndarray:
|
# Main execution
|
||||||
"""Shade one camera ray with direct light plus gathered photons."""
|
if __name__ == "__main__":
|
||||||
hit = nearest_hit(ray_origin, ray_direction)
|
print("Emitting photons...")
|
||||||
if hit is None:
|
emit_photons()
|
||||||
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)
|
||||||
|
|
||||||
logger.info(
|
print(
|
||||||
"Render Took: %ss\nresolution: %sx%s\nphotons (emitted): %s\n"
|
f"Render Took: {round(time.time() - t0, 2)}s\n"
|
||||||
"photons (reflected): %s\nphotons (total): %s\nrays: %s",
|
f"resolution: {width}x{height}\n"
|
||||||
round(time.time() - t0, 2),
|
f"photons (emitted): {num_photons}\n"
|
||||||
width,
|
f"photons (reflected): {PHOTONS - num_photons}\n"
|
||||||
height,
|
f"photons (total): {PHOTONS}\n"
|
||||||
num_photons,
|
f"rays: {width * height}"
|
||||||
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
Executable file → Normal file
11
Programming/TRAK/lab6.py
Executable file → Normal file
@ -1,11 +1,2 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""Lab 6 driver: run another script in this directory by path.
|
|
||||||
|
|
||||||
`script_path` was filled in by hand during the lab, which is why it is empty
|
|
||||||
here -- the file is kept as submitted.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import runpy
|
|
||||||
|
|
||||||
script_path = "" # path to script
|
script_path = "" # path to script
|
||||||
runpy.run_path(script_path, run_name="__main__")
|
exec(compile(open(script_path).read(), script_path, "exec"))
|
||||||
|
|||||||
57
Programming/TRAK/main.py
Executable file → Normal file
57
Programming/TRAK/main.py
Executable file → Normal file
@ -1,25 +1,14 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""Entry point: render a scene with one of the three algorithms in this course.
|
|
||||||
|
|
||||||
The algorithm, scene, resolution and output path all default to `config.ini`
|
|
||||||
and are overridable on the command line.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import importlib
|
import importlib
|
||||||
import logging
|
import os
|
||||||
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")
|
||||||
|
|
||||||
@ -109,64 +98,58 @@ def main() -> None:
|
|||||||
|
|
||||||
# Run the selected algorithm
|
# Run the selected algorithm
|
||||||
if args.algorithm == "ray_tracing0":
|
if args.algorithm == "ray_tracing0":
|
||||||
logger.info("Starting ray tracing zero...")
|
print("Starting ray tracing zero...")
|
||||||
|
# ray_trace(args.scene, args.environment_map, image_width=width, image_height=height, output_file="output_ray_traced.png")
|
||||||
ray_trace(
|
ray_trace(
|
||||||
args.num_spheres,
|
args.num_spheres,
|
||||||
args.environment,
|
args.environment_map,
|
||||||
image_width=width,
|
image_width=width,
|
||||||
# na razie generujemy w kodzie, ale potem trzeba będzie obj wczytywać
|
image_height=height, # na razie generujemy w kodzie, ale potem trzeba będzie obj wczytywać
|
||||||
image_height=height,
|
output_file="output_ray_traced.png",
|
||||||
output_file=Path("outputs") / args.output,
|
|
||||||
)
|
)
|
||||||
elif args.algorithm == "ray_tracing":
|
elif args.algorithm == "ray_tracing":
|
||||||
logger.info("Starting ray tracing...")
|
print("Starting ray tracing...")
|
||||||
try:
|
try:
|
||||||
logger.info("%s", args.scene)
|
print(args.scene)
|
||||||
scene_module = importlib.import_module(f"scenes.{args.scene}")
|
scene_module = importlib.import_module(f"scenes.{args.scene}")
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
logger.info(
|
print(f"Error: Scene '{args.scene}' not found in the 'scenes' directory.")
|
||||||
"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:
|
||||||
logger.info(
|
print(
|
||||||
"Error: Scene '%s' does not define a `setup_scene` function.",
|
f"Error: Scene '{args.scene}' does not define a `setup_scene` function."
|
||||||
args.scene,
|
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
# Renderowanie
|
# Renderowanie
|
||||||
logger.info(
|
print(
|
||||||
"Rendering scene '%s' with %s samples per pixel...",
|
f"Rendering scene '{args.scene}' with {args.samples_per_pixel} 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 = Path("outputs") / args.output
|
output_path = os.path.join("outputs", args.output)
|
||||||
img.save(output_path)
|
img.save(output_path)
|
||||||
logger.info("Image saved to %s", output_path)
|
print(f"Image saved to {output_path}")
|
||||||
if args.show:
|
if args.show:
|
||||||
img.show()
|
img.show()
|
||||||
elif args.algorithm == "photon_mapping":
|
elif args.algorithm == "photon_mapping":
|
||||||
logger.info("Starting photon mapping...")
|
print("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 = Path("outputs") / args.output
|
output_path = os.path.join("outputs", args.output)
|
||||||
plt.savefig(output_path)
|
plt.savefig(output_path)
|
||||||
logger.info("Image saved to %s", output_path)
|
print(f"Image saved to {output_path}")
|
||||||
if args.show:
|
if args.show:
|
||||||
plt.show()
|
plt.show()
|
||||||
else:
|
else:
|
||||||
logger.info("Unknown algorithm: %s", args.algorithm)
|
print(f"Unknown algorithm: {args.algorithm}")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
logging.basicConfig(format="%(message)s", level=logging.INFO)
|
|
||||||
main()
|
main()
|
||||||
|
|||||||
@ -1,114 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""Vectors, photons and the two surfaces the photon mapper traces.
|
|
||||||
|
|
||||||
Split out of `photon_mapping.py` so each file stays under this repo's
|
|
||||||
250-line cap; the classes are unchanged.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
|
|
||||||
# A ray whose direction is this close to parallel with a plane never hits it.
|
|
||||||
_PARALLEL_EPSILON = 1e-6
|
|
||||||
|
|
||||||
class Vector3:
|
|
||||||
"""A 3D vector, with just the operations this renderer needs."""
|
|
||||||
|
|
||||||
def __init__(self, x: float, y: float, z: float) -> None:
|
|
||||||
"""Store the three components."""
|
|
||||||
self.x = x
|
|
||||||
self.y = y
|
|
||||||
self.z = z
|
|
||||||
|
|
||||||
def __add__(self, other: Vector3) -> Vector3:
|
|
||||||
"""Return the component-wise sum."""
|
|
||||||
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
|
|
||||||
|
|
||||||
def __sub__(self, other: Vector3) -> Vector3:
|
|
||||||
"""Return the component-wise difference."""
|
|
||||||
return Vector3(self.x - other.x, self.y - other.y, self.z - other.z)
|
|
||||||
|
|
||||||
def __mul__(self, scalar: float) -> Vector3:
|
|
||||||
"""Return this vector scaled by `scalar`."""
|
|
||||||
return Vector3(self.x * scalar, self.y * scalar, self.z * scalar)
|
|
||||||
|
|
||||||
def dot(self, other: Vector3) -> float:
|
|
||||||
"""Return the dot product with `other`."""
|
|
||||||
return self.x * other.x + self.y * other.y + self.z * other.z
|
|
||||||
|
|
||||||
def norm(self) -> float:
|
|
||||||
"""Return the length of this vector."""
|
|
||||||
return float(np.sqrt(self.dot(self)))
|
|
||||||
|
|
||||||
def normalize(self) -> Vector3:
|
|
||||||
"""Return a new vector of unit length pointing the same way."""
|
|
||||||
n = self.norm()
|
|
||||||
return Vector3(self.x / n, self.y / n, self.z / n)
|
|
||||||
|
|
||||||
|
|
||||||
class Photon:
|
|
||||||
"""A packet of light energy travelling in a straight line."""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self, position: Vector3, direction: Vector3, power: np.ndarray
|
|
||||||
) -> None:
|
|
||||||
"""Store where the photon is, where it is going, and what it carries."""
|
|
||||||
self.position = position
|
|
||||||
self.direction = direction
|
|
||||||
self.power = power
|
|
||||||
|
|
||||||
|
|
||||||
class Sphere:
|
|
||||||
"""A sphere of uniform colour."""
|
|
||||||
|
|
||||||
def __init__(self, center: Vector3, radius: float, color: np.ndarray) -> None:
|
|
||||||
"""Store the sphere's geometry and colour."""
|
|
||||||
self.center = center
|
|
||||||
self.radius = radius
|
|
||||||
self.color = color
|
|
||||||
|
|
||||||
def intersect(
|
|
||||||
self, ray_origin: Vector3, ray_direction: Vector3
|
|
||||||
) -> tuple[float, Vector3, Vector3] | None:
|
|
||||||
"""Return the nearest hit as (distance, point, normal), or None."""
|
|
||||||
oc = ray_origin - self.center
|
|
||||||
a = ray_direction.dot(ray_direction)
|
|
||||||
b = 2.0 * oc.dot(ray_direction)
|
|
||||||
c = oc.dot(oc) - self.radius * self.radius
|
|
||||||
discriminant = b * b - 4 * a * c
|
|
||||||
if discriminant < 0:
|
|
||||||
return None
|
|
||||||
t = (-b - np.sqrt(discriminant)) / (2.0 * a)
|
|
||||||
if t < 0:
|
|
||||||
t = (-b + np.sqrt(discriminant)) / (2.0 * a)
|
|
||||||
if t < 0:
|
|
||||||
return None
|
|
||||||
hit_point = ray_origin + ray_direction * t
|
|
||||||
normal = (hit_point - self.center).normalize()
|
|
||||||
return (t, hit_point, normal)
|
|
||||||
|
|
||||||
|
|
||||||
class Plane:
|
|
||||||
"""An infinite plane of uniform colour."""
|
|
||||||
|
|
||||||
def __init__(self, point: Vector3, normal: Vector3, color: np.ndarray) -> None:
|
|
||||||
"""Store a point on the plane, its (normalised) normal, and its colour."""
|
|
||||||
self.point = point
|
|
||||||
self.normal = normal.normalize()
|
|
||||||
self.color = color
|
|
||||||
|
|
||||||
def intersect(
|
|
||||||
self, ray_origin: Vector3, ray_direction: Vector3
|
|
||||||
) -> tuple[float, Vector3, Vector3] | None:
|
|
||||||
"""Return the nearest hit as (distance, point, normal), or None."""
|
|
||||||
denom = self.normal.dot(ray_direction)
|
|
||||||
if abs(denom) > _PARALLEL_EPSILON:
|
|
||||||
t = (self.point - ray_origin).dot(self.normal) / denom
|
|
||||||
if t >= 0:
|
|
||||||
hit_point = ray_origin + ray_direction * t
|
|
||||||
return (t, hit_point, self.normal)
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
Surface = Sphere | Plane
|
|
||||||
284
Programming/TRAK/photon_mapping.py
Executable file → Normal file
284
Programming/TRAK/photon_mapping.py
Executable file → Normal file
@ -1,150 +1,181 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""A two-pass photon mapper: scatter photons from the light, then gather them.
|
|
||||||
|
|
||||||
The first pass emits `num_photons` from the light and records every surface
|
|
||||||
they land on. The second pass shoots one camera ray per pixel and shades each
|
|
||||||
hit with direct light plus the photons gathered within `gather_radius`.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from typing import cast
|
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from photon_geometry import Photon, Plane, Sphere, Surface, Vector3
|
|
||||||
|
|
||||||
# Shadow rays start this far off the surface they were cast from.
|
|
||||||
_SHADOW_OFFSET = 1e-5
|
|
||||||
|
|
||||||
# Fraction of its power a photon keeps across one diffuse bounce.
|
|
||||||
_BOUNCE_ABSORPTION = 0.8
|
|
||||||
|
|
||||||
|
|
||||||
|
# Define basic vector operations
|
||||||
|
class Vector3:
|
||||||
|
def __init__(self, x, y, z):
|
||||||
|
self.x = x
|
||||||
|
self.y = y
|
||||||
|
self.z = z
|
||||||
|
|
||||||
|
def __add__(self, other):
|
||||||
|
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
|
||||||
|
|
||||||
|
def __sub__(self, other):
|
||||||
|
return Vector3(self.x - other.x, self.y - other.y, self.z - other.z)
|
||||||
|
|
||||||
|
def __mul__(self, scalar):
|
||||||
|
return Vector3(self.x * scalar, self.y * scalar, self.z * scalar)
|
||||||
|
|
||||||
|
def dot(self, other):
|
||||||
|
return self.x * other.x + self.y * other.y + self.z * other.z
|
||||||
|
|
||||||
|
def norm(self):
|
||||||
|
return np.sqrt(self.dot(self))
|
||||||
|
|
||||||
|
def normalize(self):
|
||||||
|
n = self.norm()
|
||||||
|
return Vector3(self.x / n, self.y / n, self.z / n)
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
class Photon:
|
||||||
class Scene:
|
def __init__(self, position, direction, power):
|
||||||
"""Everything the two passes share: the geometry, the light, the photons."""
|
self.position = position
|
||||||
|
self.direction = direction
|
||||||
objects: list[Surface]
|
self.power = power
|
||||||
rng: np.random.Generator
|
|
||||||
light_position: Vector3
|
|
||||||
light_power: np.ndarray
|
|
||||||
gather_radius: float
|
|
||||||
photon_map: list[tuple[Vector3, np.ndarray]]
|
|
||||||
|
|
||||||
|
|
||||||
def random_unit_vector(rng: np.random.Generator) -> Vector3:
|
class Sphere:
|
||||||
"""Draw a direction uniformly over the sphere."""
|
def __init__(self, center, radius, color):
|
||||||
theta = rng.uniform(0, 2 * np.pi)
|
self.center = center
|
||||||
z = rng.uniform(-1, 1)
|
self.radius = radius
|
||||||
r = np.sqrt(1 - z * z)
|
self.color = color
|
||||||
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)
|
||||||
|
|
||||||
|
|
||||||
def random_hemisphere_direction(rng: np.random.Generator, normal: Vector3) -> Vector3:
|
class Plane:
|
||||||
"""Draw a direction uniformly over the hemisphere around `normal`."""
|
def __init__(self, point, normal, color):
|
||||||
direction = random_unit_vector(rng)
|
self.point = point
|
||||||
if direction.dot(normal) < 0:
|
self.normal = normal.normalize()
|
||||||
direction = Vector3(-direction.x, -direction.y, -direction.z)
|
self.color = color
|
||||||
return direction
|
|
||||||
|
|
||||||
|
def intersect(self, ray_origin, ray_direction):
|
||||||
def nearest_hit(
|
denom = self.normal.dot(ray_direction)
|
||||||
objects: list[Surface], ray_origin: Vector3, ray_direction: Vector3
|
if abs(denom) > 1e-6:
|
||||||
) -> tuple[Surface, Vector3, Vector3] | None:
|
t = (self.point - ray_origin).dot(self.normal) / denom
|
||||||
"""Return the closest surface the ray meets, with its point and normal."""
|
if t >= 0:
|
||||||
closest_t = np.inf
|
hit_point = ray_origin + ray_direction * t
|
||||||
hit_object = None
|
return (t, hit_point, self.normal)
|
||||||
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 trace_photon(scene: Scene, photon: Photon, depth: int, max_depth: int) -> None:
|
def render_photon_mapping(width, height, num_photons, max_depth, gather_radius):
|
||||||
"""Bounce one photon through the scene, recording every surface it lands on."""
|
# Photon mapping logic
|
||||||
if depth > max_depth:
|
photon_map = []
|
||||||
return
|
sphere = Sphere(Vector3(0, 0, -5), 1.0, np.array([1, 0, 0])) # Red sphere
|
||||||
hit = nearest_hit(scene.objects, photon.position, photon.direction)
|
plane = Plane(
|
||||||
if hit is not None:
|
Vector3(0, -1, 0), Vector3(0, 1, 0), np.array([0.5, 0.5, 0.5])
|
||||||
_, hit_point, normal = hit
|
) # Gray plane
|
||||||
scene.photon_map.append((hit_point, photon.power))
|
objects = [sphere, plane]
|
||||||
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(scene: Scene, num_photons: int, max_depth: int) -> None:
|
def emit_photons():
|
||||||
"""Run the scatter pass: emit `num_photons` from the light and trace each."""
|
for _ in range(num_photons):
|
||||||
for _ in range(num_photons):
|
direction = random_unit_vector()
|
||||||
direction = random_unit_vector(scene.rng)
|
power = light_power / num_photons
|
||||||
power = scene.light_power / num_photons
|
photon = Photon(light_position, direction, power)
|
||||||
photon = Photon(scene.light_position, direction, power)
|
trace_photon(photon, 0)
|
||||||
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 compute_direct_light(scene: Scene, point: Vector3, normal: Vector3) -> np.ndarray:
|
def random_unit_vector():
|
||||||
"""Return the light arriving straight from the source, or black if shadowed."""
|
theta = np.random.uniform(0, 2 * np.pi)
|
||||||
direction_to_light = (scene.light_position - point).normalize()
|
z = np.random.uniform(-1, 1)
|
||||||
shadow_origin = point + normal * _SHADOW_OFFSET
|
r = np.sqrt(1 - z * z)
|
||||||
for obj in scene.objects:
|
return Vector3(r * np.cos(theta), r * np.sin(theta), z)
|
||||||
if obj.intersect(shadow_origin, direction_to_light):
|
|
||||||
return np.array([0, 0, 0])
|
|
||||||
intensity = max(0, normal.dot(direction_to_light))
|
|
||||||
distance_squared = (scene.light_position - point).norm() ** 2
|
|
||||||
return intensity * scene.light_power / (4 * np.pi * distance_squared)
|
|
||||||
|
|
||||||
|
def random_hemisphere_direction(normal):
|
||||||
|
dir = random_unit_vector()
|
||||||
|
if dir.dot(normal) < 0:
|
||||||
|
dir = Vector3(-dir.x, -dir.y, -dir.z)
|
||||||
|
return dir
|
||||||
|
|
||||||
def estimate_radiance(scene: Scene, point: Vector3, normal: Vector3) -> np.ndarray:
|
def trace_ray(ray_origin, ray_direction):
|
||||||
"""Gather the photons within `gather_radius` of `point` into a radiance."""
|
closest_t = np.inf
|
||||||
accumulated_power = np.array([0.0, 0.0, 0.0])
|
hit_object = None
|
||||||
for photon_pos, photon_power in scene.photon_map:
|
hit_info = None
|
||||||
distance = (photon_pos - point).norm()
|
for obj in objects:
|
||||||
if distance < scene.gather_radius:
|
result = obj.intersect(ray_origin, ray_direction)
|
||||||
weight = max(0, normal.dot((photon_pos - point).normalize()))
|
if result:
|
||||||
accumulated_power += photon_power * weight
|
t, hit_point, normal = result
|
||||||
area = np.pi * scene.gather_radius**2
|
if t < closest_t:
|
||||||
return accumulated_power / area
|
closest_t = t
|
||||||
|
hit_object = obj
|
||||||
|
hit_info = (hit_point, normal, obj.color)
|
||||||
def trace_ray(scene: Scene, ray_origin: Vector3, ray_direction: Vector3) -> np.ndarray:
|
if hit_object:
|
||||||
"""Shade one camera ray with direct light plus gathered photons."""
|
hit_point, normal, color = hit_info
|
||||||
hit = nearest_hit(scene.objects, ray_origin, ray_direction)
|
direct_light = compute_direct_light(hit_point, normal)
|
||||||
if hit is None:
|
indirect_light = estimate_radiance(hit_point, normal)
|
||||||
|
return color * (direct_light + indirect_light)
|
||||||
return np.array([0, 0, 0])
|
return np.array([0, 0, 0])
|
||||||
hit_object, hit_point, normal = hit
|
|
||||||
direct_light = compute_direct_light(scene, hit_point, normal)
|
|
||||||
indirect_light = estimate_radiance(scene, hit_point, normal)
|
|
||||||
return cast("np.ndarray", hit_object.color * (direct_light + indirect_light))
|
|
||||||
|
|
||||||
|
def compute_direct_light(point, normal):
|
||||||
|
direction_to_light = (light_position - point).normalize()
|
||||||
|
shadow_origin = point + normal * 1e-5
|
||||||
|
shadow_ray = direction_to_light
|
||||||
|
in_shadow = False
|
||||||
|
for obj in objects:
|
||||||
|
result = obj.intersect(shadow_origin, shadow_ray)
|
||||||
|
if result:
|
||||||
|
in_shadow = True
|
||||||
|
break
|
||||||
|
if in_shadow:
|
||||||
|
return np.array([0, 0, 0])
|
||||||
|
intensity = max(0, normal.dot(direction_to_light))
|
||||||
|
return (
|
||||||
|
intensity * light_power / (4 * np.pi * (light_position - point).norm() ** 2)
|
||||||
|
)
|
||||||
|
|
||||||
def render_photon_mapping(
|
def estimate_radiance(point, normal):
|
||||||
width: int, height: int, num_photons: int, max_depth: int, gather_radius: float
|
accumulated_power = np.array([0.0, 0.0, 0.0])
|
||||||
) -> np.ndarray:
|
for photon_pos, photon_power in photon_map:
|
||||||
"""Render the fixed red-sphere-over-grey-plane scene and return the image."""
|
distance = (photon_pos - point).norm()
|
||||||
scene = Scene(
|
if distance < gather_radius:
|
||||||
objects=[
|
weight = max(0, normal.dot((photon_pos - point).normalize()))
|
||||||
Sphere(Vector3(0, 0, -5), 1.0, np.array([1, 0, 0])), # Red sphere
|
accumulated_power += photon_power * weight
|
||||||
Plane(Vector3(0, -1, 0), Vector3(0, 1, 0), np.array([0.5, 0.5, 0.5])),
|
area = np.pi * gather_radius**2
|
||||||
],
|
return accumulated_power / area
|
||||||
rng=np.random.default_rng(),
|
|
||||||
light_position=Vector3(-5, 5, -5),
|
emit_photons()
|
||||||
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
|
||||||
@ -153,8 +184,9 @@ def render_photon_mapping(
|
|||||||
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(scene, Vector3(0, 0, 0), ray_direction)
|
color = trace_ray(ray_origin, ray_direction)
|
||||||
image[y, x, :] = np.clip(color, 0, 1)
|
image[y, x, :] = np.clip(color, 0, 1)
|
||||||
|
|
||||||
return image
|
return image
|
||||||
|
|||||||
@ -1,233 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""Ray/geometry intersection and Phong shading for the `ray_tracing0` renderer.
|
|
||||||
|
|
||||||
These were nested closures inside `rendering.ray_trace`, which is what made
|
|
||||||
that one function 460 lines long. They are pure now: the scene and the light
|
|
||||||
constants are passed in rather than captured, so each can be read on its own.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from typing import Any, cast
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
|
|
||||||
# A scene object is a plain dict tagged with "type": "sphere" or "plane".
|
|
||||||
SceneObject = dict[str, Any]
|
|
||||||
|
|
||||||
# A ray whose direction is this close to parallel with a plane never hits it.
|
|
||||||
_PARALLEL_EPSILON = 1e-6
|
|
||||||
|
|
||||||
# Shadow and reflection rays start this far off the surface, so that the
|
|
||||||
# surface they just left does not intersect them at t=0.
|
|
||||||
SURFACE_OFFSET = 0.0001
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class Lighting:
|
|
||||||
"""The single point light and the Phong coefficients every surface uses."""
|
|
||||||
|
|
||||||
position: np.ndarray
|
|
||||||
color: np.ndarray
|
|
||||||
ambient: float
|
|
||||||
diffuse_c: float
|
|
||||||
specular_c: float
|
|
||||||
specular_k: int
|
|
||||||
|
|
||||||
|
|
||||||
def normalize(vector: np.ndarray) -> np.ndarray:
|
|
||||||
"""Scale `vector` to unit length, in place, and return it."""
|
|
||||||
vector /= np.linalg.norm(vector)
|
|
||||||
return vector
|
|
||||||
|
|
||||||
|
|
||||||
def intersect_plane(
|
|
||||||
ray_origin: np.ndarray,
|
|
||||||
ray_direction: np.ndarray,
|
|
||||||
plane_point: np.ndarray,
|
|
||||||
plane_normal: np.ndarray,
|
|
||||||
) -> float:
|
|
||||||
"""Distance along the ray to the plane, or +inf if it never reaches it."""
|
|
||||||
denom = np.dot(ray_direction, plane_normal)
|
|
||||||
if np.abs(denom) < _PARALLEL_EPSILON:
|
|
||||||
return np.inf
|
|
||||||
d = np.dot(plane_point - ray_origin, plane_normal) / denom
|
|
||||||
if d < 0:
|
|
||||||
return np.inf
|
|
||||||
return float(d)
|
|
||||||
|
|
||||||
|
|
||||||
def calculate_sphere_intersection(a: float, b: float, c: float, disc: float) -> float:
|
|
||||||
"""Solve `a*t^2 + b*t + c` for the nearest root ahead of the ray origin.
|
|
||||||
|
|
||||||
`disc` is the discriminant, passed in because the caller already has it.
|
|
||||||
The root is taken via the numerically stable `q` form rather than the
|
|
||||||
textbook quadratic formula, which loses precision when `b` dominates.
|
|
||||||
"""
|
|
||||||
if disc > 0:
|
|
||||||
distance_squared = np.sqrt(disc)
|
|
||||||
q = (-b - distance_squared) / 2.0 if b < 0 else (-b + distance_squared) / 2.0
|
|
||||||
t0 = q / a
|
|
||||||
t1 = c / q
|
|
||||||
t0, t1 = min(t0, t1), max(t0, t1)
|
|
||||||
if t1 >= 0:
|
|
||||||
return float(t1) if t0 < 0 else float(t0)
|
|
||||||
return np.inf
|
|
||||||
|
|
||||||
|
|
||||||
def intersect_sphere(
|
|
||||||
ray_origin: np.ndarray,
|
|
||||||
ray_direction: np.ndarray,
|
|
||||||
sphere_center: np.ndarray,
|
|
||||||
sphere_radius: float,
|
|
||||||
) -> float:
|
|
||||||
"""Distance along the ray to the sphere, or +inf if it misses."""
|
|
||||||
a = np.dot(ray_direction, ray_direction)
|
|
||||||
origin_to_center = ray_origin - sphere_center
|
|
||||||
b = 2 * np.dot(ray_direction, origin_to_center)
|
|
||||||
radius_squared = sphere_radius * sphere_radius
|
|
||||||
c = np.dot(origin_to_center, origin_to_center) - radius_squared
|
|
||||||
disc = b * b - 4 * a * c
|
|
||||||
return calculate_sphere_intersection(a, b, c, disc)
|
|
||||||
|
|
||||||
|
|
||||||
def intersect(
|
|
||||||
ray_origin: np.ndarray, ray_direction: np.ndarray, object_: SceneObject
|
|
||||||
) -> float:
|
|
||||||
"""Dispatch to the plane or sphere intersection for `object_`."""
|
|
||||||
if object_["type"] == "plane":
|
|
||||||
return intersect_plane(
|
|
||||||
ray_origin, ray_direction, object_["position"], object_["normal"]
|
|
||||||
)
|
|
||||||
return intersect_sphere(
|
|
||||||
ray_origin, ray_direction, object_["position"], object_["radius"]
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def get_normal(object_: SceneObject, intersection_point: np.ndarray) -> np.ndarray:
|
|
||||||
"""Surface normal of `object_` at `intersection_point`."""
|
|
||||||
if object_["type"] == "sphere":
|
|
||||||
return normalize(intersection_point - object_["position"])
|
|
||||||
if object_["type"] == "plane":
|
|
||||||
return cast("np.ndarray", object_["normal"])
|
|
||||||
msg = f"Unknown object type: {object_['type']}"
|
|
||||||
raise ValueError(msg)
|
|
||||||
|
|
||||||
|
|
||||||
def get_color(object_: SceneObject, intersection_point: np.ndarray) -> np.ndarray:
|
|
||||||
"""Return the colour of `object_`: either a constant or a function of position."""
|
|
||||||
color = object_["color"]
|
|
||||||
if not hasattr(color, "__len__"):
|
|
||||||
color = color(intersection_point)
|
|
||||||
return cast("np.ndarray", color)
|
|
||||||
|
|
||||||
|
|
||||||
def find_intersection(
|
|
||||||
scene: list[SceneObject], ray_origin: np.ndarray, ray_direction: np.ndarray
|
|
||||||
) -> tuple[float, int]:
|
|
||||||
"""Return the distance to the nearest hit and that object's scene index.
|
|
||||||
|
|
||||||
The index is -1 when the ray hits nothing, in which case the distance is
|
|
||||||
+inf and callers stop.
|
|
||||||
"""
|
|
||||||
t = np.inf
|
|
||||||
obj_idx = -1
|
|
||||||
for index, object_ in enumerate(scene):
|
|
||||||
t_obj = intersect(ray_origin, ray_direction, object_)
|
|
||||||
if t_obj < t:
|
|
||||||
t, obj_idx = t_obj, index
|
|
||||||
return t, obj_idx
|
|
||||||
|
|
||||||
|
|
||||||
def is_shadowed(
|
|
||||||
scene: list[SceneObject],
|
|
||||||
lighting: Lighting,
|
|
||||||
intersection_point: np.ndarray,
|
|
||||||
normal: np.ndarray,
|
|
||||||
obj_idx: int,
|
|
||||||
) -> bool:
|
|
||||||
"""Report whether anything but object `obj_idx` blocks the light here."""
|
|
||||||
to_light = normalize(lighting.position - intersection_point)
|
|
||||||
shadow_intersections = [
|
|
||||||
intersect(intersection_point + normal * SURFACE_OFFSET, to_light, obj_sh)
|
|
||||||
for k, obj_sh in enumerate(scene)
|
|
||||||
if k != obj_idx
|
|
||||||
]
|
|
||||||
return bool(shadow_intersections) and min(shadow_intersections) < np.inf
|
|
||||||
|
|
||||||
|
|
||||||
def compute_color(
|
|
||||||
lighting: Lighting,
|
|
||||||
object_: SceneObject,
|
|
||||||
intersection_point: np.ndarray,
|
|
||||||
normal: np.ndarray,
|
|
||||||
ray_origin: np.ndarray,
|
|
||||||
) -> tuple[SceneObject, np.ndarray, np.ndarray, np.ndarray]:
|
|
||||||
"""Shade the hit with Blinn-Phong and return it alongside the hit geometry."""
|
|
||||||
color = get_color(object_, intersection_point)
|
|
||||||
to_light = normalize(lighting.position - intersection_point)
|
|
||||||
to_origin = normalize(ray_origin - intersection_point)
|
|
||||||
color_ray = lighting.ambient
|
|
||||||
diffuse_intensity = object_.get("diffuse_c", lighting.diffuse_c) * max(
|
|
||||||
np.dot(normal, to_light), 0
|
|
||||||
)
|
|
||||||
color_ray += diffuse_intensity * color
|
|
||||||
half_vector = normalize(to_light + to_origin)
|
|
||||||
specular_intensity = (
|
|
||||||
object_.get("specular_c", lighting.specular_c)
|
|
||||||
* max(np.dot(normal, half_vector), 0) ** lighting.specular_k
|
|
||||||
)
|
|
||||||
color_ray += specular_intensity * lighting.color
|
|
||||||
return object_, intersection_point, normal, color_ray
|
|
||||||
|
|
||||||
|
|
||||||
def trace_ray(
|
|
||||||
scene: list[SceneObject],
|
|
||||||
lighting: Lighting,
|
|
||||||
ray_origin: np.ndarray,
|
|
||||||
ray_direction: np.ndarray,
|
|
||||||
) -> tuple[SceneObject, np.ndarray, np.ndarray, np.ndarray] | None:
|
|
||||||
"""Trace one ray and return its hit, or None if it misses or lands in shadow."""
|
|
||||||
t, obj_idx = find_intersection(scene, ray_origin, ray_direction)
|
|
||||||
if t == np.inf:
|
|
||||||
return None
|
|
||||||
object_ = scene[obj_idx]
|
|
||||||
intersection_point = ray_origin + ray_direction * t
|
|
||||||
normal = get_normal(object_, intersection_point)
|
|
||||||
if is_shadowed(scene, lighting, intersection_point, normal, obj_idx):
|
|
||||||
return None
|
|
||||||
return compute_color(lighting, object_, intersection_point, normal, ray_origin)
|
|
||||||
|
|
||||||
|
|
||||||
def make_sphere(
|
|
||||||
position: list[float], radius: float, color: np.ndarray
|
|
||||||
) -> SceneObject:
|
|
||||||
"""Build a sphere scene object."""
|
|
||||||
return {
|
|
||||||
"type": "sphere",
|
|
||||||
"position": np.array(position),
|
|
||||||
"radius": np.array(radius),
|
|
||||||
"color": np.array(color),
|
|
||||||
"reflection": 0.5,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def make_plane(
|
|
||||||
position: list[float],
|
|
||||||
normal: list[float],
|
|
||||||
color_a: np.ndarray,
|
|
||||||
color_b: np.ndarray,
|
|
||||||
) -> SceneObject:
|
|
||||||
"""Build a plane scene object with a checkerboard of `color_a`/`color_b`."""
|
|
||||||
return {
|
|
||||||
"type": "plane",
|
|
||||||
"position": np.array(position),
|
|
||||||
"normal": np.array(normal),
|
|
||||||
"color": lambda point: (
|
|
||||||
color_a if (int(point[0] * 2) % 2) == (int(point[2] * 2) % 2) else color_b
|
|
||||||
),
|
|
||||||
"diffuse_c": 0.75,
|
|
||||||
"specular_c": 0.5,
|
|
||||||
"reflection": 0.25,
|
|
||||||
}
|
|
||||||
518
Programming/TRAK/rendering.py
Executable file → Normal file
518
Programming/TRAK/rendering.py
Executable file → Normal file
@ -1,52 +1,382 @@
|
|||||||
#!/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 build_scene(num_spheres: int) -> list[SceneObject]:
|
def ray_trace(
|
||||||
"""Lay out a checkerboard plane and `num_spheres` spheres in a receding row."""
|
num_spheres, environment, image_width=400, image_height=300, output_file="fig.png"
|
||||||
|
):
|
||||||
|
IMAGE_WIDTH = image_width
|
||||||
|
IMAGE_HEIGHT = image_height
|
||||||
|
|
||||||
|
def normalize(vector):
|
||||||
|
"""Normalize a vector.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
vector (numpy.ndarray): The input vector to be normalized.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
numpy.ndarray: The normalized vector.
|
||||||
|
|
||||||
|
"""
|
||||||
|
vector /= np.linalg.norm(vector)
|
||||||
|
return vector
|
||||||
|
|
||||||
|
def intersect_plane(ray_origin, ray_direction, plane_point, plane_normal):
|
||||||
|
"""Calculate the intersection of a ray with a plane.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
ray_origin (numpy.ndarray): A 3D point representing the origin of the ray.
|
||||||
|
ray_direction (numpy.ndarray): A normalized 3D vector representing the
|
||||||
|
direction of the ray.
|
||||||
|
plane_point (numpy.ndarray): A 3D point representing a point on the plane.
|
||||||
|
plane_normal (numpy.ndarray): A normalized 3D vector representing
|
||||||
|
the normal of the plane.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
float: The distance from the origin ray_origin to the intersection
|
||||||
|
point with the plane.
|
||||||
|
Returns +inf if there is no intersection or if the intersection is
|
||||||
|
behind the origin.
|
||||||
|
|
||||||
|
"""
|
||||||
|
denom = np.dot(ray_direction, plane_normal)
|
||||||
|
if np.abs(denom) < 1e-6:
|
||||||
|
return np.inf
|
||||||
|
d = np.dot(plane_point - ray_origin, plane_normal) / denom
|
||||||
|
if d < 0:
|
||||||
|
return np.inf
|
||||||
|
return d
|
||||||
|
|
||||||
|
def intersect_sphere(ray_origin, ray_direction, sphere_center, sphere_radius):
|
||||||
|
"""Calculate the intersection of a ray with a sphere.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
ray_origin (numpy.ndarray): A 3D point representing the origin of the ray.
|
||||||
|
ray_direction (numpy.ndarray): A normalized 3D vector representing the
|
||||||
|
direction of the ray.
|
||||||
|
sphere_center (numpy.ndarray): A 3D point representing
|
||||||
|
the center of the sphere.
|
||||||
|
sphere_radius (float): The radius of the sphere.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
float: The distance from the origin ray_origin to the intersection
|
||||||
|
point with the sphere.
|
||||||
|
Returns +inf if there is no intersection or if the intersection is
|
||||||
|
behind the origin.
|
||||||
|
|
||||||
|
"""
|
||||||
|
a = np.dot(ray_direction, ray_direction)
|
||||||
|
origin_to_center = ray_origin - sphere_center
|
||||||
|
b = 2 * np.dot(ray_direction, origin_to_center)
|
||||||
|
radius_squared = sphere_radius * sphere_radius
|
||||||
|
c = np.dot(origin_to_center, origin_to_center) - radius_squared
|
||||||
|
disc = b * b - 4 * a * c
|
||||||
|
return calculate_sphere_intersection(a, b, c, disc)
|
||||||
|
|
||||||
|
def calculate_sphere_intersection(a, b, c, disc):
|
||||||
|
"""Calculate the
|
||||||
|
intersection distance of a ray with a sphere using the quadratic formula.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
a (float): Coefficient of t^2 in the quadratic equation.
|
||||||
|
b (float): Coefficient of t in the quadratic equation.
|
||||||
|
c (float): Constant term in the quadratic equation.
|
||||||
|
disc (float): Discriminant of the quadratic equation.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
float:
|
||||||
|
The distance from the origin to the intersection point with the sphere.
|
||||||
|
Returns +inf if there is no intersection
|
||||||
|
or if the intersection is behind the origin.
|
||||||
|
|
||||||
|
"""
|
||||||
|
if disc > 0:
|
||||||
|
distance_squared = np.sqrt(disc)
|
||||||
|
# q is used to find the roots of the quadratic equation
|
||||||
|
if b < 0:
|
||||||
|
q = (-b - distance_squared) / 2.0
|
||||||
|
else:
|
||||||
|
q = (-b + distance_squared) / 2.0
|
||||||
|
t0 = q / a
|
||||||
|
t1 = c / q
|
||||||
|
t0, t1 = min(t0, t1), max(t0, t1)
|
||||||
|
if t1 >= 0:
|
||||||
|
return t1 if t0 < 0 else t0
|
||||||
|
return np.inf
|
||||||
|
|
||||||
|
def intersect(ray_origin, ray_direction, object_):
|
||||||
|
"""Calculate the intersection of a ray with an object.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
ray_origin (numpy.ndarray): A 3D point representing the origin of the ray.
|
||||||
|
ray_direction (numpy.ndarray): A normalized 3D vector representing the
|
||||||
|
direction of the ray.
|
||||||
|
obj (dict): A dictionary representing the object with keys
|
||||||
|
'type', 'position', 'normal' (for planes), and 'radius' (for spheres).
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
float: The distance from the origin ray_origin to the intersection
|
||||||
|
point with the object.
|
||||||
|
Returns +inf if there is no intersection or if the intersection is
|
||||||
|
behind the origin.
|
||||||
|
|
||||||
|
"""
|
||||||
|
if object_["type"] == "plane":
|
||||||
|
return intersect_plane(
|
||||||
|
ray_origin, ray_direction, object_["position"], object_["normal"]
|
||||||
|
)
|
||||||
|
# object_['type'] == 'sphere':
|
||||||
|
return intersect_sphere(
|
||||||
|
ray_origin, ray_direction, object_["position"], object_["radius"]
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_normal(object_, intersection_point):
|
||||||
|
"""Calculate the normal at the intersection point on the object.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
obj (dict): A dictionary representing the object with keys
|
||||||
|
'type' and 'position'.
|
||||||
|
intersection_point (numpy.ndarray): A 3D point representing the
|
||||||
|
intersection point on the object.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
numpy.ndarray: The normal vector at the intersection point.
|
||||||
|
|
||||||
|
"""
|
||||||
|
if object_["type"] == "sphere":
|
||||||
|
normal = normalize(intersection_point - object_["position"])
|
||||||
|
elif object_["type"] == "plane":
|
||||||
|
normal = object_["normal"]
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Unknown object type: {object_['type']}")
|
||||||
|
return normal
|
||||||
|
|
||||||
|
def get_color(object_, intersection_point):
|
||||||
|
"""Get the color of the object at the intersection point.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
object_ (dict): A dictionary representing the object with a key 'color'.
|
||||||
|
intersection_point (numpy.ndarray): A 3D point representing the
|
||||||
|
intersection point on the object.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
numpy.ndarray: The color of the object at the intersection point.
|
||||||
|
|
||||||
|
"""
|
||||||
|
color = object_["color"]
|
||||||
|
if not hasattr(color, "__len__"):
|
||||||
|
color = color(intersection_point)
|
||||||
|
return color
|
||||||
|
|
||||||
|
def trace_ray(ray_origin, ray_direction):
|
||||||
|
"""Trace a ray and find the color at the intersection point.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
ray_origin (numpy.ndarray): A 3D point representing the origin of the ray.
|
||||||
|
ray_direction (numpy.ndarray):
|
||||||
|
A normalized 3D vector representing the direction of the ray.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
tuple: A tuple containing the object,
|
||||||
|
intersection point, normal at the intersection,
|
||||||
|
and the color at the intersection point.
|
||||||
|
Returns None if there is no intersection.
|
||||||
|
|
||||||
|
"""
|
||||||
|
t, obj_idx = find_intersection(ray_origin, ray_direction)
|
||||||
|
if t == np.inf:
|
||||||
|
return None
|
||||||
|
object_, intersection_point = get_intersection_details(
|
||||||
|
ray_origin, ray_direction, t, obj_idx
|
||||||
|
)
|
||||||
|
normal, color = (
|
||||||
|
get_normal(object_, intersection_point),
|
||||||
|
get_color(object_, intersection_point),
|
||||||
|
)
|
||||||
|
if is_shadowed(intersection_point, normal, obj_idx):
|
||||||
|
return None
|
||||||
|
return compute_color(object_, intersection_point, normal, color, ray_origin)
|
||||||
|
|
||||||
|
def find_intersection(ray_origin, ray_direction):
|
||||||
|
"""Find the intersection of a ray with the objects in the scene.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
ray_origin (numpy.ndarray): A 3D point representing the origin of the ray.
|
||||||
|
ray_direction (numpy.ndarray):
|
||||||
|
A normalized 3D vector representing the direction of the ray.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
tuple: A tuple containing the distance to the intersection point
|
||||||
|
and the index of the intersected object.
|
||||||
|
|
||||||
|
"""
|
||||||
|
t = np.inf
|
||||||
|
obj_idx = -1
|
||||||
|
for index, object_ in enumerate(scene):
|
||||||
|
t_obj = intersect(ray_origin, ray_direction, object_)
|
||||||
|
if t_obj < t:
|
||||||
|
t, obj_idx = t_obj, index
|
||||||
|
return t, obj_idx
|
||||||
|
|
||||||
|
def get_intersection_details(ray_origin, ray_direction, t, obj_idx):
|
||||||
|
"""Get the details of the intersection point on the object.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
ray_origin (numpy.ndarray): A 3D point representing the origin of the ray.
|
||||||
|
ray_direction (numpy.ndarray):
|
||||||
|
A normalized 3D vector representing the direction of the ray.
|
||||||
|
t (float): The distance to the intersection point.
|
||||||
|
obj_idx (int): The index of the intersected object in the scene.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
tuple: A tuple containing the intersected object
|
||||||
|
and the intersection point.
|
||||||
|
|
||||||
|
"""
|
||||||
|
object_ = scene[obj_idx]
|
||||||
|
intersection_point = ray_origin + ray_direction * t
|
||||||
|
return object_, intersection_point
|
||||||
|
|
||||||
|
def is_shadowed(intersection_point, normal, obj_idx):
|
||||||
|
"""Determine if the intersection point is in shadow.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
intersection_point (numpy.ndarray):
|
||||||
|
A 3D point representing the intersection point on the object.
|
||||||
|
normal (numpy.ndarray): The normal vector at the intersection point.
|
||||||
|
obj_idx (int): The index of the intersected object in the scene.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
bool: True if the intersection point is in shadow, False otherwise.
|
||||||
|
|
||||||
|
"""
|
||||||
|
to_light = normalize(L - intersection_point)
|
||||||
|
shadow_intersections = [
|
||||||
|
intersect(intersection_point + normal * 0.0001, to_light, obj_sh)
|
||||||
|
for k, obj_sh in enumerate(scene)
|
||||||
|
if k != obj_idx
|
||||||
|
]
|
||||||
|
return shadow_intersections and min(shadow_intersections) < np.inf
|
||||||
|
|
||||||
|
def compute_color(object_, intersection_point, normal, color, ray_origin):
|
||||||
|
"""Compute the color at the intersection point using shading techniques.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
object_ (dict): A dictionary representing the intersected object.
|
||||||
|
intersection_point (numpy.ndarray):
|
||||||
|
A 3D point representing the intersection point on the object.
|
||||||
|
normal (numpy.ndarray): The normal vector at the intersection point.
|
||||||
|
color (numpy.ndarray): The base color of the object.
|
||||||
|
ray_origin (numpy.ndarray): A 3D point representing the origin of the ray.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
tuple:
|
||||||
|
A tuple containing the intersected object, intersection point, normal,
|
||||||
|
and the computed color.
|
||||||
|
|
||||||
|
"""
|
||||||
|
to_light = normalize(L - intersection_point)
|
||||||
|
to_origin = normalize(ray_origin - intersection_point)
|
||||||
|
color_ray = AMBIENT
|
||||||
|
diffuse_intensity = object_.get("diffuse_c", DIFFUSE_C) * max(
|
||||||
|
np.dot(normal, to_light), 0
|
||||||
|
)
|
||||||
|
color_ray += diffuse_intensity * color
|
||||||
|
half_vector = normalize(to_light + to_origin)
|
||||||
|
specular_intensity = (
|
||||||
|
object_.get("specular_c", SPECULAR_C)
|
||||||
|
* max(np.dot(normal, half_vector), 0) ** SPECULAR_K
|
||||||
|
)
|
||||||
|
color_ray += specular_intensity * color_light
|
||||||
|
return object_, intersection_point, normal, color_ray
|
||||||
|
|
||||||
|
def add_sphere(position, radius, color):
|
||||||
|
"""Create a dictionary representing a sphere object.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
position (list or numpy.ndarray):
|
||||||
|
A 3D point representing the position of the sphere.
|
||||||
|
radius (float): The radius of the sphere.
|
||||||
|
color (list or numpy.ndarray): The color of the sphere.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
dict: A dictionary representing the sphere object.
|
||||||
|
|
||||||
|
"""
|
||||||
|
return {
|
||||||
|
"type": "sphere",
|
||||||
|
"position": np.array(position),
|
||||||
|
"radius": np.array(radius),
|
||||||
|
"color": np.array(color),
|
||||||
|
"reflection": 0.5,
|
||||||
|
}
|
||||||
|
|
||||||
|
def add_plane(position, normal):
|
||||||
|
"""Create a dictionary representing a plane object.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
position (list or numpy.ndarray):
|
||||||
|
A 3D point representing a point on the plane.
|
||||||
|
normal (list or numpy.ndarray):
|
||||||
|
A normalized 3D vector representing the normal of the plane.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
dict: A dictionary representing the plane object.
|
||||||
|
|
||||||
|
"""
|
||||||
|
return {
|
||||||
|
"type": "plane",
|
||||||
|
"position": np.array(position),
|
||||||
|
"normal": np.array(normal),
|
||||||
|
"color": lambda M: (
|
||||||
|
color_plane0
|
||||||
|
if (int(M[0] * 2) % 2) == (int(M[2] * 2) % 2)
|
||||||
|
else color_plane1
|
||||||
|
),
|
||||||
|
"diffuse_c": 0.75,
|
||||||
|
"specular_c": 0.5,
|
||||||
|
"reflection": 0.25,
|
||||||
|
}
|
||||||
|
|
||||||
|
scene = []
|
||||||
|
|
||||||
|
# List of objects.
|
||||||
color_plane0 = 1.0 * np.ones(3)
|
color_plane0 = 1.0 * np.ones(3)
|
||||||
color_plane1 = 0.0 * np.ones(3)
|
color_plane1 = 0.0 * np.ones(3)
|
||||||
scene = [make_plane([0.0, -0.5, 0.0], [0.0, 1.0, 0.0], color_plane0, color_plane1)]
|
scene.append(add_plane([0.0, -0.5, 0.0], [0.0, 1.0, 0.0]))
|
||||||
|
|
||||||
base_radius = 1 / np.sqrt(num_spheres) # Im więcej kul, tym mniejsze
|
base_radius = 1 / np.sqrt(num_spheres) # Im więcej kul, tym mniejsze
|
||||||
base_distance = 4.5 / num_spheres
|
base_distance = 4.5 / num_spheres
|
||||||
|
|
||||||
@ -60,87 +390,67 @@ def build_scene(num_spheres: int) -> list[SceneObject]:
|
|||||||
color = np.array([i / num_spheres, (num_spheres - i) / num_spheres, 0.5])
|
color = np.array([i / num_spheres, (num_spheres - i) / num_spheres, 0.5])
|
||||||
|
|
||||||
# Dodanie kuli do sceny
|
# Dodanie kuli do sceny
|
||||||
scene.append(make_sphere([x, y, z], base_radius, color))
|
scene.append(add_sphere([x, y, z], base_radius, color))
|
||||||
|
|
||||||
return scene
|
# Light position and color.
|
||||||
|
L = np.array([5.0, 5.0, -10.0])
|
||||||
|
color_light = np.ones(3)
|
||||||
|
|
||||||
|
# Default light and material parameters.
|
||||||
|
AMBIENT = 0.05
|
||||||
|
DIFFUSE_C = 1.0
|
||||||
|
SPECULAR_C = 1.0
|
||||||
|
SPECULAR_K = 50
|
||||||
|
|
||||||
def ray_trace(
|
DEPTH_MAX = 5 # Maximum number of light reflections.
|
||||||
num_spheres: int,
|
col = np.zeros(3) # Current color.
|
||||||
_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.
|
||||||
camera_target = np.array([0.0, 0.0, 0.0]) # Camera pointing to.
|
Q = 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))
|
||||||
|
|
||||||
aspect = float(image_width) / image_height
|
r = float(IMAGE_WIDTH) / IMAGE_HEIGHT
|
||||||
# Screen coordinates: x0, y0, x1, y1.
|
# Screen coordinates: x0, y0, x1, y1.
|
||||||
screen = (-1.0, -1.0 / aspect + 0.25, 1.0, 1.0 / aspect + 0.25)
|
S = (-1.0, -1.0 / r + 0.25, 1.0, 1.0 / r + 0.25)
|
||||||
|
|
||||||
render_time = time.time()
|
renderTime = time.time()
|
||||||
reflections = 0
|
reflections = 0
|
||||||
rays = 0
|
rays = 0
|
||||||
primary_rays = 0
|
initialRays = 0
|
||||||
# Loop through all pixels.
|
# Loop through all pixels.
|
||||||
for i, x in enumerate(np.linspace(screen[0], screen[2], image_width)):
|
for i, x in enumerate(np.linspace(S[0], S[2], IMAGE_WIDTH)):
|
||||||
if i % _PROGRESS_EVERY == 0:
|
if i % 10 == 0:
|
||||||
logger.info("%s %%", round(i / float(image_width) * 100, 2))
|
print(round(i / float(IMAGE_WIDTH) * 100, 2), "%")
|
||||||
for j, y in enumerate(np.linspace(screen[1], screen[3], image_height)):
|
for j, y in enumerate(np.linspace(S[1], S[3], IMAGE_HEIGHT)):
|
||||||
color[:] = 0
|
col[:] = 0
|
||||||
camera_target[:2] = (x, y)
|
Q[:2] = (x, y)
|
||||||
ray_origin = camera_origin
|
D = normalize(Q - camera_origin)
|
||||||
ray_direction = normalize(camera_target - camera_origin)
|
DEPTH = 0
|
||||||
depth = 0
|
rayO, rayD = camera_origin, D
|
||||||
reflection = 1.0
|
REFLECTION = 1.0
|
||||||
primary_rays += 1
|
initialRays += 1
|
||||||
# Loop through initial and secondary rays.
|
# Loop through initial and secondary rays.
|
||||||
while depth < DEPTH_MAX:
|
while DEPTH < DEPTH_MAX:
|
||||||
traced = trace_ray(scene, lighting, ray_origin, ray_direction)
|
traced = trace_ray(rayO, rayD)
|
||||||
rays += 1
|
rays += 1
|
||||||
if not traced:
|
if not traced:
|
||||||
break
|
break
|
||||||
reflections += 1
|
reflections += 1
|
||||||
obj, hit_point, hit_normal, color_ray = traced
|
obj, M, N, col_ray = traced
|
||||||
# Reflection: create a new ray.
|
# Reflection: create a new ray.
|
||||||
ray_origin = hit_point + hit_normal * SURFACE_OFFSET
|
rayO, rayD = M + N * 0.0001, normalize(rayD - 2 * np.dot(rayD, N) * N)
|
||||||
ray_direction = normalize(
|
DEPTH += 1
|
||||||
ray_direction - 2 * np.dot(ray_direction, hit_normal) * hit_normal
|
col += REFLECTION * col_ray
|
||||||
)
|
REFLECTION *= obj.get("reflection", 1.0)
|
||||||
depth += 1
|
img[IMAGE_HEIGHT - j - 1, i, :] = np.clip(col, 0, 1)
|
||||||
color += reflection * color_ray
|
renderTime = time.time() - renderTime
|
||||||
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)
|
||||||
logger.info(
|
print(
|
||||||
"Image saved as %s\nresolution: %sx%s\nrender time: %s s\nreflections: %s\n"
|
f"Image saved as {output_file}\n"
|
||||||
"rays (initial): %s\nrays (secondary): %s\nrays (total): %s",
|
f"resolution: {IMAGE_WIDTH}x{IMAGE_HEIGHT}\n"
|
||||||
output_file,
|
f"render time: {round(renderTime, 2)} s\n"
|
||||||
image_width,
|
f"reflections: {reflections}\n"
|
||||||
image_height,
|
f"rays (initial): {initialRays}\n"
|
||||||
round(render_time, 2),
|
f"rays (secondary): {rays - initialRays}\n"
|
||||||
reflections,
|
f"rays (total): {rays}"
|
||||||
primary_rays,
|
|
||||||
rays - primary_rays,
|
|
||||||
rays,
|
|
||||||
)
|
)
|
||||||
|
|||||||
@ -1 +0,0 @@
|
|||||||
"""Scene definitions, each exposing a `setup_scene(width, height, environment)`."""
|
|
||||||
@ -1,35 +1,14 @@
|
|||||||
"""The Cornell box: a closed room lit by a ceiling panel.
|
from sightpy import *
|
||||||
|
|
||||||
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,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def setup_scene(
|
# define materials to use
|
||||||
width: int = 400, height: int = 300, environment: str | None = None
|
def setup_scene(width=400, height=300, environment=None):
|
||||||
) -> Scene:
|
|
||||||
"""Build the Cornell box at `width` x `height`.
|
|
||||||
|
|
||||||
`environment` is accepted so every scene has one interface, and ignored:
|
Sc = Scene(ambient_color=rgb(0.00, 0.00, 0.00))
|
||||||
the box is closed, so no background is ever visible.
|
|
||||||
"""
|
|
||||||
del environment
|
|
||||||
|
|
||||||
scene = Scene(ambient_color=rgb(0.00, 0.00, 0.00))
|
angle = -0
|
||||||
|
|
||||||
scene.add_Camera(
|
Sc.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),
|
||||||
@ -44,10 +23,11 @@ def setup_scene(
|
|||||||
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
|
||||||
scene.add(
|
Sc.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),
|
||||||
@ -59,7 +39,7 @@ def setup_scene(
|
|||||||
importance_sampled=True,
|
importance_sampled=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
scene.add(
|
Sc.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),
|
||||||
@ -70,7 +50,7 @@ def setup_scene(
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
scene.add(
|
Sc.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),
|
||||||
@ -81,7 +61,7 @@ def setup_scene(
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
scene.add(
|
Sc.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),
|
||||||
@ -92,7 +72,7 @@ def setup_scene(
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
scene.add(
|
Sc.add(
|
||||||
Plane(
|
Plane(
|
||||||
material=white_diffuse,
|
material=white_diffuse,
|
||||||
center=vec3(555 / 2, 555, -555 / 2),
|
center=vec3(555 / 2, 555, -555 / 2),
|
||||||
@ -103,7 +83,7 @@ def setup_scene(
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
scene.add(
|
Sc.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),
|
||||||
@ -123,9 +103,9 @@ def setup_scene(
|
|||||||
shadow=False,
|
shadow=False,
|
||||||
)
|
)
|
||||||
cb.rotate(θ=15, u=vec3(0, 1, 0))
|
cb.rotate(θ=15, u=vec3(0, 1, 0))
|
||||||
scene.add(cb)
|
Sc.add(cb)
|
||||||
|
|
||||||
scene.add(
|
Sc.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),
|
||||||
@ -136,4 +116,4 @@ def setup_scene(
|
|||||||
importance_sampled=True,
|
importance_sampled=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
return scene
|
return Sc
|
||||||
|
|||||||
@ -1,22 +1,14 @@
|
|||||||
"""One soap bubble in front of a blurred backdrop.
|
from sightpy import *
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def setup_scene(
|
# define materials to use
|
||||||
width: int = 400, height: int = 300, environment: str = "lake.png"
|
def setup_scene(width=400, height=300, environment="lake.png"):
|
||||||
) -> Scene:
|
# Set Scene
|
||||||
"""Build the soap-bubble scene at `width` x `height` over `environment`."""
|
|
||||||
scene = Scene(ambient_color=rgb(0.01, 0.01, 0.01))
|
Sc = Scene(ambient_color=rgb(0.01, 0.01, 0.01))
|
||||||
|
|
||||||
angle = -np.pi * 0.5
|
angle = -np.pi * 0.5
|
||||||
scene.add_Camera(
|
Sc.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)),
|
||||||
@ -24,7 +16,7 @@ def setup_scene(
|
|||||||
)
|
)
|
||||||
|
|
||||||
soap_bubble = ThinFilmInterference(thickness=330, noise=60.0)
|
soap_bubble = ThinFilmInterference(thickness=330, noise=60.0)
|
||||||
scene.add(
|
Sc.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),
|
||||||
@ -34,6 +26,6 @@ def setup_scene(
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
scene.add_Background(environment, blur=10.0)
|
Sc.add_Background(environment, blur=10.0)
|
||||||
|
|
||||||
return scene
|
return Sc
|
||||||
|
|||||||
@ -1,17 +1,9 @@
|
|||||||
"""Three coloured glass spheres on a checkered floor, over a photo backdrop.
|
from sightpy import *
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def setup_scene(
|
# define materials to use
|
||||||
width: int = 400, height: int = 300, environment: str = "miramar.jpeg"
|
def setup_scene(width=400, height=300, environment="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
|
||||||
@ -28,19 +20,19 @@ def setup_scene(
|
|||||||
|
|
||||||
# Set Scene
|
# Set Scene
|
||||||
|
|
||||||
scene = Scene(ambient_color=rgb(0.05, 0.05, 0.05))
|
Sc = Scene(ambient_color=rgb(0.05, 0.05, 0.05))
|
||||||
|
|
||||||
angle = np.pi / 2 * 0.3
|
angle = np.pi / 2 * 0.3
|
||||||
scene.add_Camera(
|
Sc.add_Camera(
|
||||||
look_from=vec3(2.5 * np.sin(angle), 0.25, 2.5 * np.cos(angle) - 1.5),
|
look_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,
|
||||||
)
|
)
|
||||||
|
|
||||||
scene.add_DirectionalLight(Ldir=vec3(0.52, 0.45, -0.5), color=rgb(0.15, 0.15, 0.15))
|
Sc.add_DirectionalLight(Ldir=vec3(0.52, 0.45, -0.5), color=rgb(0.15, 0.15, 0.15))
|
||||||
|
|
||||||
scene.add(
|
Sc.add(
|
||||||
Sphere(
|
Sphere(
|
||||||
material=blue_glass,
|
material=blue_glass,
|
||||||
center=vec3(-1.2, 0.0, -1.5),
|
center=vec3(-1.2, 0.0, -1.5),
|
||||||
@ -49,7 +41,7 @@ def setup_scene(
|
|||||||
max_ray_depth=3,
|
max_ray_depth=3,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
scene.add(
|
Sc.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),
|
||||||
@ -58,7 +50,7 @@ def setup_scene(
|
|||||||
max_ray_depth=3,
|
max_ray_depth=3,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
scene.add(
|
Sc.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),
|
||||||
@ -68,7 +60,7 @@ def setup_scene(
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
scene.add(
|
Sc.add(
|
||||||
Plane(
|
Plane(
|
||||||
material=floor,
|
material=floor,
|
||||||
center=vec3(0, -0.5, -3.0),
|
center=vec3(0, -0.5, -3.0),
|
||||||
@ -81,6 +73,6 @@ def setup_scene(
|
|||||||
)
|
)
|
||||||
|
|
||||||
# see sightpy/backgrounds
|
# see sightpy/backgrounds
|
||||||
scene.add_Background(environment)
|
Sc.add_Background(environment)
|
||||||
|
|
||||||
return scene
|
return Sc
|
||||||
|
|||||||
@ -1,16 +1,8 @@
|
|||||||
"""A rotated block of green glass standing on a checkered floor.
|
from sightpy import *
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def setup_scene(
|
# define materials to use
|
||||||
width: int = 400, height: int = 300, environment: str = "stormydays.png"
|
def setup_scene(width=400, height=300, environment="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,
|
||||||
@ -20,17 +12,17 @@ def setup_scene(
|
|||||||
) # 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))
|
||||||
|
|
||||||
scene = Scene()
|
Sc = Scene()
|
||||||
scene.add_Camera(
|
Sc.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,
|
||||||
)
|
)
|
||||||
|
|
||||||
scene.add_DirectionalLight(Ldir=vec3(0.0, 0.5, 0.5), color=rgb(0.5, 0.5, 0.5))
|
Sc.add_DirectionalLight(Ldir=vec3(0.0, 0.5, 0.5), color=rgb(0.5, 0.5, 0.5))
|
||||||
|
|
||||||
scene.add(
|
Sc.add(
|
||||||
Plane(
|
Plane(
|
||||||
material=floor,
|
material=floor,
|
||||||
center=vec3(0, -0.5, -3.0),
|
center=vec3(0, -0.5, -3.0),
|
||||||
@ -52,9 +44,9 @@ def setup_scene(
|
|||||||
max_ray_depth=5,
|
max_ray_depth=5,
|
||||||
)
|
)
|
||||||
cb.rotate(θ=30, u=vec3(0, 1, 0))
|
cb.rotate(θ=30, u=vec3(0, 1, 0))
|
||||||
scene.add(cb)
|
Sc.add(cb)
|
||||||
|
|
||||||
# see sightpy/backgrounds
|
# see sightpy/backgrounds
|
||||||
scene.add_Background(environment)
|
Sc.add_Background(environment)
|
||||||
|
|
||||||
return scene
|
return Sc
|
||||||
|
|||||||
@ -1,17 +1,8 @@
|
|||||||
"""Two metal spheres -- gold and bluish -- on a checkered floor.
|
from sightpy import *
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def setup_scene(
|
# define materials to use
|
||||||
width: int = 400, height: int = 300, environment: str = "stormydays.png"
|
def setup_scene(width=400, height=300, environment="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),
|
||||||
@ -36,19 +27,19 @@ def setup_scene(
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Set Scene
|
# Set Scene
|
||||||
scene = Scene(ambient_color=rgb(0.05, 0.05, 0.05))
|
Sc = Scene(ambient_color=rgb(0.05, 0.05, 0.05))
|
||||||
|
|
||||||
angle = -np.pi / 2 * 0.3
|
angle = -np.pi / 2 * 0.3
|
||||||
scene.add_Camera(
|
Sc.add_Camera(
|
||||||
look_from=vec3(2.5 * np.sin(angle), 0.25, 2.5 * np.cos(angle) - 1.5),
|
look_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,
|
||||||
)
|
)
|
||||||
|
|
||||||
scene.add_DirectionalLight(Ldir=vec3(0.52, 0.45, -0.5), color=rgb(0.15, 0.15, 0.15))
|
Sc.add_DirectionalLight(Ldir=vec3(0.52, 0.45, -0.5), color=rgb(0.15, 0.15, 0.15))
|
||||||
|
|
||||||
scene.add(
|
Sc.add(
|
||||||
Sphere(
|
Sphere(
|
||||||
material=gold_metal,
|
material=gold_metal,
|
||||||
center=vec3(-0.75, 0.1, -3.0),
|
center=vec3(-0.75, 0.1, -3.0),
|
||||||
@ -56,7 +47,7 @@ def setup_scene(
|
|||||||
max_ray_depth=3,
|
max_ray_depth=3,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
scene.add(
|
Sc.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),
|
||||||
@ -65,7 +56,7 @@ def setup_scene(
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
scene.add(
|
Sc.add(
|
||||||
Plane(
|
Plane(
|
||||||
material=floor,
|
material=floor,
|
||||||
center=vec3(0, -0.5, -3.0),
|
center=vec3(0, -0.5, -3.0),
|
||||||
@ -78,6 +69,6 @@ def setup_scene(
|
|||||||
)
|
)
|
||||||
|
|
||||||
# see sightpy/backgrounds
|
# see sightpy/backgrounds
|
||||||
scene.add_Background(environment)
|
Sc.add_Background(environment)
|
||||||
|
|
||||||
return scene
|
return Sc
|
||||||
|
|||||||
22
Programming/TRAK/utils.py
Executable file → Normal file
22
Programming/TRAK/utils.py
Executable file → Normal file
@ -1,25 +1,17 @@
|
|||||||
#!/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: str) -> ConfigParser:
|
def load_config(config_path):
|
||||||
"""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: str) -> tuple[int, int]:
|
def parse_resolution(resolution):
|
||||||
"""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"))
|
||||||
except ValueError as err:
|
return width, height
|
||||||
msg = "Resolution must be in the format WIDTHxHEIGHT, e.g., 1920x1080."
|
except ValueError:
|
||||||
raise ValueError(msg) from err
|
raise ValueError(
|
||||||
return width, height
|
"Resolution must be in the format WIDTHxHEIGHT, e.g., 1920x1080."
|
||||||
|
)
|
||||||
|
|||||||
@ -5,15 +5,8 @@ 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 the notebook's **CIFAR-10 section only**. |
|
| `TWM_KerasIntro.py` | An `nbconvert` export of that notebook. Derived, not edited by hand. |
|
||||||
| `twm.py` | Prints the TensorFlow version the notebook will run against. |
|
| `twm.py` | Helper code used by the notebook. |
|
||||||
|
|
||||||
The notebook is the source of truth. The `.py` is kept because it makes that
|
The `.py` export is kept because it is what makes the notebook's code
|
||||||
section's code reviewable and diffable, but it is not a full export: it covers
|
reviewable and diffable; edit the notebook, then re-export.
|
||||||
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/`.
|
|
||||||
|
|||||||
@ -89,16 +89,10 @@
|
|||||||
"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",
|
||||||
@ -107,14 +101,9 @@
|
|||||||
") # 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() would need a logging handler configured to survive this file being\n",
|
"print(tf.__version__)"
|
||||||
"# exported and run as a script; sys.stdout.write shows the same text in a cell.\n",
|
|
||||||
"sys.stdout.write(f\"{tf.__version__}\\n\")"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -140,14 +129,13 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# The MNIST data is split between 60,000 28 x 28 pixel training images\n",
|
"# The MNIST data is split between 60,000 28 x 28 pixel training images and 10,000 28 x 28 pixel images\n",
|
||||||
"# 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",
|
||||||
"sys.stdout.write(f\"X_train shape {X_train.shape}\\n\")\n",
|
"print(\"X_train shape\", X_train.shape)\n",
|
||||||
"sys.stdout.write(f\"y_train shape {y_train.shape}\\n\")\n",
|
"print(\"y_train shape\", y_train.shape)\n",
|
||||||
"sys.stdout.write(f\"X_test shape {X_test.shape}\\n\")\n",
|
"print(\"X_test shape\", X_test.shape)\n",
|
||||||
"sys.stdout.write(f\"y_test shape {y_test.shape}\\n\")"
|
"print(\"y_test shape\", y_test.shape)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -174,28 +162,20 @@
|
|||||||
"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",
|
||||||
"\n",
|
"def visualize_classes(X, y):\n",
|
||||||
"def visualize_classes(images: np.ndarray, labels: np.ndarray) -> None:\n",
|
" for i in range(10):\n",
|
||||||
" \"\"\"Show ten samples of each class as one wide strip.\n",
|
" img_batch = X[y == i][0:10]\n",
|
||||||
"\n",
|
" img_batch = np.reshape(\n",
|
||||||
" The strips are collected in a list and concatenated once. Growing the\n",
|
" img_batch, (img_batch.shape[0] * img_batch.shape[1], img_batch.shape[2])\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(np.concatenate(strips, axis=1), cmap=\"gray\")\n",
|
" plt.imshow(img, cmap=\"gray\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"visualize_classes(X_train, y_train)"
|
"visualize_classes(X_train, y_train)"
|
||||||
@ -223,14 +203,12 @@
|
|||||||
"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: np.ndarray, fmt: str = \"g\") -> None:\n",
|
"def matprint(mat, fmt=\"g\"):\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 row in mat:\n",
|
" for x in mat:\n",
|
||||||
" for i, value in enumerate(row):\n",
|
" for i, y in enumerate(x):\n",
|
||||||
" # Two trailing spaces and no newline: this builds one line per row.\n",
|
" print((\"{:\" + str(col_maxes[i]) + fmt + \"}\").format(y), end=\" \")\n",
|
||||||
" sys.stdout.write((\"{:\" + str(col_maxes[i]) + fmt + \"} \").format(value))\n",
|
" print()\n",
|
||||||
" sys.stdout.write(\"\\n\")\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# now print!\n",
|
"# now print!\n",
|
||||||
@ -279,42 +257,44 @@
|
|||||||
},
|
},
|
||||||
"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(CLASS_COUNT)]\n",
|
"class_names = [str(clid) for clid in range(10)]\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def scatter(points: np.ndarray, colors: np.ndarray) -> None:\n",
|
"def scatter(x, colors):\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\", CLASS_COUNT))\n",
|
" palette = np.array(sns.color_palette(\"hls\", 10))\n",
|
||||||
"\n",
|
"\n",
|
||||||
" # We create a scatter plot.\n",
|
" # We create a scatter plot.\n",
|
||||||
" plt.figure(figsize=(8, 8))\n",
|
" f = plt.figure(figsize=(8, 8))\n",
|
||||||
" ax = plt.subplot(aspect=\"equal\")\n",
|
" ax = plt.subplot(aspect=\"equal\")\n",
|
||||||
" ax.scatter(points[:, 0], points[:, 1], lw=0, s=40, c=palette[colors.astype(\"int\")])\n",
|
" sc = ax.scatter(x[:, 0], x[:, 1], lw=0, s=40, c=palette[colors.astype(\"int\")])\n",
|
||||||
" plt.xlim(-25, 25)\n",
|
" plt.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",
|
||||||
" for i in range(CLASS_COUNT):\n",
|
" txts = []\n",
|
||||||
|
" for i in range(10):\n",
|
||||||
" # Position of each label.\n",
|
" # Position of each label.\n",
|
||||||
" xtext, ytext = np.median(points[colors == i, :], axis=0)\n",
|
" xtext, ytext = np.median(x[colors == i, :], axis=0)\n",
|
||||||
" txt = ax.text(xtext, ytext, class_names[i], fontsize=15)\n",
|
" txt = 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(features: np.ndarray, labels: np.ndarray) -> None:\n",
|
"def plot_tsne(X, y):\n",
|
||||||
" \"\"\"Project `features` to two dimensions with t-SNE and scatter them.\"\"\"\n",
|
" print(\"calculating tsne ...\")\n",
|
||||||
" sys.stdout.write(\"calculating tsne ...\\n\")\n",
|
" proj = TSNE(random_state=RS, learning_rate=200, init=\"random\").fit_transform(X)\n",
|
||||||
" proj = TSNE(random_state=RS, learning_rate=200, init=\"random\").fit_transform(\n",
|
" scatter(proj, y)"
|
||||||
" features\n",
|
|
||||||
" )\n",
|
|
||||||
" scatter(proj, labels)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -384,8 +364,8 @@
|
|||||||
")\n",
|
")\n",
|
||||||
"X_test /= 255\n",
|
"X_test /= 255\n",
|
||||||
"\n",
|
"\n",
|
||||||
"sys.stdout.write(f\"Training matrix shape {X_train.shape}\\n\")\n",
|
"print(\"Training matrix shape\", X_train.shape)\n",
|
||||||
"sys.stdout.write(f\"Testing matrix shape {X_test.shape}\\n\")"
|
"print(\"Testing matrix shape\", X_test.shape)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -467,8 +447,7 @@
|
|||||||
"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\n",
|
"# Each node will receive an element from each input vector and apply some weight and bias to it.\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",
|
||||||
@ -483,11 +462,10 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# An \"activation\" is a non-linear function applied to the output of the layer\n",
|
"# An \"activation\" is a non-linear function applied to the output of the layer above.\n",
|
||||||
"# above. It checks the new value of the node, and decides whether that\n",
|
"# It checks the new value of the node, and decides whether that artifical neuron has fired.\n",
|
||||||
"# artifical neuron has fired.\n",
|
"# The Rectified Linear Unit (ReLU) converts all negative inputs to nodes in the next layer to be zero.\n",
|
||||||
"# The Rectified Linear Unit (ReLU) converts all negative inputs to nodes in the\n",
|
"# Those inputs are then not considered to be fired.\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\"))"
|
||||||
@ -534,9 +512,8 @@
|
|||||||
"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\n",
|
"# However, instead of each of the 512-node receiving 784-inputs from the input image data,\n",
|
||||||
"# image data, they receive 512 inputs from the output of the first 512-node\n",
|
"# they receive 512 inputs from the output of the first 512-node layer.\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",
|
||||||
@ -560,10 +537,9 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# The final layer of 10 neurons in fully-connected to the previous 512-node\n",
|
"# The final layer of 10 neurons in fully-connected to the previous 512-node layer.\n",
|
||||||
"# layer. The final layer of a FCN should be equal to the number of desired\n",
|
"# The final layer of a FCN should be equal to the number of desired classes (10 in this case).\n",
|
||||||
"# classes (10 in this case).\n",
|
"model.add(Dense(10))"
|
||||||
"model.add(Dense(CLASS_COUNT))"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -574,8 +550,8 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# The \"softmax\" activation represents a probability distribution over K\n",
|
"# The \"softmax\" activation represents a probability distribution over K different possible outcomes.\n",
|
||||||
"# different possible outcomes. Its values are all non-negative and sum to 1.\n",
|
"# Its values are all non-negative and sum to 1.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"model.add(Activation(\"softmax\"))"
|
"model.add(Activation(\"softmax\"))"
|
||||||
]
|
]
|
||||||
@ -734,8 +710,8 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"score = model.evaluate(X_test, Y_test)\n",
|
"score = model.evaluate(X_test, Y_test)\n",
|
||||||
"sys.stdout.write(f\"Test score: {score[0]}\\n\")\n",
|
"print(\"Test score:\", score[0])\n",
|
||||||
"sys.stdout.write(f\"Test accuracy: {score[1]}\\n\")"
|
"print(\"Test accuracy:\", score[1])"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -747,24 +723,18 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def plot_confusion_matrix(\n",
|
"def plot_confusion_matrix(\n",
|
||||||
" cm: np.ndarray,\n",
|
" cm, classes, normalize=False, title=\"Confusion matrix\", cmap=plt.cm.Blues\n",
|
||||||
" classes: list[str],\n",
|
"):\n",
|
||||||
" *,\n",
|
" \"\"\"This function prints and plots the confusion matrix.\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",
|
||||||
" sys.stdout.write(\"Normalized confusion matrix\\n\")\n",
|
" print(\"Normalized confusion matrix\")\n",
|
||||||
" else:\n",
|
" else:\n",
|
||||||
" sys.stdout.write(\"Confusion matrix, without normalization\\n\")\n",
|
" print(\"Confusion matrix, without normalization\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
" sys.stdout.write(f\"{cm}\\n\")\n",
|
" print(cm)\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",
|
||||||
@ -786,17 +756,7 @@
|
|||||||
"\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()\n",
|
" plt.tight_layout()"
|
||||||
"\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"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -875,34 +835,29 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def show_samples(indices: np.ndarray, samples: Samples, *, count: int = 3) -> None:\n",
|
"def show_samples(indices, preds, images, labels, count=3, names=[]):\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(samples.scores[sample]))\n",
|
" pred_id = int(np.argmax(preds[sample]))\n",
|
||||||
" real_id = int(samples.labels[sample])\n",
|
" real_id = int(labels[sample])\n",
|
||||||
" pred_score = samples.scores[sample][pred_id]\n",
|
" pred_score = preds[sample][pred_id]\n",
|
||||||
" real_score = samples.scores[sample][real_id]\n",
|
" real_score = preds[sample][real_id]\n",
|
||||||
" plt.subplot(count, count, i + 1)\n",
|
" plt.subplot(count, count, i + 1)\n",
|
||||||
" plt.imshow(\n",
|
" plt.imshow(images[sample].reshape(28, 28), cmap=\"gray\", interpolation=\"none\")\n",
|
||||||
" samples.images[sample].reshape(28, 28), cmap=\"gray\", interpolation=\"none\"\n",
|
|
||||||
" )\n",
|
|
||||||
" plt.axis(\"off\")\n",
|
" plt.axis(\"off\")\n",
|
||||||
" if samples.names:\n",
|
" if len(names) > 0:\n",
|
||||||
" predicted_label: str | int = samples.names[pred_id]\n",
|
" plt.title(\n",
|
||||||
" real_label: str | int = samples.names[real_id]\n",
|
" f\"P: {names[pred_id]} ({pred_score:.2f})\\nE: {names[real_id]} ({real_score:.2f})\"\n",
|
||||||
|
" )\n",
|
||||||
" else:\n",
|
" else:\n",
|
||||||
" predicted_label = pred_id\n",
|
" plt.title(\n",
|
||||||
" real_label = real_id\n",
|
" f\"P: {pred_id} ({pred_score:.2f})\\nE: {real_id} ({real_score:.2f})\"\n",
|
||||||
" plt.title(\n",
|
" )\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, Samples(predict, X_test, y_test), count=5)"
|
"show_samples(correct_indices, predict, X_test, y_test, 5)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -927,7 +882,7 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"show_samples(incorrect_indices, Samples(predict, X_test, y_test), count=5)"
|
"show_samples(incorrect_indices, predict, X_test, y_test, 5)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -1084,8 +1039,7 @@
|
|||||||
"outputs": [],
|
"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\n",
|
"# Except we do not flatten each image into a 784-length vector because we want to perform convolutions first\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",
|
||||||
@ -1100,8 +1054,8 @@
|
|||||||
")\n",
|
")\n",
|
||||||
"X_test /= 255\n",
|
"X_test /= 255\n",
|
||||||
"\n",
|
"\n",
|
||||||
"sys.stdout.write(f\"Training matrix shape {X_train.shape}\\n\")\n",
|
"print(\"Training matrix shape\", X_train.shape)\n",
|
||||||
"sys.stdout.write(f\"Testing matrix shape {X_test.shape}\\n\")"
|
"print(\"Testing matrix shape\", X_test.shape)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -1213,9 +1167,8 @@
|
|||||||
"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\n",
|
"# Besides loss function considerations as before, this method actually results in significant memory savings\n",
|
||||||
"# in significant memory savings because we are actually LOADING the data into\n",
|
"# because we are actually LOADING the data into the network in batches before processing each batch\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",
|
||||||
@ -1264,8 +1217,8 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"score = model.evaluate(X_test, Y_test)\n",
|
"score = model.evaluate(X_test, Y_test)\n",
|
||||||
"sys.stdout.write(f\"Test score: {score[0]}\\n\")\n",
|
"print(\"Test score:\", score[0])\n",
|
||||||
"sys.stdout.write(f\"Test accuracy: {score[1]}\\n\")"
|
"print(\"Test accuracy:\", score[1])"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -1318,7 +1271,7 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"show_samples(correct_indices, Samples(predict, X_test, y_test), count=5)"
|
"show_samples(correct_indices, predict, X_test, y_test, 5)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -1334,7 +1287,7 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"show_samples(incorrect_indices, Samples(predict, X_test, y_test), count=5)"
|
"show_samples(incorrect_indices, predict, X_test, y_test, 5)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -1356,16 +1309,15 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def visualize2(\n",
|
"def visualize2(model, layer, img, r, c):\n",
|
||||||
" model: Sequential, layer: object, img: np.ndarray, r: int, c: int\n",
|
" from keras import Model\n",
|
||||||
") -> None:\n",
|
"\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",
|
||||||
" feature_model = Model(inputs=model.inputs, outputs=outputs)\n",
|
" model = Model(inputs=model.inputs, outputs=outputs)\n",
|
||||||
" # get feature map for first hidden layer\n",
|
" # get feature map for first hidden layer\n",
|
||||||
" feature_maps = feature_model.predict(img)\n",
|
" feature_maps = model.predict(img)\n",
|
||||||
" for fmap in feature_maps:\n",
|
" 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",
|
||||||
@ -1457,34 +1409,31 @@
|
|||||||
"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(\n",
|
"def get_mnist(digits):\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.isin(y_train, digits).ravel()\n",
|
" train_ids = np.in1d(y_train, digits)\n",
|
||||||
" test_ids = np.isin(y_test, digits).ravel()\n",
|
" test_ids = np.in1d(y_test, digits)\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"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -1496,8 +1445,7 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# Preparing the base model\n",
|
"# Preparing the base model\n",
|
||||||
"def prepare_model(input_shape: tuple[int, ...], class_count: int) -> Sequential:\n",
|
"def prepare_model(input_shape, class_count):\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",
|
||||||
@ -1537,11 +1485,12 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# One-hot encoding of non-consecutive labels\n",
|
"# One-hot encoding of non-consecutive labels\n",
|
||||||
"def one_hot(labels: np.ndarray) -> np.ndarray:\n",
|
"def one_hot(labels):\n",
|
||||||
" \"\"\"One-hot encode `labels`, which need not be 0..n-1.\"\"\"\n",
|
" from sklearn.preprocessing import OneHotEncoder\n",
|
||||||
|
"\n",
|
||||||
" encoder = OneHotEncoder(categories=\"auto\")\n",
|
" encoder = OneHotEncoder(categories=\"auto\")\n",
|
||||||
" column = labels.reshape(-1, 1)\n",
|
" l = labels.reshape(-1, 1)\n",
|
||||||
" output = encoder.fit_transform(column)\n",
|
" output = encoder.fit_transform(l)\n",
|
||||||
" return output.toarray()"
|
" return output.toarray()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@ -1553,25 +1502,23 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def test_model(\n",
|
"def test_model(model, X_test, Y_test, y_test, digits):\n",
|
||||||
" model: Sequential,\n",
|
" score = model.evaluate(X_test, Y_test)\n",
|
||||||
" x_test: np.ndarray,\n",
|
" print(\"Test score:\", score[0])\n",
|
||||||
" y_test_onehot: np.ndarray,\n",
|
" print(\"Test accuracy:\", score[1])\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",
|
||||||
@ -1701,10 +1648,7 @@
|
|||||||
"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(\n",
|
"def extract_layers(main_model, starting_layer_ix, ending_layer_ix):\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",
|
||||||
@ -1948,50 +1892,46 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# The scheme is spelled out at each use site rather than folded into this\n",
|
"import os\n",
|
||||||
"# constant, so that the URL handed to urlopen is visibly https and nothing\n",
|
"import urllib\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(\n",
|
"def download_and_load(class_names, test_split=0.2, max_items_per_class=10000):\n",
|
||||||
" class_names: list[str],\n",
|
" root = \"data\"\n",
|
||||||
" test_split: float = 0.2,\n",
|
" if not os.path.exists(root):\n",
|
||||||
" max_items_per_class: int = 10000,\n",
|
" os.makedirs(root)\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",
|
||||||
" sys.stdout.write(\"downloading ...\\n\")\n",
|
" print(\"downloading ...\")\n",
|
||||||
|
" base = \"https://storage.googleapis.com/quickdraw_dataset/full/numpy_bitmap/\"\n",
|
||||||
" for c in class_names:\n",
|
" for c in class_names:\n",
|
||||||
" cc = c.replace(\"_\", \"%20\")\n",
|
" cc = c.replace(\"_\", \"%20\")\n",
|
||||||
" path = f\"https://{QUICKDRAW_HOST}/{cc}.npy\"\n",
|
" path = base + cc + \".npy\"\n",
|
||||||
" sys.stdout.write(f\"{path}\\n\")\n",
|
" print(path)\n",
|
||||||
" destination = root / f\"{cc}.npy\"\n",
|
" if not os.path.exists(f\"{root}/{cc}.npy\"):\n",
|
||||||
" if not destination.exists():\n",
|
" urllib.request.urlretrieve(path, f\"{root}/{cc}.npy\")\n",
|
||||||
" with urllib.request.urlopen(path) as response:\n",
|
|
||||||
" destination.write_bytes(response.read())\n",
|
|
||||||
" else:\n",
|
" else:\n",
|
||||||
" sys.stdout.write(\"Already downloaded\\n\")\n",
|
" print(\"Already downloaded\")\n",
|
||||||
" sys.stdout.write(\"loading ...\\n\")\n",
|
" print(\"loading ...\")\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, name in enumerate(class_names):\n",
|
" for idx, file in enumerate(class_names):\n",
|
||||||
" quoted = name.replace(\"_\", \"%20\")\n",
|
" file = file.replace(\"_\", \"%20\")\n",
|
||||||
" data = np.load(root / f\"{quoted}.npy\")\n",
|
" data = np.load(f\"{root}/{file}.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.default_rng().permutation(y.shape[0])\n",
|
" permutation = np.random.permutation(y.shape[0])\n",
|
||||||
" x = x[permutation, :]\n",
|
" x = x[permutation, :]\n",
|
||||||
" y = y[permutation]\n",
|
" y = y[permutation]\n",
|
||||||
"\n",
|
"\n",
|
||||||
@ -2007,8 +1947,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",
|
||||||
" sys.stdout.write(f\"Training Data : {x_train.shape[0]}\\n\")\n",
|
" print(\"Training Data : \", x_train.shape[0])\n",
|
||||||
" sys.stdout.write(f\"Testing Data : {x_test.shape[0]}\\n\")\n",
|
" print(\"Testing Data : \", x_test.shape[0])\n",
|
||||||
" return x_train, y_train, x_test, y_test"
|
" return x_train, y_train, x_test, y_test"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@ -2037,7 +1977,9 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"all_class_names = Path(\"categories.txt\").read_text().splitlines()\n",
|
"with open(\"categories.txt\") as f:\n",
|
||||||
|
" all_class_names = f.readlines()\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"random.seed(RANDOM_SEED)\n",
|
"random.seed(RANDOM_SEED)\n",
|
||||||
"\n",
|
"\n",
|
||||||
@ -2048,11 +1990,10 @@
|
|||||||
"# 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",
|
||||||
"# The lab also suggests a deliberately hard fixed set instead of a random one:\n",
|
"# you can also try those \"hard\" classes instead\n",
|
||||||
"# wheel, pizza, smiley_face, apple, potato, basketball, soccer_ball, brain,\n",
|
"# class_names = ['wheel', 'pizza', 'smiley_face', 'apple', 'potato', 'basketball', 'soccer_ball', 'brain', 'clock', 'circle']\n",
|
||||||
"# clock and circle.\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"sys.stdout.write(f\"{class_names}\\n\")\n",
|
"print(class_names)\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",
|
||||||
@ -2184,8 +2125,8 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"score = model.evaluate(X_test, Y_test)\n",
|
"score = model.evaluate(X_test, Y_test)\n",
|
||||||
"sys.stdout.write(f\"Test score: {score[0]}\\n\")\n",
|
"print(\"Test score:\", score[0])\n",
|
||||||
"sys.stdout.write(f\"Test accuracy: {score[1]}\\n\")"
|
"print(\"Test accuracy:\", score[1])"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -2225,7 +2166,7 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"show_samples(correct_indices, Samples(predicted, X_test, y_test, class_names), count=5)"
|
"show_samples(correct_indices, predicted, X_test, y_test, 5, class_names)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -2236,9 +2177,7 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"show_samples(\n",
|
"show_samples(incorrect_indices, predicted, X_test, y_test, 5, class_names)"
|
||||||
" incorrect_indices, Samples(predicted, X_test, y_test, class_names), count=5\n",
|
|
||||||
")"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -2286,8 +2225,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",
|
||||||
"sys.stdout.write(f\"Training matrix shape {X_train.shape} {y_train.shape}\\n\")\n",
|
"print(\"Training matrix shape\", X_train.shape, y_train.shape)\n",
|
||||||
"sys.stdout.write(f\"Testing matrix shape {X_test.shape} {y_test.shape}\\n\")\n",
|
"print(\"Testing matrix shape\", X_test.shape, y_test.shape)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# one-hot format classes\n",
|
"# one-hot format classes\n",
|
||||||
"\n",
|
"\n",
|
||||||
@ -2332,22 +2271,23 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"strips = []\n",
|
"for i in range(10):\n",
|
||||||
"for class_id in range(CLASS_COUNT):\n",
|
" img_batch = X_train[y_train == i][0:10]\n",
|
||||||
" img_batch = X_train[y_train == class_id][0:10]\n",
|
" img_batch = np.reshape(\n",
|
||||||
" strips.append(\n",
|
" img_batch,\n",
|
||||||
" np.reshape(\n",
|
" (\n",
|
||||||
" img_batch,\n",
|
" img_batch.shape[0] * img_batch.shape[1],\n",
|
||||||
" (\n",
|
" img_batch.shape[2],\n",
|
||||||
" img_batch.shape[0] * img_batch.shape[1],\n",
|
" img_batch.shape[3],\n",
|
||||||
" img_batch.shape[2],\n",
|
" ),\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(np.concatenate(strips, axis=1), cmap=\"gray\")"
|
"plt.imshow(img, cmap=\"gray\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -2370,8 +2310,7 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def generate_model() -> Sequential:\n",
|
"def generate_model():\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",
|
||||||
@ -2396,8 +2335,7 @@
|
|||||||
" return model\n",
|
" return model\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def generate_model_default() -> Sequential:\n",
|
"def generate_model_default():\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",
|
||||||
@ -2422,8 +2360,7 @@
|
|||||||
" return model\n",
|
" return model\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def generate_model_gemini() -> Sequential:\n",
|
"def generate_model_gemini():\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",
|
||||||
@ -2449,8 +2386,7 @@
|
|||||||
" return model\n",
|
" return model\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def generate_model_chat() -> Sequential:\n",
|
"def generate_model_chat():\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",
|
||||||
@ -2594,14 +2530,14 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"for trained in models:\n",
|
"for model in models:\n",
|
||||||
" score = trained.evaluate(X_test, Y_test)\n",
|
" score = model.evaluate(X_test, Y_test)\n",
|
||||||
" sys.stdout.write(f\"Test score: {score[0]}\\n\")\n",
|
" print(\"Test score:\", score[0])\n",
|
||||||
" sys.stdout.write(f\"Test accuracy: {score[1]}\\n\")\n",
|
" print(\"Test accuracy:\", score[1])\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 = trained.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",
|
||||||
" # Check which items we got right / wrong\n",
|
" # Check which items we got right / wrong\n",
|
||||||
@ -2611,7 +2547,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(CLASS_COUNT)]\n",
|
" class_names = [str(i) for i in range(10)]\n",
|
||||||
"\n",
|
"\n",
|
||||||
" # Plot non-normalized confusion matrix\n",
|
" # Plot non-normalized confusion matrix\n",
|
||||||
" plt.figure()\n",
|
" plt.figure()\n",
|
||||||
@ -2633,27 +2569,24 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def show_samples_rgb(indices: np.ndarray, samples: Samples, *, count: int = 3) -> None:\n",
|
"def show_samples_rgb(indices, preds, images, labels, count=3, names=[]):\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(samples.scores[sample]))\n",
|
" pred_id = int(np.argmax(preds[sample]))\n",
|
||||||
" real_id = int(samples.labels[sample])\n",
|
" real_id = int(labels[sample])\n",
|
||||||
" pred_score = samples.scores[sample][pred_id]\n",
|
" pred_score = preds[sample][pred_id]\n",
|
||||||
" real_score = samples.scores[sample][real_id]\n",
|
" real_score = preds[sample][real_id]\n",
|
||||||
" plt.subplot(count, count, i + 1)\n",
|
" plt.subplot(count, count, i + 1)\n",
|
||||||
" plt.imshow(samples.images[sample], interpolation=\"none\")\n",
|
" plt.imshow(images[sample], interpolation=\"none\")\n",
|
||||||
" plt.axis(\"off\")\n",
|
" plt.axis(\"off\")\n",
|
||||||
" if samples.names:\n",
|
" if len(names) > 0:\n",
|
||||||
" predicted_label: str | int = samples.names[pred_id]\n",
|
" plt.title(\n",
|
||||||
" real_label: str | int = samples.names[real_id]\n",
|
" f\"P: {names[pred_id]} ({pred_score:.2f})\\nE: {names[real_id]} ({real_score:.2f})\"\n",
|
||||||
|
" )\n",
|
||||||
" else:\n",
|
" else:\n",
|
||||||
" predicted_label = pred_id\n",
|
" plt.title(\n",
|
||||||
" real_label = real_id\n",
|
" f\"P: {pred_id} ({pred_score:.2f})\\nE: {real_id} ({real_score:.2f})\"\n",
|
||||||
" plt.title(\n",
|
" )\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()"
|
||||||
]
|
]
|
||||||
@ -2679,9 +2612,7 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"show_samples_rgb(\n",
|
"show_samples_rgb(correct_indices, predicted, X_test, y_test, 5, cifar_names)"
|
||||||
" correct_indices, Samples(predicted, X_test, y_test, cifar_names), count=5\n",
|
|
||||||
")"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -2705,9 +2636,7 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"show_samples_rgb(\n",
|
"show_samples_rgb(incorrect_indices, predicted, X_test, y_test, 5, cifar_names)"
|
||||||
" incorrect_indices, Samples(predicted, X_test, y_test, cifar_names), count=5\n",
|
|
||||||
")"
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
|||||||
230
Programming/twm_4/TWM_KerasIntro.py
Executable file → Normal file
230
Programming/twm_4/TWM_KerasIntro.py
Executable file → Normal file
@ -1,24 +1,25 @@
|
|||||||
#!/usr/bin/env python3
|
# # CIFAR-10
|
||||||
"""CIFAR-10 half of the lab notebook, exported so the code can be diffed.
|
|
||||||
|
|
||||||
Four CNN variants are built and only `model_chat` is trained, then evaluated
|
# ## Ładowanie zbioru danych
|
||||||
with a confusion matrix and sample grids of its right and wrong answers.
|
|
||||||
|
|
||||||
Needs a GPU: the script exits early without one, exactly as the notebook does.
|
# In[ ]:
|
||||||
`print` is `sys.stdout.write` here so the output is identical to the notebook's
|
import sys
|
||||||
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,
|
||||||
@ -35,59 +36,20 @@ 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: np.ndarray,
|
cm, classes, normalize=False, title="Confusion matrix", cmap=plt.cm.Blues
|
||||||
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]
|
||||||
sys.stdout.write("Normalized confusion matrix\n")
|
print("Normalized confusion matrix")
|
||||||
else:
|
else:
|
||||||
sys.stdout.write("Confusion matrix, without normalization\n")
|
print("Confusion matrix, without normalization")
|
||||||
|
|
||||||
sys.stdout.write(f"{cm}\n")
|
print(cm)
|
||||||
|
|
||||||
plt.imshow(cm, interpolation="nearest", cmap=cmap)
|
plt.imshow(cm, interpolation="nearest", cmap=cmap)
|
||||||
plt.title(title)
|
plt.title(title)
|
||||||
@ -125,13 +87,15 @@ 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]
|
||||||
|
|
||||||
sys.stdout.write(f"Training matrix shape {X_train.shape} {y_train.shape}\n")
|
print("Training matrix shape", X_train.shape, y_train.shape)
|
||||||
sys.stdout.write(f"Testing matrix shape {X_test.shape} {y_test.shape}\n")
|
print("Testing matrix shape", X_test.shape, y_test.shape)
|
||||||
|
|
||||||
# one-hot format classes
|
# one-hot format classes
|
||||||
|
|
||||||
Y_train = to_categorical(y_train, NUM_CLASSES)
|
nb_classes = 10
|
||||||
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",
|
||||||
@ -149,23 +113,23 @@ cifar_names = [
|
|||||||
|
|
||||||
# ## Podgląd zbioru treningowego
|
# ## Podgląd zbioru treningowego
|
||||||
|
|
||||||
# Ten samples of each class, stacked into one wide strip. Built as a list and
|
# In[ ]:
|
||||||
# concatenated once: growing `img` in place only bound it in the loop's `else`
|
|
||||||
# branch, which reads as a use-before-assignment and is what ruff flagged.
|
|
||||||
strips = []
|
for i in range(10):
|
||||||
for class_id in range(NUM_CLASSES):
|
img_batch = X_train[y_train == i][0:10]
|
||||||
img_batch = X_train[y_train == class_id][0:10]
|
img_batch = np.reshape(
|
||||||
strips.append(
|
img_batch,
|
||||||
np.reshape(
|
(
|
||||||
img_batch,
|
img_batch.shape[0] * img_batch.shape[1],
|
||||||
(
|
img_batch.shape[2],
|
||||||
img_batch.shape[0] * img_batch.shape[1],
|
img_batch.shape[3],
|
||||||
img_batch.shape[2],
|
),
|
||||||
img_batch.shape[3],
|
|
||||||
),
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
img = np.concatenate(strips, axis=1)
|
if i > 0:
|
||||||
|
img = np.concatenate([img, img_batch], axis=1)
|
||||||
|
else:
|
||||||
|
img = img_batch
|
||||||
plt.figure(figsize=(10, 20))
|
plt.figure(figsize=(10, 20))
|
||||||
plt.axis("off")
|
plt.axis("off")
|
||||||
plt.imshow(img, cmap="gray")
|
plt.imshow(img, cmap="gray")
|
||||||
@ -173,9 +137,10 @@ plt.imshow(img, cmap="gray")
|
|||||||
|
|
||||||
# ## Przygotowanie modelu
|
# ## Przygotowanie modelu
|
||||||
|
|
||||||
|
# In[ ]:
|
||||||
|
|
||||||
def generate_model() -> Sequential:
|
|
||||||
"""Build the minimal variant: one conv layer straight into the classifier."""
|
def generate_model():
|
||||||
model = Sequential() # Linear stacking of layers
|
model = Sequential() # Linear stacking of layers
|
||||||
|
|
||||||
# Convolution Layer 1
|
# Convolution Layer 1
|
||||||
@ -189,7 +154,7 @@ def generate_model() -> Sequential:
|
|||||||
# ...
|
# ...
|
||||||
|
|
||||||
# Fully Connected Layer
|
# Fully Connected Layer
|
||||||
model.add(Dense(NUM_CLASSES)) # final 10 FC nodes
|
model.add(Dense(10)) # final 10 FC nodes
|
||||||
model.add(Activation("softmax")) # softmax activation
|
model.add(Activation("softmax")) # softmax activation
|
||||||
|
|
||||||
model.summary()
|
model.summary()
|
||||||
@ -200,8 +165,7 @@ def generate_model() -> Sequential:
|
|||||||
return model
|
return model
|
||||||
|
|
||||||
|
|
||||||
def generate_model_default() -> Sequential:
|
def generate_model_default():
|
||||||
"""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
|
||||||
@ -215,7 +179,7 @@ def generate_model_default() -> Sequential:
|
|||||||
# ...
|
# ...
|
||||||
|
|
||||||
# Fully Connected Layer
|
# Fully Connected Layer
|
||||||
model.add(Dense(NUM_CLASSES)) # final 10 FC nodes
|
model.add(Dense(10)) # final 10 FC nodes
|
||||||
model.add(Activation("softmax")) # softmax activation
|
model.add(Activation("softmax")) # softmax activation
|
||||||
|
|
||||||
model.summary()
|
model.summary()
|
||||||
@ -226,8 +190,7 @@ def generate_model_default() -> Sequential:
|
|||||||
return model
|
return model
|
||||||
|
|
||||||
|
|
||||||
def generate_model_gemini() -> Sequential:
|
def generate_model_gemini():
|
||||||
"""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
|
||||||
@ -241,7 +204,7 @@ def generate_model_gemini() -> Sequential:
|
|||||||
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(NUM_CLASSES, activation="softmax"))
|
model.add(Dense(10, activation="softmax"))
|
||||||
|
|
||||||
# Model Compilation
|
# Model Compilation
|
||||||
model.compile(
|
model.compile(
|
||||||
@ -253,11 +216,7 @@ def generate_model_gemini() -> Sequential:
|
|||||||
return model
|
return model
|
||||||
|
|
||||||
|
|
||||||
def generate_model_chat() -> Sequential:
|
def generate_model_chat():
|
||||||
"""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
|
||||||
@ -292,7 +251,7 @@ def generate_model_chat() -> Sequential:
|
|||||||
model.add(Dropout(0.6))
|
model.add(Dropout(0.6))
|
||||||
|
|
||||||
# Output Layer
|
# Output Layer
|
||||||
model.add(Dense(NUM_CLASSES)) # final 10 FC nodes
|
model.add(Dense(10)) # final 10 FC nodes
|
||||||
model.add(Activation("softmax")) # softmax activation
|
model.add(Activation("softmax")) # softmax activation
|
||||||
|
|
||||||
model.summary()
|
model.summary()
|
||||||
@ -304,6 +263,9 @@ def generate_model_chat() -> Sequential:
|
|||||||
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()
|
||||||
@ -313,6 +275,9 @@ 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,
|
||||||
@ -322,35 +287,38 @@ gen = ImageDataGenerator(
|
|||||||
validation_split=0.2,
|
validation_split=0.2,
|
||||||
)
|
)
|
||||||
|
|
||||||
train_generator = gen.flow(X_train, Y_train, batch_size=BATCH_SIZE, subset="training")
|
train_generator = gen.flow(X_train, Y_train, batch_size=128, subset="training")
|
||||||
valid_generator = gen.flow(X_train, Y_train, batch_size=BATCH_SIZE, subset="validation")
|
valid_generator = gen.flow(X_train, Y_train, batch_size=128, subset="validation")
|
||||||
|
|
||||||
|
|
||||||
|
# In[ ]:
|
||||||
|
|
||||||
|
|
||||||
# Max 20 epoch
|
# Max 20 epoch
|
||||||
for trained in models:
|
for model in models:
|
||||||
trained.fit(
|
model.fit(
|
||||||
train_generator,
|
train_generator,
|
||||||
steps_per_epoch=TRAIN_IMAGES // BATCH_SIZE,
|
steps_per_epoch=40000 // 128,
|
||||||
epochs=EPOCHS,
|
epochs=20,
|
||||||
verbose=1,
|
verbose=1,
|
||||||
validation_data=valid_generator,
|
validation_data=valid_generator,
|
||||||
validation_steps=VALID_IMAGES // BATCH_SIZE,
|
validation_steps=10000 // 128,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
# ## Test
|
# ## Test
|
||||||
|
|
||||||
for evaluated in models:
|
# In[ ]:
|
||||||
score = evaluated.evaluate(X_test, Y_test)
|
|
||||||
sys.stdout.write(f"Test score: {score[0]}\n")
|
for model in models:
|
||||||
sys.stdout.write(f"Test accuracy: {score[1]}\n")
|
score = model.evaluate(X_test, Y_test)
|
||||||
|
print("Test score:", score[0])
|
||||||
|
print("Test accuracy:", score[1])
|
||||||
|
|
||||||
# The predict_classes function outputs the highest probability class
|
# 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 = evaluated.predict(X_test)
|
predicted = model.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]
|
||||||
@ -359,7 +327,7 @@ for evaluated 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(NUM_CLASSES)]
|
class_names = [str(i) for i in range(10)]
|
||||||
|
|
||||||
# Plot non-normalized confusion matrix
|
# Plot non-normalized confusion matrix
|
||||||
plt.figure()
|
plt.figure()
|
||||||
@ -370,38 +338,42 @@ for evaluated in models:
|
|||||||
plt.show()
|
plt.show()
|
||||||
|
|
||||||
|
|
||||||
def show_samples_rgb(
|
# In[ ]:
|
||||||
indices: np.ndarray, results: Predictions, *, count: int = 3
|
|
||||||
) -> None:
|
|
||||||
"""Plot a `count` x `count` grid of samples, titled predicted vs expected."""
|
def show_samples_rgb(indices, preds, images, labels, count=3, names=[]):
|
||||||
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(results.scores[sample]))
|
pred_id = int(np.argmax(preds[sample]))
|
||||||
real_id = int(results.labels[sample])
|
real_id = int(labels[sample])
|
||||||
pred_score = results.scores[sample][pred_id]
|
pred_score = preds[sample][pred_id]
|
||||||
real_score = results.scores[sample][real_id]
|
real_score = preds[sample][real_id]
|
||||||
plt.subplot(count, count, i + 1)
|
plt.subplot(count, count, i + 1)
|
||||||
plt.imshow(results.images[sample], interpolation="none")
|
plt.imshow(images[sample], interpolation="none")
|
||||||
plt.axis("off")
|
plt.axis("off")
|
||||||
if results.names:
|
if len(names) > 0:
|
||||||
predicted_label: str | int = results.names[pred_id]
|
plt.title(
|
||||||
real_label: str | int = results.names[real_id]
|
f"P: {names[pred_id]} ({pred_score:.2f})\nE: {names[real_id]} ({real_score:.2f})"
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
predicted_label = pred_id
|
plt.title(
|
||||||
real_label = real_id
|
f"P: {pred_id} ({pred_score:.2f})\nE: {real_id} ({real_score:.2f})"
|
||||||
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
|
||||||
|
|
||||||
show_samples_rgb(correct_indices, results, count=5)
|
# In[ ]:
|
||||||
|
|
||||||
|
|
||||||
|
show_samples_rgb(correct_indices, predicted, X_test, y_test, 5, cifar_names)
|
||||||
|
|
||||||
|
|
||||||
# ## Błędne klasyfikacje
|
# ## Błędne klasyfikacje
|
||||||
|
|
||||||
show_samples_rgb(incorrect_indices, results, count=5)
|
# In[ ]:
|
||||||
|
|
||||||
|
|
||||||
|
show_samples_rgb(incorrect_indices, predicted, X_test, y_test, 5, cifar_names)
|
||||||
|
|||||||
7
Programming/twm_4/twm.py
Executable file → Normal file
7
Programming/twm_4/twm.py
Executable file → Normal file
@ -1,8 +1,3 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""Smoke check: report which TensorFlow the notebook will actually run against."""
|
|
||||||
|
|
||||||
import sys
|
|
||||||
|
|
||||||
import tensorflow as tf
|
import tensorflow as tf
|
||||||
|
|
||||||
sys.stdout.write(f"{tf.__version__}\n")
|
print(tf.__version__)
|
||||||
|
|||||||
@ -32,43 +32,31 @@ own docs and the rest of this fleet carry. A test asserts by raising.
|
|||||||
|---|---|
|
|---|---|
|
||||||
| Baseline, before any of this | 9,281 |
|
| 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** | **423** |
|
| **Now** | **1,183** |
|
||||||
|
|
||||||
Courses at zero: `WDWR`, `SPD`, `MOM`, `ECRYPT`, `ECRYPT_PROJECT`, `ECOTE`,
|
Courses at zero: `WDWR`, `SPD`, `MOM`, `ECRYPT`, `ECRYPT_PROJECT`, `ECOTE`,
|
||||||
`NLP`, `EARIN`, `PORR`, `TRAK`, `twm_4`. What is left, by course:
|
`NLP`, `EARIN`, `PORR`. What is left, by course:
|
||||||
|
|
||||||
| Course | ruff | Can it be verified by running? |
|
| 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 |
|
||||||
|
|
||||||
`course_run.sh`'s notebook branch is fixed: it executes to a temp
|
**Before running the notebook courses, fix `scripts/course_run.sh` first.**
|
||||||
`--output-dir`, probes jupyter by running it rather than by `command -v`, and
|
Its notebook branch is `jupyter nbconvert --execute --inplace`, and all four
|
||||||
`course_main` now fails if a run changed anything git can see under the course
|
notebooks are tracked WITH their outputs -- that would overwrite a committed
|
||||||
root. `PBAD` is still blocked on jupyter itself -- the binary on PATH is a
|
deliverable. This exact bug has already been found twice (TRAK's
|
||||||
pipx shim whose interpreter is gone, so `--probe` reports "needs jupyter".
|
`outputs/output.png`, SPD's `results_*.png`); execute to a temp path instead.
|
||||||
|
|
||||||
**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,
|
||||||
mypy IS installed now (`~/.local/bin/mypy`) -- the earlier note here saying it
|
but mypy is not installed on this machine (pip is externally managed; use a
|
||||||
was not is out of date. **"Zero findings" in a commit message still means zero
|
venv) and no commit so far has type-checked. **"Zero findings" in the commit
|
||||||
RUFF findings unless it says otherwise**; only `TRAK` has been type-checked.
|
messages means zero RUFF findings.** Measured after installing it:
|
||||||
|
|
||||||
| Course | mypy --strict errors |
|
| Course | mypy --strict errors |
|
||||||
|---|---|
|
|---|---|
|
||||||
@ -76,8 +64,7 @@ RUFF findings unless it says otherwise**; only `TRAK` has been type-checked.
|
|||||||
| `ECOTE` | 14 |
|
| `ECOTE` | 14 |
|
||||||
| `NLP` | 29 |
|
| `NLP` | 29 |
|
||||||
| `EARIN/lab1` alone | 46 |
|
| `EARIN/lab1` alone | 46 |
|
||||||
| `TRAK` | **0** -- cleared 2026-08-29 |
|
| `TRAK` | 1 |
|
||||||
| `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:
|
||||||
@ -87,24 +74,15 @@ 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: 50 files
|
### 1. The 250-line cap: 51 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` | 10 | Several GREW during the lint pass, because docstrings and annotations are lines: `NLP/gpt_chunks.py` 911 -> 973, `EARIN/lab2/main.py` 581 -> 647, `PORR/.../linear_algebra_utils.py` 422 -> 553. Split them AFTER the lint work, not during. TRAK is already clear: its three over-cap files were split in the same pass that linted them, each verified by a byte-identical render. `twm_4/TWM_KerasIntro.py` joined the list at 407 lines and should NOT be split: it is an nbconvert export, and a partial one |
|
| `.py` | 11 | Several GREW during the lint pass, because docstrings and annotations are lines: `NLP/gpt_chunks.py` 911 -> 973, `EARIN/lab2/main.py` 581 -> 647, `PORR/.../linear_algebra_utils.py` 422 -> 553. Split them AFTER the lint work, not during |
|
||||||
| `.cpp` | 9 | |
|
| `.cpp` | 9 | |
|
||||||
| `.c` | 4 | |
|
| `.c` | 4 | |
|
||||||
| `.java` | 2 | |
|
| `.java` | 2 | |
|
||||||
@ -142,15 +120,6 @@ And run mypy per directory afterwards: it found 12 latent TypeErrors in EARIN
|
|||||||
that ruff could not see -- call sites still passing positionally to arguments
|
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
|
||||||
|
|||||||
@ -73,22 +73,6 @@ 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 = [
|
||||||
|
|||||||
@ -29,12 +29,6 @@ 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() {
|
||||||
@ -49,17 +43,6 @@ _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
|
||||||
@ -137,17 +120,7 @@ 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
|
||||||
}
|
}
|
||||||
|
|||||||
@ -52,7 +52,7 @@ _probe() {
|
|||||||
_runnable "compiles each standalone .cpp"
|
_runnable "compiles each standalone .cpp"
|
||||||
;;
|
;;
|
||||||
notebook)
|
notebook)
|
||||||
_works jupyter || _blocked "needs jupyter"
|
_have 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.
|
||||||
|
|||||||
@ -181,20 +181,11 @@ _run() {
|
|||||||
printf 'binaries in %s/build\n' "$COURSE_ROOT"
|
printf 'binaries in %s/build\n' "$COURSE_ROOT"
|
||||||
;;
|
;;
|
||||||
notebook)
|
notebook)
|
||||||
_works jupyter || _blocked "needs jupyter"
|
_have jupyter || _blocked "needs jupyter"
|
||||||
# NOT --inplace: all four notebooks in this repo are tracked WITH
|
local nb
|
||||||
# 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 --output-dir "$nbtmp" "$nb"
|
jupyter nbconvert --to notebook --execute --inplace "$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
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user