-
Notifications
You must be signed in to change notification settings - Fork 2
Feature/assign shipment #32
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
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
b88baab
Change timezone
Ke-vin-S 6a4f083
Clients for other apps
Ke-vin-S 5145400
Merge pull request #31 from IASSCMS/main
Ke-vin-S 77215c7
change shipment model
Ke-vin-S 81e106e
update assignment model
Ke-vin-S db4eca9
Delete clients for apps in this project
Ke-vin-S d3b9424
Add demand field to shipment
Ke-vin-S 863361e
Add depot fields to vehicle model
Ke-vin-S 5561239
Assignment service
Ke-vin-S 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
This file was deleted.
Oops, something went wrong.
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,26 @@ | ||
| from django.db import models | ||
| from fleet.models import Vehicle | ||
|
|
||
| class Assignment(models.Model): | ||
| vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) | ||
| created_at = models.DateTimeField(auto_now_add=True) | ||
| started_at = models.DateTimeField(null=True, blank=True) | ||
| completed_at = models.DateTimeField(null=True, blank=True) | ||
|
|
||
| status = models.CharField( | ||
| max_length=32, | ||
| choices=[ | ||
| ('created', 'Created'), | ||
| ('dispatched', 'Dispatched'), | ||
| ('partially_completed', 'Partially Completed'), | ||
| ('completed', 'Completed'), | ||
| ('failed', 'Failed'), | ||
| ('reassigned', 'Reassigned'), | ||
| ], | ||
| default='created' | ||
| ) | ||
|
|
||
| total_load = models.PositiveIntegerField() | ||
|
|
||
| def __str__(self): | ||
| return f"Assignment #{self.id} to Vehicle {self.vehicle.vehicle_id}" |
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,20 @@ | ||
| from django.db import models | ||
|
|
||
| from assignment.models.assignment import Assignment | ||
| from shipments.models import Shipment | ||
|
|
||
|
|
||
| class AssignmentItem(models.Model): | ||
| assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE, related_name='items') | ||
| shipment = models.ForeignKey(Shipment, on_delete=models.CASCADE) | ||
| delivery_sequence = models.PositiveIntegerField() # 1st, 2nd, 3rd drop, etc. | ||
| delivery_location = models.JSONField() # { "lat": ..., "lng": ... } | ||
|
|
||
| is_delivered = models.BooleanField(default=False) | ||
| delivered_at = models.DateTimeField(null=True, blank=True) | ||
|
|
||
| class Meta: | ||
| ordering = ['delivery_sequence'] | ||
|
|
||
| def __str__(self): | ||
| return f"Shipment {self.shipment.id} in Assignment {self.assignment.id}" |
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
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,91 @@ | ||
| import logging | ||
| from typing import List | ||
| from datetime import datetime | ||
|
|
||
| from assignment.models.assignment import Assignment | ||
| from assignment.models.assignment_item import AssignmentItem | ||
| from assignment.services.mappers import map_vehicle_model | ||
| from fleet.models import Vehicle | ||
| from route_optimizer.services.vrp_solver import solve_cvrp | ||
| from shipments.models import Shipment | ||
| from route_optimizer.models.vrp_input import VRPInputBuilder, VRPCompiler, Location, DeliveryTask | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
| logging.basicConfig(level=logging.DEBUG) | ||
|
|
||
| class AssignmentPlanner: | ||
| def __init__(self, vehicles: List[Vehicle], shipments: List[Shipment]): | ||
| self.vehicles = vehicles | ||
| self.shipments = shipments | ||
|
|
||
| def plan_assignments(self) -> List[Assignment]: | ||
| logger.info("Planning assignments started.") | ||
| builder = VRPInputBuilder() | ||
|
|
||
| vehicle_map = {} | ||
| for v in self.vehicles: | ||
| logger.debug(f"Mapping vehicle: {v.vehicle_id}") | ||
| mapped_vehicle = map_vehicle_model(v) | ||
| builder.add_vehicle(mapped_vehicle) | ||
| vehicle_map[mapped_vehicle.id] = v | ||
| logger.info(f"{len(vehicle_map)} vehicles added to VRP input.") | ||
|
|
||
| shipment_map = {} | ||
| for s in self.shipments: | ||
| logger.debug(f"Adding shipment: {s.shipment_id} (demand={s.demand})") | ||
| builder.add_delivery_task( | ||
| DeliveryTask( | ||
| id=str(s.id), | ||
| pickup=Location(lat=s.origin["lat"], lon=s.origin["lng"]), | ||
| delivery=Location(lat=s.destination["lat"], lon=s.destination["lng"]), | ||
| demand=s.demand, | ||
| ) | ||
| ) | ||
| shipment_map[str(s.id)] = s | ||
| logger.info(f"{len(shipment_map)} shipments added to VRP input.") | ||
|
|
||
| vrp_input = VRPCompiler.compile(builder) | ||
| logger.debug(f"Compiled VRP input with {len(vrp_input.location_ids)} locations.") | ||
|
|
||
| result = solve_cvrp(vrp_input) | ||
| logger.info("Optimizer finished solving.") | ||
|
|
||
| if result["status"] != "success": | ||
| logger.error("Optimizer failed to find a solution.") | ||
| raise Exception("Optimization failed") | ||
|
|
||
| assignments = [] | ||
| for i, route in enumerate(result["routes"]): | ||
| vehicle = self.vehicles[i] | ||
| logger.debug(f"Creating assignment for vehicle {vehicle.vehicle_id}, route: {route}") | ||
| assignment = Assignment.objects.create( | ||
| vehicle=vehicle, | ||
| total_load=sum( | ||
| vrp_input.demands[node] for node in route if vrp_input.demands[node] > 0 | ||
| ), | ||
| status='created' | ||
| ) | ||
|
|
||
| seq = 1 | ||
| for node in route: | ||
| if node in vrp_input.task_index_map: | ||
| task_id, role = vrp_input.task_index_map[node] | ||
| shipment = shipment_map[task_id] | ||
| loc = shipment.destination if role == "delivery" else shipment.origin | ||
|
|
||
| logger.debug(f"Adding {role} for shipment {shipment.shipment_id} at sequence {seq}") | ||
| AssignmentItem.objects.create( | ||
| assignment=assignment, | ||
| shipment=shipment, | ||
| delivery_sequence=seq, | ||
| delivery_location={ | ||
| "lat": loc["lat"], | ||
| "lng": loc["lng"], | ||
| } | ||
| ) | ||
| seq += 1 | ||
|
|
||
| assignments.append(assignment) | ||
|
|
||
| logger.info(f"{len(assignments)} assignments successfully created.") | ||
| return assignments | ||
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 route_optimizer.models.vrp_input import Vehicle as VRPVehicle, Location | ||
|
|
||
| def map_vehicle_model(vehicle_model): | ||
| if vehicle_model.depot_latitude is None or vehicle_model.depot_longitude is None: | ||
| raise ValueError(f"Vehicle {vehicle_model.vehicle_id} missing depot coordinates") | ||
|
|
||
| return VRPVehicle( | ||
| id=vehicle_model.vehicle_id, | ||
| capacity=vehicle_model.capacity, | ||
| depot=Location( | ||
| lat=float(vehicle_model.depot_latitude), | ||
| lon=float(vehicle_model.depot_longitude) | ||
| ) | ||
| ) |
This file was deleted.
Oops, something went wrong.
Empty file.
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.
[nitpick] Assuming that the order of routes from the VRP solver always matches the order of self.vehicles might be fragile. Consider adding a mapping mechanism to associate each route with the correct vehicle to improve robustness.