PHPackages                             azaharizaman/nexus-routing - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. azaharizaman/nexus-routing

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

azaharizaman/nexus-routing
==========================

Route optimization and vehicle routing problem (VRP) solver for Nexus ERP

v0.1.0-alpha1(1mo ago)001MITPHPPHP ^8.3

Since May 5Pushed 1mo agoCompare

[ Source](https://github.com/azaharizaman/nexus-routing)[ Packagist](https://packagist.org/packages/azaharizaman/nexus-routing)[ RSS](/packages/azaharizaman-nexus-routing/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (2)Versions (2)Used By (1)

Nexus\\Routing
==============

[](#nexusrouting)

Route optimization and Vehicle Routing Problem (VRP) solver for the Nexus ERP system.

Overview
--------

[](#overview)

`Nexus\Routing` provides **framework-agnostic** algorithms for solving Traveling Salesman Problem (TSP) and Vehicle Routing Problem (VRP) with support for:

- **TSP Optimization**: Nearest-Neighbor with 2-Opt refinement
- **Multi-Vehicle VRP**: Google OR-Tools integration for complex constraints
- **Offline Routing Cache**: Gzip-compressed route storage (50MB limit)
- **Constraint Validation**: Time windows, vehicle capacity, service duration
- **Route Metrics**: Total distance, duration, constraint violations

This package depends on `azaharizaman/nexus-geo` for distance calculations and coordinates.

Installation
------------

[](#installation)

```
composer require azaharizaman/nexus-routing:*@dev
```

Features
--------

[](#features)

### 1. TSP Optimization (Single Vehicle)

[](#1-tsp-optimization-single-vehicle)

Optimizes route for a single vehicle visiting multiple stops:

```
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());
```

**Output:**

```
Total Distance: 12.45 km
Total Duration: 00:42:30
Optimized Sequence: depot -> stop_2 -> stop_3 -> stop_1 -> depot

```

### 2. VRP Optimization (Multi-Vehicle)

[](#2-vrp-optimization-multi-vehicle)

Assigns stops to multiple vehicles with capacity constraints:

```
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');
}
```

### 3. Time Window Constraints

[](#3-time-window-constraints)

Enforce delivery time windows:

```
$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}";
    }
}
```

### 4. Offline Route Cache

[](#4-offline-route-cache)

Store optimized routes for offline mobile app access:

```
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";
```

**Cache Characteristics:**

- **Compression**: Gzip compression (typically 80% reduction)
- **Size Limit**: 50MB per tenant
- **TTL**: 30 days (configurable)
- **Versioning**: Cache key includes route parameters hash

### 5. OR-Tools Integration

[](#5-or-tools-integration)

For complex VRP scenarios, integrate with Google OR-Tools Docker service:

```
// 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)
```

Architecture
------------

[](#architecture)

### Package Structure

[](#package-structure)

```
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

```

### Algorithm Performance

[](#algorithm-performance)

AlgorithmStopsVehiclesTime ComplexityExecution Time**Nearest-Neighbor**501O(n²)~10ms**2-Opt Refinement**501O(n²)~50ms**VRP (Greedy)**1005O(n² × v)~200ms**OR-Tools (Meta)**50010Variable5-30s### Cost Optimization Strategies

[](#cost-optimization-strategies)

1. **Cache Reusable Routes**: Store frequently-requested routes (e.g., daily delivery routes)
2. **Batch Optimization**: Combine multiple route requests for OR-Tools
3. **Tiered Approach**: Use TSP for &lt;20 stops, VRP for 20-100, OR-Tools for &gt;100
4. **Offline Priority**: Deliver cache to mobile apps to reduce real-time API calls

Integration with Nexus\\Geo
---------------------------

[](#integration-with-nexusgeo)

This package tightly integrates with `Nexus\Geo`:

```
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);
```

Constraint Violation Logging
----------------------------

[](#constraint-violation-logging)

All constraint violations are logged for analytics:

```
// 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);
```

Configuration
-------------

[](#configuration)

Configuration is managed in `config/routing.php` (in Atomy):

```
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
    ],
];
```

Testing
-------

[](#testing)

```
vendor/bin/phpunit packages/Routing/tests
```

📖 Documentation
---------------

[](#-documentation)

### Package Documentation

[](#package-documentation)

- [Getting Started Guide](docs/getting-started.md)
- [API Reference](docs/api-reference.md)
- [Integration Guide](docs/integration-guide.md)
- [Examples](docs/examples/)

### Additional Resources

[](#additional-resources)

- `IMPLEMENTATION_SUMMARY.md` - Implementation progress
- `REQUIREMENTS.md` - Requirements
- `TEST_SUITE_SUMMARY.md` - Tests
- `VALUATION_MATRIX.md` - Valuation

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

Dependencies
------------

[](#dependencies)

- `azaharizaman/nexus-geo`: Geospatial calculations
- `psr/log`: Logging interface
- Google OR-Tools (optional, via Docker)

Contributing
------------

[](#contributing)

This package follows the Nexus monorepo **Logic in Packages, Implementation in Applications** architecture. All business logic stays framework-agnostic.

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance93

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity34

Early-stage or recently created project

 Bus Factor1

Top contributor holds 76.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

36d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/117408?v=4)[Azahari Zaman](/maintainers/azaharizaman)[@azaharizaman](https://github.com/azaharizaman)

---

Top Contributors

[![azaharizaman](https://avatars.githubusercontent.com/u/117408?v=4)](https://github.com/azaharizaman "azaharizaman (465 commits)")[![Copilot](https://avatars.githubusercontent.com/in/1143301?v=4)](https://github.com/Copilot "Copilot (139 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")

### Embed Badge

![Health badge](/badges/azaharizaman-nexus-routing/health.svg)

```
[![Health](https://phpackages.com/badges/azaharizaman-nexus-routing/health.svg)](https://phpackages.com/packages/azaharizaman-nexus-routing)
```

###  Alternatives

[symfony/lock

Creates and manages locks, a mechanism to provide exclusive access to a shared resource

515135.1M619](/packages/symfony-lock)[matomo/matomo

Matomo is the leading Free/Libre open analytics platform

21.6k38.2k](/packages/matomo-matomo)[phpro/soap-client

A general purpose SoapClient library

8955.9M52](/packages/phpro-soap-client)[ecotone/ecotone

Enterprise architecture layer for Laravel and Symfony — CQRS, Event Sourcing, Durable Workflows (Sagas, Orchestrators), Projections, and Outbox messaging via PHP attributes.

562565.8k41](/packages/ecotone-ecotone)[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

744284.3k34](/packages/civicrm-civicrm-core)[illuminate/broadcasting

The Illuminate Broadcasting package.

7126.9M199](/packages/illuminate-broadcasting)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
