Repository navigation
Feature/algorithm development #54
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
MJ-Parson
wants to merge
41
commits into
main
Choose a base branch
from
feature/algorithm-development
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
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 640e3df
added algorithm process document to algorithm folder.
LiterallyAFlower e639144
added sticker png samples, file structure for algorithm, restarting. …
LiterallyAFlower 1133c05
added toml for dependancies for testing/algo
LiterallyAFlower ab81375
added .gitignore, just for settings/os files and generated output, we…
LiterallyAFlower 1835f5c
test driven development, test fails, writing now.
LiterallyAFlower abce7c8
additional test for creating smallest sticker model needed
LiterallyAFlower 41b16f6
added sticker class, additional files.
LiterallyAFlower 528eed1
added sticker tests for sticker implementation with new model require…
LiterallyAFlower 5cde7d4
added tests, in red, testing with fixtures
MJ-Parson f975c56
added tests for svg input: test it loads stickers, test nonsense svg …
LiterallyAFlower 0e6f50d
added path/point logic to loader.py to handle svg format.
LiterallyAFlower 4d06f30
added load_sticker, so hopefully that works with these tests. tests s…
LiterallyAFlower 2818782
tracking whether something is or isnt continuous is messing up. conti…
LiterallyAFlower 115981e
altered loader.py to check for continous stickers. should work with a…
LiterallyAFlower 8626bef
red phase, added lots of tests to check continuity. made a choice to …
LiterallyAFlower c097c5b
changed load sticker, need to rewrite some tests, stoppign for tonight.
LiterallyAFlower 66b9456
red stage to test overlap and incorperate geometry, trying to get a g…
MJ-Parson bff57ee
red flag, coding page logic. this should be transmissable to whatever…
MJ-Parson a8ddba1
page logic works???? first try??????? somethings wrong ill look at it…
MJ-Parson 32c63de
added tests for algorithm handling
MJ-Parson 84ad607
greedy algorithm works!!!!! done for now, going to add more tests lat…
MJ-Parson 5c848fa
developing less greedy algorithm to show off today with a visual element
MJ-Parson b09a44d
created semi-greedy algo, currently just uses greedy to pass tests, w…
MJ-Parson d7bf96c
two reds in a row, ik, but im on a streak. fixing tests for semi-gree…
MJ-Parson deaf34c
main tests now use semi-greedy, which factors in rotation and ordering.
MJ-Parson bafeab8
added visualization tests and directory. implementing visualization now.
MJ-Parson 091a0f1
semi-greedy both works and exports everything correctly, outtput need…
MJ-Parson 95c54d8
adding hpgl creation! fingers crossed, red stage.
MJ-Parson 5484b68
file properly generates svg ouput!
MJ-Parson 8717dcf
merging into github
MJ-Parson b43b4e2
Merge branch 'main' of https://github.com/RIT-Software-Engineering/Op…
MJ-Parson e9318fe
created pdf export files and test files.
MJ-Parson c16e24f
added failing tests for pdf creation.
MJ-Parson 082023a
pdf exports are now working!! tests check for rotation, proper colors…
MJ-Parson 52015af
added new pdf tests, refactored save pdf to take database arguments
MJ-Parson 0b0e144
feat(test): adding failing test to point out svg y-axis flip bug
or8655 c68b48d
Merge branch 'feature/algorithm-development' of github-rit:RIT-Softwa…
or8655 5f3bef5
Added and fixed several problems, focused on pr criteria from oscar
LiterallyAFlower 0c96da6
tests pass, moving on to revisiting the algorithm to fit it well in f…
MJ-Parson 6daf645
Added a results class for the algorithm: can show if stickers are not…
MJ-Parson File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
|
|
||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 inmain.