Skip to content

pockerrock/ContainerFit

Repository files navigation

ContainerFit - 3D Container Loading Optimization

ContainerFit is a web application that optimizes the packing of items (especially plastic rolls and cylindrical goods) into shipping containers using advanced 3D bin packing algorithms.

ContainerFit License

Features

Core Capabilities

  • Multi-item type support: Handles both rectangular boxes and cylindrical rolls (plastic films, fabrics, paper, etc.)

  • Advanced constraint satisfaction:

    • Never exceed container internal dimensions
    • Respect weight limits and floor load constraints
    • Maintain center-of-gravity within configurable tolerances
    • Enforce stacking rules and support requirements
    • Respect per-item rotation/orientation flags
  • Multi-stage solver pipeline:

    • Stage A: Feasibility checking (weight, dimensions)
    • Stage B: Knapsack selection using OR-Tools CP-SAT for optimal item quantity selection
    • Stage C: Layer-based constructive placement with guillotine heuristics
    • Stage D: Local optimization using genetic algorithms and hill-climbing
    • Stage E: Stability and center-of-gravity verification
  • Interactive 3D visualization: Real-time Three.js rendering showing:

    • Container wireframe
    • Placed items with color-coding by SKU
    • Cylindrical visualization for rolls
    • Orientation indicators (horizontal/vertical)
  • Comprehensive reporting:

    • Volume and weight utilization statistics
    • Center-of-gravity calculations
    • Placed vs. unplaced item counts
    • Roll-specific metrics (horizontal/vertical counts)
    • JSON, CSV, and PDF export options

Tech Stack

Backend

  • Framework: FastAPI (Python 3.10+)
  • Optimization Engine: OR-Tools CP-SAT for knapsack/ILP problems
  • Data Validation: Pydantic for robust type checking
  • Reports: ReportLab for PDF generation
  • Database: PostgreSQL (optional, for persistence)
  • Task Queue: Celery with Redis (for background jobs)

Frontend

  • Framework: React 18 with TypeScript
  • Styling: Tailwind CSS
  • 3D Visualization: Three.js with react-three-fiber
  • Build Tool: Vite
  • HTTP Client: Axios

Quick Start

Prerequisites

  • Python 3.10+
  • Node.js 18+
  • npm or yarn

Installation

1. Clone the repository

git clone https://github.com/your-org/ContainerFit.git
cd ContainerFit

2. Backend Setup

cd backend
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt

3. Frontend Setup

cd frontend
npm install

Running Locally

Start the Backend

Option 1: Using the startup script (Recommended)

# From project root directory
python run_backend.py

# Or on Linux/Mac:
./run_backend.sh

# Or on Windows:
run_backend.bat

Option 2: Manual start

# From project root directory
python -m backend.main

# Or with virtual environment:
cd backend
source venv/bin/activate  # On Windows: venv\Scripts\activate
cd ..
python -m backend.main

The API will be available at http://localhost:8000

API documentation: http://localhost:8000/docs

Start the Frontend

cd frontend
npm run dev

The web interface will be available at http://localhost:3000

Usage

Web Interface

  1. Navigate to http://localhost:3000
  2. Configure your container dimensions and constraints
  3. Add items (plastic rolls or boxes):
    • For rolls: specify diameter, roll width, inner diameter
    • For boxes: specify length, width, height
    • Set weight, quantity, and orientation options
  4. Click "Pack Container" to run the optimization
  5. View the 3D visualization and results
  6. Export results as JSON, CSV, or PDF

CSV Import

Create a CSV file with your items:

For plastic rolls:

sku,item_type,diameter,roll_width,inner_diameter,weight,quantity,material,color,stackable,fragile
LDPE-150-1000-CLR,roll,150,1000,76,12.5,20,LDPE,Clear,true,false
HDPE-200-1200-BLK,roll,200,1200,76,22.0,15,HDPE,Black,true,false

For boxes:

sku,item_type,length,width,height,weight,quantity,stackable,fragile
BOX-001,box,600,400,300,25,50,true,false

Upload via the web interface or use the API endpoint:

curl -X POST http://localhost:8000/api/pack/csv \
  -F "container_data={\"length\":12000,\"width\":2350,\"height\":2400,\"max_payload\":28000}" \
  -F "items_file=@items.csv"

API Usage

import requests

# Define container
container = {
    "length": 12000,
    "width": 2350,
    "height": 2400,
    "max_payload": 28000,
    "door_orientation": "front",
    "cog_offset_x": 200,
    "cog_offset_y": 200,
    "cog_offset_z": 300
}

# Define items (plastic rolls)
items = [
    {
        "sku": "LDPE-150-1000-CLR",
        "item_type": "roll",
        "diameter": 150,
        "roll_width": 1000,
        "inner_diameter": 76,
        "weight": 12.5,
        "quantity": 20,
        "allowed_orientations": ["horizontal", "vertical"],
        "material": "LDPE",
        "color": "Clear"
    }
]

# Call the API
response = requests.post(
    "http://localhost:8000/api/pack",
    json={
        "container": container,
        "items": items,
        "optimization_time_budget": 60,
        "min_support_percentage": 0.75
    }
)

result = response.json()
print(f"Volume utilization: {result['volume_utilization'] * 100:.1f}%")
print(f"Placed items: {len(result['placed_items'])}")

Configuration

Solver Time Budget

Adjust the optimization time limit in your request:

{
  "optimization_time_budget": 120  // seconds
}

Or in the backend code at backend/models.py:

class PackingRequest(BaseModel):
    optimization_time_budget: int = Field(60, description="Time budget in seconds")

Center of Gravity Tolerances

Configure CoG offsets in the container specification:

{
  "cog_offset_x": 200,  // mm
  "cog_offset_y": 200,  // mm
  "cog_offset_z": 300   // mm
}

Support Requirements

Set minimum base support percentage:

{
  "min_support_percentage": 0.75  // 75% of base must be supported
}

Testing

Backend Tests

cd backend
pytest tests/ -v

Tests cover:

  • No overflow (items within container bounds)
  • No overweight (total weight ≤ payload)
  • Rotation/orientation enforcement
  • Collision detection
  • Stability checks
  • Weight conservation

Test Coverage

pytest --cov=backend tests/

Architecture

See ARCHITECTURE.md for detailed technical documentation including:

  • System architecture and component interactions
  • Solver algorithm details
  • Extension points for custom heuristics
  • How to add support for non-cuboid items
  • Performance tuning guidelines

Project Structure

ContainerFit/
├── backend/
│   ├── solver/
│   │   ├── __init__.py
│   │   ├── feasibility.py      # Stage A: Feasibility checks
│   │   ├── knapsack.py          # Stage B: OR-Tools CP-SAT knapsack
│   │   ├── placement.py         # Stage C: Layer-based placement
│   │   ├── optimization.py      # Stage D: Local optimization (GA/hill-climb)
│   │   ├── stability.py         # Stage E: Stability verification
│   │   └── main_solver.py       # Orchestrator
│   ├── tests/
│   │   ├── test_solver.py       # Solver constraint tests
│   │   └── test_api.py          # API endpoint tests
│   ├── models.py                # Pydantic data models
│   ├── main.py                  # FastAPI application
│   ├── export.py                # Export utilities (PDF, CSV)
│   └── requirements.txt
├── frontend/
│   ├── src/
│   │   ├── components/
│   │   │   ├── ContainerForm.tsx      # Container configuration
│   │   │   ├── ItemsManager.tsx       # Item management
│   │   │   ├── Visualizer3D.tsx       # Three.js 3D view
│   │   │   └── ResultsPanel.tsx       # Results display
│   │   ├── App.tsx              # Main application
│   │   ├── types.ts             # TypeScript interfaces
│   │   └── api.ts               # API client
│   └── package.json
├── examples/
│   ├── plastic_rolls.csv        # Sample plastic roll data
│   ├── standard_40ft_container.json
│   └── standard_20ft_container.json
└── README.md

Examples

Example datasets are provided in the examples/ directory:

  • plastic_rolls.csv: 10 different plastic roll SKUs (LDPE, HDPE, PP)
  • standard_40ft_container.json: Standard 40ft high-cube container specs
  • standard_20ft_container.json: Standard 20ft high-cube container specs

Performance

Typical solve times on a modern CPU (Intel i7 / AMD Ryzen 7):

  • Small problem (5-10 SKUs, 20-50 items): 2-5 seconds
  • Medium problem (10-20 SKUs, 50-150 items): 10-30 seconds
  • Large problem (20+ SKUs, 150+ items): 30-120 seconds

To improve performance:

  • Reduce optimization_time_budget for faster (but potentially sub-optimal) solutions
  • Adjust knapsack time allocation in backend/solver/main_solver.py
  • Use background task queue (Celery) for very large problems

Extending the System

Adding New Heuristics

To plug in custom packing heuristics, modify backend/solver/placement.py:

class LayerBasedPacker:
    def _place_item(self, item: Item) -> bool:
        # Your custom placement logic here
        pass

See ARCHITECTURE.md for detailed extension guidelines.

Supporting Non-Cuboid Items

The system currently supports boxes and cylinders. To add new shapes:

  1. Add new ItemType to backend/models.py
  2. Implement get_bounding_box() and get_volume() methods
  3. Update collision detection in backend/solver/placement.py
  4. Add visualization in frontend/src/components/Visualizer3D.tsx

Troubleshooting

OR-Tools installation issues

If you encounter issues installing OR-Tools:

pip install --upgrade pip
pip install ortools --no-cache-dir

CORS errors in frontend

Ensure the backend is running and the proxy is configured in frontend/vite.config.ts:

server: {
  proxy: {
    '/api': 'http://localhost:8000'
  }
}

3D visualization not rendering

Check browser console for errors. Ensure:

  • Browser supports WebGL
  • @react-three/fiber and @react-three/drei are installed correctly

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Submit a pull request

License

MIT License - see LICENSE file for details

References

Academic Papers

  • "The Three-Dimensional Bin Packing Problem" (Martello et al., 2000)
  • "Hybrid GRASP/VND heuristic for two-and three-dimensional bin packing" (Crainic et al., 2008)

Libraries Used

Support

For issues and feature requests, please use the GitHub issue tracker.

Roadmap

  • Add support for irregular shapes
  • Implement machine learning-based heuristics
  • Add multi-container optimization
  • Support for pallet constraints
  • Real-time collaboration features
  • Integration with ERP systems

Built with ❤️ for the logistics industry

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published