PHP code example of azaharizaman / nexus-routing

1. Go to this page and download the library: Download azaharizaman/nexus-routing library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

azaharizaman / nexus-routing example snippets


use Nexus\Routing\Services\TspOptimizer;
use Nexus\Routing\ValueObjects\RouteStop;
use Nexus\Geo\ValueObjects\Coordinates;

$stops = [
    new RouteStop('stop_1', new Coordinates(3.1390, 101.6869), null, null, 300), // 5 min service
    new RouteStop('stop_2', new Coordinates(3.1478, 101.6953), null, null, 600),
    new RouteStop('stop_3', new Coordinates(3.1570, 101.7123), null, null, 450),
];

$result = $tspOptimizer->optimize($stops, $depotCoordinates);

echo "Total Distance: " . $result->optimizedRoute->totalDistance->format('km');
echo "Total Duration: " . gmdate('H:i:s', $result->optimizedRoute->totalDurationSeconds);
echo "Optimized Sequence: " . implode(' -> ', $result->optimizedRoute->getStopIds());

use Nexus\Routing\Services\VrpOptimizer;
use Nexus\Routing\ValueObjects\VehicleProfile;
use Nexus\Routing\ValueObjects\RouteConstraints;

$vehicles = [
    new VehicleProfile('truck_1', 1000, $depotCoordinates), // 1000 kg capacity
    new VehicleProfile('truck_2', 800, $depotCoordinates),
];

$constraints = new RouteConstraints(
    maxDurationSeconds: 28800, // 8 hours
    maxCapacity: 1000
);

$result = $vrpOptimizer->optimize($stops, $vehicles, $constraints);

foreach ($result->routes as $vehicleId => $route) {
    echo "Vehicle {$vehicleId}: " . $route->totalDistance->format('km');
}

$stop = new RouteStop(
    id: 'customer_123',
    coordinates: new Coordinates(3.1390, 101.6869),
    timeWindowStart: new \DateTimeImmutable('2025-01-15 09:00:00'),
    timeWindowEnd: new \DateTimeImmutable('2025-01-15 12:00:00'),
    serviceDurationSeconds: 600, // 10 minutes
    demand: 50 // 50 kg
);

$violations = $constraintValidator->validate($route, $constraints);

if (!empty($violations)) {
    foreach ($violations as $violation) {
        echo "{$violation->type}: {$violation->description}";
    }
}

use Nexus\Routing\Services\OfflineRouteCacheManager;

// Store route
$cacheManager->store($routeId, $optimizedRoute, $tenantId);

// Retrieve for offline use
$cachedRoute = $cacheManager->retrieve($routeId, $tenantId);

// Get cache metrics
$metrics = $cacheManager->getMetrics($tenantId);
echo "Total cached routes: {$metrics->totalRoutes}";
echo "Cache size: " . number_format($metrics->totalSizeBytes / 1024 / 1024, 2) . " MB";

// In Atomy adapter (apps/Atomy/app/Services/ORToolsAdapter.php)
$result = $orToolsAdapter->solve($stops, $vehicles, $constraints);

// OR-Tools provides:
// - Advanced constraints (pickup/delivery pairs, vehicle breaks)
// - Metaheuristics (Simulated Annealing, Tabu Search)
// - Large-scale optimization (1000+ stops)

use Nexus\Geo\Services\DistanceCalculator;
use Nexus\Geo\Services\TravelTimeEstimator;
use Nexus\Routing\Services\TspOptimizer;

$distanceCalculator = new DistanceCalculator();
$travelTimeEstimator = new TravelTimeEstimator($distanceCalculator);

$tspOptimizer = new TspOptimizer($distanceCalculator, $travelTimeEstimator, $logger);

// Violations are tracked in OptimizationMetrics
$metrics = $result->metrics;

foreach ($metrics->violations as $violation) {
    // Log to Nexus\QueryEngine
    $analyticsLogger->logConstraintViolation($violation);
}

// Query violations trend
$trendData = $analyticsService->getViolationTrend($tenantId, $startDate, $endDate);

return [
    'offline_cache' => [
        'enabled' => true,
        'max_size_mb' => 50,
        'ttl_days' => 30,
        'compression' => 'gzip',
    ],
    'or_tools' => [
        'docker_host' => env('OR_TOOLS_HOST', 'localhost'),
        'docker_port' => env('OR_TOOLS_PORT', 8080),
        'timeout_seconds' => 60,
    ],
    'optimization' => [
        'tsp_threshold' => 20,      // Use TSP for ≤20 stops
        'vrp_threshold' => 100,     // Use VRP for ≤100 stops
        'use_or_tools_above' => 100, // Use OR-Tools for >100 stops
    ],
];

packages/Routing/
├── src/
│   ├── Contracts/
│   │   ├── RouteOptimizerInterface.php
│   │   ├── RouteCacheInterface.php
│   │   └── ConstraintValidatorInterface.php
│   ├── Services/
│   │   ├── TspOptimizer.php           # Nearest-Neighbor + 2-Opt
│   │   ├── VrpOptimizer.php           # Multi-vehicle assignment
│   │   └── OfflineRouteCacheManager.php
│   ├── ValueObjects/
│   │   ├── RouteStop.php
│   │   ├── OptimizedRoute.php
│   │   ├── VehicleProfile.php
│   │   ├── RouteConstraints.php
│   │   ├── RouteOptimizationResult.php
│   │   ├── ConstraintViolation.php
│   │   └── OptimizationMetrics.php
│   ├── Exceptions/
│   │   ├── RouteOptimizationException.php
│   │   ├── InvalidConstraintException.php
│   │   └── NoFeasibleSolutionException.php
│   └── ServiceProvider.php
├── composer.json
├── LICENSE
└── README.md