Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
db9c3ea
Added algorithm folder and document for summary/requirements. Marigol…
MJ-Parson Oct 1, 2026
640e3df
added algorithm process document to algorithm folder.
LiterallyAFlower Oct 8, 2026
e639144
added sticker png samples, file structure for algorithm, restarting. …
LiterallyAFlower Oct 17, 2026
1133c05
added toml for dependancies for testing/algo
LiterallyAFlower Oct 18, 2026
ab81375
added .gitignore, just for settings/os files and generated output, we…
LiterallyAFlower Oct 18, 2026
1835f5c
test driven development, test fails, writing now.
LiterallyAFlower Oct 18, 2026
abce7c8
additional test for creating smallest sticker model needed
LiterallyAFlower Oct 18, 2026
41b16f6
added sticker class, additional files.
LiterallyAFlower Oct 18, 2026
528eed1
added sticker tests for sticker implementation with new model require…
LiterallyAFlower Oct 18, 2026
5cde7d4
added tests, in red, testing with fixtures
MJ-Parson Oct 20, 2026
f975c56
added tests for svg input: test it loads stickers, test nonsense svg …
LiterallyAFlower Oct 22, 2026
0e6f50d
added path/point logic to loader.py to handle svg format.
LiterallyAFlower Oct 22, 2026
4d06f30
added load_sticker, so hopefully that works with these tests. tests s…
LiterallyAFlower Oct 22, 2026
2818782
tracking whether something is or isnt continuous is messing up. conti…
LiterallyAFlower Oct 22, 2026
115981e
altered loader.py to check for continous stickers. should work with a…
LiterallyAFlower Oct 22, 2026
8626bef
red phase, added lots of tests to check continuity. made a choice to …
LiterallyAFlower Oct 22, 2026
c097c5b
changed load sticker, need to rewrite some tests, stoppign for tonight.
LiterallyAFlower Oct 23, 2026
66b9456
red stage to test overlap and incorperate geometry, trying to get a g…
MJ-Parson Oct 26, 2026
bff57ee
red flag, coding page logic. this should be transmissable to whatever…
MJ-Parson Oct 26, 2026
a8ddba1
page logic works???? first try??????? somethings wrong ill look at it…
MJ-Parson Oct 26, 2026
32c63de
added tests for algorithm handling
MJ-Parson Oct 26, 2026
84ad607
greedy algorithm works!!!!! done for now, going to add more tests lat…
MJ-Parson Oct 26, 2026
5c848fa
developing less greedy algorithm to show off today with a visual element
MJ-Parson Oct 27, 2026
b09a44d
created semi-greedy algo, currently just uses greedy to pass tests, w…
MJ-Parson Oct 27, 2026
d7bf96c
two reds in a row, ik, but im on a streak. fixing tests for semi-gree…
MJ-Parson Oct 27, 2026
deaf34c
main tests now use semi-greedy, which factors in rotation and ordering.
MJ-Parson Oct 27, 2026
bafeab8
added visualization tests and directory. implementing visualization now.
MJ-Parson Oct 27, 2026
091a0f1
semi-greedy both works and exports everything correctly, outtput need…
MJ-Parson Oct 27, 2026
95c54d8
adding hpgl creation! fingers crossed, red stage.
MJ-Parson Nov 2, 2026
5484b68
file properly generates svg ouput!
MJ-Parson Nov 2, 2026
8717dcf
merging into github
MJ-Parson Nov 5, 2026
b43b4e2
Merge branch 'main' of https://github.com/RIT-Software-Engineering/Op…
MJ-Parson Nov 5, 2026
e9318fe
created pdf export files and test files.
MJ-Parson Nov 5, 2026
c16e24f
added failing tests for pdf creation.
MJ-Parson Nov 5, 2026
082023a
pdf exports are now working!! tests check for rotation, proper colors…
MJ-Parson Nov 5, 2026
52015af
added new pdf tests, refactored save pdf to take database arguments
MJ-Parson Nov 12, 2026
0b0e144
feat(test): adding failing test to point out svg y-axis flip bug
or8655 Nov 14, 2026
c68b48d
Merge branch 'feature/algorithm-development' of github-rit:RIT-Softwa…
or8655 Nov 14, 2026
5f3bef5
Added and fixed several problems, focused on pr criteria from oscar
LiterallyAFlower Nov 17, 2026
0c96da6
tests pass, moving on to revisiting the algorithm to fit it well in f…
MJ-Parson Nov 17, 2026
6daf645
Added a results class for the algorithm: can show if stickers are not…
MJ-Parson Nov 17, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions algorithm/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

# Python bytecode and caches
__pycache__/
*.py[cod]
.pytest_cache/
.coverage
htmlcov/

# Virtual environments
.venv/
venv/
env/

# Packaging/build artifacts
build/
dist/
*.egg-info/

# IDE/editor settings
.vscode/
.idea/
*.swp
*.swo

# OS files
.DS_Store
Thumbs.db

# Generated output
output/*
!output/.gitkeep
110 changes: 110 additions & 0 deletions algorithm/algo_doc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
I’m using a bottom-left greedy polygon-packing algorithm with a compactness score. Basically, place the biggest/weirdest/most difficult sticker first, then place the next one in the lowest leftmost position that produces the most compact sheet.
It’s greedy because I’m not planning on moving stickers again after placing them, as that would be very expensive computationally and time-wise.
It’s not optimal! But it is relatively fast, deterministic, human-readable, and with polygon geometry it can be very good.
For my code and for your visualization, I’m using tetris shapes.

Steps:
Get info from stickers.
For a quick example, 2 5 square pieces.
A
O O
O
O
O
(0,0)(1,0)
(0,1)
(0,2)
(0,3)

And
B
O O
O O
O
(0,0)(1,0)
(0,1)(1,1)
(0,2)
(this is just convenient picks to show the program)

2: Sort the stickers
We need to place the largest sticker first, so we sort with a couple parameters.
Area, bounding-box area (ill get to this later), width, height, complexity.
(easiest version:
stickers.sort(
key=lambda sticker: sticker.area,
reverse=True
)
)

For example, A would have an area of 5, and so would B. Their bounding box would be 2*4 for A, but only 2*3 for B, so you could put A first because it’s more awkward. Pick weird shapes first.

3:
The sheet can be whatever size you want, so we can arbitrarily choose what our demo sheet size is (obviously usually it’s 8x4 or whatever the size of a half sheet is)

4:
Sticker by Sticker
First, nothing on the sheet, so the candidate is (0,0)
And you place A there, taking up
(0,0)(1,0)
(0,1)
(0,2)
(0,3)
Then, B:
The laziest implementation would look at every coordinate, but because we’re not just working in whole numbers, that’s not helpful.
We would want to look for each edge of the current shape, including
Right side, bottom line, corners, and internal vertices.
For this example we get (2,0)(1,1)(1,2)(1,3) and (0,4) as options.

5: Where to put it
We go through all of the candidates!
(2,0)
If we place at 2,0 it looks like
O O O O
O X O O
O X O X
O X X X
So the placement would be (2,0)

(1,1)
It looks like
O O X X
O O O X
O O O X
O O X X

Continue for all of those position, then consider rotations of the shape.

A simple algorithm prefers lowest x, then lowest y, cram it all in the corner. However, I also want to consider going for the most square space.
O O X X feels more helpful than O O X X
O O X X O O O X
O O O O O O O X
O O O O O O O X

Because it can fit a bigger sticker in that space. (Want to figure this out, what im working on currently.)

So, I used a score: height of the shape after placement + wasted space + fragmentation. A lower score is better.

For option (2,0) our choice was
O O O O
O X O O
O X O X
O X X X
With a bounding box of 4*4
Where
O O X X
O O O X
O O O X
O O X X
Only has 3*4.
So it chooses that one.

That pattern continues until we get the smallest total area and score.
Obviously normal stickers aren’t just blocks but this is proof of concept that should work.


I’m including a 1-step lookahead, to avoid true recursion and too much burden, but it does help fit bigger stickers.

I’m going to include a variable for this that we can actually change to get deeper, but for now it’s staying at 0 for demos, then 1 for normal stuff, but if we want to go insane for efficiency over time we can deepen it.
Basically it’ll try one sticker, check other answers, go back a step and check again in case one of those is a more accurate fit.


Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the sticker-business/packing-algorithm/ should be the only home for the algorithm. Is there a need to keep the original root level algorithm folder?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, there's not, but it has some of my important code and pieces and I wanted to ensure it stuck around for a little. I'll remove it when I can.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to merge in this branch into main with only one packing algorithm folder. I think it would be bad practice to put in the main branch two folders for the algorithm. Can you move the important pieces of code into one directory?
I had stated sticker-business/packing-algorithm/ should be the only home for the algorithm, but its your call as to which directory you'd like to have the algorithm in main.

Empty file.
27 changes: 27 additions & 0 deletions algorithm/app/geometry/placement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from shapely.affinity import rotate, translate

def place_sticker(geometry, x, y, rotation_degrees=0):
"""Rotate a sticker and place its bounding box at (x,y)"""
placed = rotate(
geometry,
rotation_degrees,
origin="centroid",
)

min_x, min_y, _, _ = placed.bounds

return translate(
placed,
xoff=x - min_x,
yoff = y- min_y,
)

def stickers_overlap(first,second):
"""Return whether two stickers overlap in their interiors"""
return first.intersection(second).area >0

# page logic
def fits_on_page(sticker,page):
"""Return whether the entire sticker lies inside the page"""
return page.covers(sticker)

Empty file added algorithm/app/hpgl/__init__.py
Empty file.
54 changes: 54 additions & 0 deletions algorithm/app/hpgl/output.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from pathlib import Path

def save_hpgl(
placements,
output,
units_per_unit=1,
offset=(0,0),
):
"""Export sticker polygons as HPGL paths"""
output = Path(output)

offset_x, offset_y = offset
commands = [
"IN;",
"PA;",
"SP1;",
]

def plot_point(x,y):
plot_x = round((x + offset_x) * units_per_unit)
plot_y = round((y+offset_y) * units_per_unit)
return plot_x, plot_y

for _, geometry in placements:
if geometry.geom_type != "Polygon":
raise ValueError(
"Each sticker must be a single Polygon"
)

coordinates = list(geometry.exterior.coords)
if len(coordinates) < 4:
raise ValueError(
"Sticker outline must contain at least three points"
)

points = [plot_point(x,y) for x,y in coordinates]

# go to starting point with pen raised
start_x, start_y = points[0]
commands.append(f"PU{start_x},{start_y};")

#lower pen
remaining_points = points[1:-1]
coordinate_data = ",".join(
f"{x},{y}" for x,y in remaining_points
)

commands.append(f"PD{coordinate_data};")
commands.append("PU;")

commands.append("SP0;")

output.parent.mkdir(parents=True,exist_ok=True)
output.write_text("\n".join(commands), encoding="ascii")
Empty file.
14 changes: 14 additions & 0 deletions algorithm/app/models/sticker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from dataclasses import dataclass,field
# from shapely.geometry import Polygon

@dataclass
class Sticker:
"""Catalog metadata and file refs for one sticker."""
id:str
name:str
size:float
description:str
tags:list[str] = field(default_factory=list)
category:str=""
hpgl_path:str=""
svg_path:str=""
Empty file.
59 changes: 59 additions & 0 deletions algorithm/app/packing/greedy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
from app.geometry.placement import (
fits_on_page,
place_sticker,
stickers_overlap,
)

def pack_stickers(stickers,page):
"""Place stickers at the first valid position (super greedy)"""
placements = []
min_x,min_y,max_x,max_y = page.bounds

# use smallest sticker dimension
dimensions = [
min(sticker.bounds[2] - sticker.bounds[0],
sticker.bounds[3] - sticker.bounds[1])
for sticker in stickers
if not sticker.is_empty
]

if not dimensions:
return placements

step = min(dimensions)
if step <= 0:
return placements

remaining = sorted(
stickers,
key=lambda s: (
(s.bounds[2]-s.bounds[0])
* (s.bounds[3] - s.bounds[1])
),
reverse= True
)

y = min_y
while y < max_y:
x = min_x
while x < max_x:
for sticker in stickers:
if any(original is sticker for original, _ in placements):
continue

placed = place_sticker(sticker, x, y)

if not fits_on_page(placed,page):
continue

if any(
stickers_overlap(placed,existing)
for _, existing in placements
):
continue

placements.append((sticker, placed))

x+= step
y += step
return placements
64 changes: 64 additions & 0 deletions algorithm/app/packing/semi_greedy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
from app.packing.greedy import pack_stickers
import random

from app.geometry.placement import (
fits_on_page,
place_sticker,
stickers_overlap,
)


def pack_stickers_semi_greedy(stickers, page, seed=None):
"""Pack stickers by randomly choosing among the best candidates, including rotation"""
rng = random.Random(seed)

remaining = sorted(
stickers,
key=lambda s: (
(s.bounds[2] - s.bounds[0])
* (s.bounds[3] - s.bounds[1])
),
reverse=True,
)

min_x, min_y, _,_ = page.bounds
placements = []

for sticker in remaining:
positions = {(min_x,min_y)}

for _, placed in placements:
left, bottom, right, top = placed.bounds
positions.add((right, bottom))
positions.add((left,top))

candidates = []

for x, y in positions:
for angle in (0,90,180,270):
candidate = place_sticker(
sticker,
x,
y,
rotation_degrees=angle,
)

if not fits_on_page(candidate,page):
continue
if any(
stickers_overlap(candidate, existing)
for _, existing in placements
):
continue

_, bottom, right, top = candidate.bounds
score = (top,right,bottom, x,y, angle)
candidates.append((score, candidate))
if candidates:
candidates.sort(key=lambda item: item[0])

#choose randomly from 3 (variable) best valid candidates
shortlist = candidates[:3]
_, chosen = rng.choice(shortlist)
placements.append((sticker,chosen))
return placements
Empty file added algorithm/app/svg/__init__.py
Empty file.
Loading
Loading