Skip to content
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

Feature: named parts #60

Merged
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ jobs:
- name: Set up Python ⚙️
uses: actions/setup-python@v4
with:
python-version: "3.9" # keep in sync with pipfile
python-version: "3.11" # keep in sync with pipfile

- name: Install dependencies ⚙️
run: |
Expand Down
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# this size should be irrelevant
FROM python:3.9 as build
FROM python:3.11 as build
# exporting here is a lot safer than depending on the dev environment. Pipenv is kept out of the container by design.
COPY ./Pipfile /Pipfile
RUN pip install pipenv
Expand All @@ -9,7 +9,7 @@ RUN pipenv lock && pipenv requirements > dev-requirements.txt
# certifi+httpie allows healthchecks with tiny installation size (#37)
RUN pip install --user --no-cache-dir --no-warn-script-location -r dev-requirements.txt

FROM python:3.9-slim
FROM python:3.11-slim
# https://github.com/opencontainers/image-spec/blob/master/annotations.md
LABEL "org.opencontainers.image.title"="CutSolver"
LABEL "org.opencontainers.image.vendor"="Modisch Fabrications"
Expand Down
17 changes: 9 additions & 8 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@ url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]
pytest = "==7.1.3"
requests = "==2.28.1"
pre-commit = "==2.20.0"
GitPython = "==3.1.9"
flake8 = "==5.0.4"
pytest = "==7.4.4"
requests = "==2.31.0"
pre-commit = "==3.6.0"
GitPython = "==3.1.41"
flake8 = "==7.0.0"
httpx = "==0.26.0"

[packages]
fastapi = "==0.85.1"
uvicorn = "==0.18.3"
fastapi = "==0.109.0"
uvicorn = "==0.26.0"

[requires]
python_version = "3.9"
python_version = "3.11"
682 changes: 415 additions & 267 deletions Pipfile.lock

Large diffs are not rendered by default.

17 changes: 7 additions & 10 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,28 @@
import platform
from contextlib import asynccontextmanager

from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.responses import HTMLResponse, PlainTextResponse

from app.constants import version, n_max_precise, n_max

# don't mark /app as a sources root or pycharm will delete the "app." prefix
# that's needed for pytest to work correctly
from app.solver.data.Job import Job
from app.solver.data.Result import Result
from app.solver.solver import distribute

app = FastAPI(
title="CutSolverBackend",
version=version
)


@app.on_event("startup")
async def on_startup():
@asynccontextmanager
async def lifespan(app: FastAPI):
print(f"Starting CutSolver {version}...")
yield
print("Shutting down CutSolver...")


@app.on_event("shutdown")
async def on_shutdown():
print(f"Shutting down CutSolver...")
app = FastAPI(title="CutSolverBackend", version=version, lifespan=lifespan)


# needs to be before CORS!
Expand Down
60 changes: 34 additions & 26 deletions app/solver/data/Job.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from typing import Iterator, Dict, List
from typing import Iterator, List, Optional, Tuple

from pydantic import BaseModel


class TargetSize(BaseModel):
length: int
quantity: int
name: Optional[str] = ""

def __lt__(self, other):
"""
Expand All @@ -20,59 +21,66 @@ def __str__(self):
class Job(BaseModel):
max_length: int
cut_width: int = 0
target_sizes: Dict[int, int]
target_sizes: List[TargetSize]

# utility

def iterate_sizes(self) -> Iterator[int]:
def iterate_sizes(self) -> Iterator[Tuple[int, str | None]]:
"""
yields all lengths, sorted descending
"""

# sort descending to favor combining larger sizes first
for size, quantity in sorted(self.target_sizes.items(), reverse=True):
for _ in range(quantity):
yield size
for target in sorted(self.target_sizes, key=lambda x: x.length, reverse=True):
for _ in range(target.quantity):
yield (target.length, target.name)

# NOTE: Not used, so not really refactored at the moment
def sizes_from_list(self, sizes_list: List[TargetSize]):
known_sizes = {}

# list to dict to make them unique
for size in sizes_list:
if size.length in known_sizes:
known_sizes[size.length] += size.quantity
else:
known_sizes[size.length] = size.quantity

self.target_sizes = known_sizes

# known_sizes = {}
#
# # list to dict to make them unique
# for size in sizes_list:
# if size.length in known_sizes:
# known_sizes[size.length] += size.quantity
# else:
# known_sizes[size.length] = size.quantity

self.target_sizes = sizes_list

# NOTE: Can eventually be removed as it does nothing anymore
def sizes_as_list(self) -> List[TargetSize]:
"""
Compatibility function
"""
# back to list again for compatibility
return [TargetSize(length=l, quantity=q) for (l, q) in self.target_sizes.items()]
return self.target_sizes

def assert_valid(self):
if self.max_length <= 0:
raise ValueError(f"Job has invalid max_length {self.max_length}")
if self.cut_width < 0:
raise ValueError(f"Job has invalid cut_width {self.cut_width}")
if len(self.target_sizes) <= 0:
raise ValueError(f"Job is missing target_sizes")
if any(size > (self.max_length - self.cut_width) for size in self.target_sizes.keys()):
raise ValueError(f"Job has target sizes longer than the stock")
raise ValueError("Job is missing target_sizes")
if any(
target.length > (self.max_length - self.cut_width)
for target in self.target_sizes
):
raise ValueError("Job has target sizes longer than the stock")

def __len__(self) -> int:
"""
Number of target sizes in job
"""
return sum(self.target_sizes.values())
return sum([target.quantity for target in self.target_sizes])

def __eq__(self, other):
return self.max_length == other.max_length and \
self.cut_width == other.cut_width and \
self.target_sizes == other.target_sizes
return (
self.max_length == other.max_length
and self.cut_width == other.cut_width
and self.target_sizes == other.target_sizes
)

def __hash__(self) -> int:
return hash((self.max_length, self.cut_width, str(sorted(self.target_sizes.items()))))
return hash((self.max_length, self.cut_width, str(sorted(self.target_sizes))))
18 changes: 9 additions & 9 deletions app/solver/data/Result.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from enum import unique, Enum
from typing import List
from typing import List, Tuple

from pydantic import BaseModel

Expand All @@ -18,23 +18,23 @@ class Result(BaseModel):
job: Job
solver_type: SolverType
time_us: int = -1
lengths: List[List[int]]
lengths: List[List[Tuple[int, str]]]

# no trimmings as they can be inferred from difference to job

def __eq__(self, other):
return (
self.job == other.job
and self.solver_type == other.solver_type
and self.lengths == other.lengths
self.job == other.job
and self.solver_type == other.solver_type
and self.lengths == other.lengths
)

def exactly(self, other):
return (
self.job == other.job
and self.solver_type == other.solver_type
and self.time_us == other.time_us
and self.lengths == other.lengths
self.job == other.job
and self.solver_type == other.solver_type
and self.time_us == other.time_us
and self.lengths == other.lengths
)

def assert_valid(self):
Expand Down
Loading
Loading