> ## Documentation Index
> Fetch the complete documentation index at: https://docs.solvice.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Cost Optimization

> Configure costs, priorities, and optimization objectives for efficient routing

# Cost Optimization

The VRP solver provides comprehensive cost modeling to optimize your routing operations based on real business constraints. This guide covers the recommended cost-based configuration, weight-based tuning, and optimization strategies.

## Quick Start: Cost-Based Optimization (Recommended)

The simplest way to configure the solver is using the `costs` configuration. Instead of tuning abstract weights, you specify actual business costs in EUR (or your currency), and the solver derives optimal weights automatically.

```json theme={null}
{
  "resources": [
    {
      "name": "driver-1",
      "hourlyCost": 25,
      "shifts": [{
        "from": "2024-03-15T08:00:00Z",
        "to": "2024-03-15T17:00:00Z"
      }]
    }
  ],
  "jobs": [
    {
      "name": "delivery-1",
      "location": {"latitude": 52.520, "longitude": 13.405},
      "duration": 1800
    }
  ],
  "costs": {
    "drivingCostPerHour": 25.0,
    "distanceCostPerKm": 0.35,
    "waitingCostPerHour": 15.0
  }
}
```

<Info>
  **Why use costs instead of weights?**

  * **Intuitive**: Costs represent real business values (EUR/hour, EUR/km)
  * **Comparable**: Different constraint types can be directly compared
  * **Transparent**: Response includes a cost breakdown in your currency
  * **Maintainable**: Business changes are easier to translate to configuration
</Info>

### Available Cost Parameters

| Parameter                        | Description                                  | Default         | Unit     |
| -------------------------------- | -------------------------------------------- | --------------- | -------- |
| `drivingCostPerHour`             | Cost of driver time while driving/traveling  | 25.0            | EUR/hour |
| `distanceCostPerKm`              | Cost per kilometer (fuel, maintenance, wear) | 0.0             | EUR/km   |
| `waitingCostPerHour`             | Cost of idle/waiting time                    | 0.0             | EUR/hour |
| `overtimeCostPerHour`            | Cost of overtime work                        | 50.0            | EUR/hour |
| `timeWindowViolationCostPerHour` | Penalty for missing time windows             | 20.0            | EUR/hour |
| `priorityCostPerPointPerHour`    | Cost per priority point per hour late        | 5.0             | EUR      |
| `preferredResourceViolationCost` | Penalty for not using preferred resource     | 20.0            | EUR      |
| `rankingViolationCostPerRank`    | Cost per rank deviation                      | 5.0             | EUR      |
| `resourceActivationCost`         | Fixed cost for using a resource              | (from resource) | EUR      |

### Cost Breakdown in Response

When using `costs`, the response includes a detailed financial breakdown:

```json theme={null}
{
  "score": {"hard": 0, "soft": -125000, "feasible": true},
  "trips": [...],
  "totalTravelTimeInSeconds": 7200,
  "totalTravelDistanceInMeters": 50000,
  "estimatedCost": {
    "totalCostEur": 85.25,
    "travelTimeCostEur": 50.00,
    "distanceCostEur": 17.50,
    "waitTimeCostEur": 3.75,
    "laborCostEur": 12.50,
    "activationCostEur": 0.00,
    "penaltyCostEur": 1.50
  }
}
```

## Cost Types Overview

The solver considers multiple cost components when optimizing routes:

<Info>
  **Total Cost = Fixed Costs + Variable Costs + Penalty Costs**

  * **Fixed Costs**: Activation costs for using resources
  * **Variable Costs**: Time-based costs (hourly rates, overtime), distance costs
  * **Penalty Costs**: Violations of soft constraints
</Info>

## Resource Cost Configuration

### Hourly Costs

Configure time-based costs for resources:

```json theme={null}
{
  "resources": [
    {
      "name": "employee-driver",
      "hourlyCost": 25,  // $25/hour
      "shifts": [{
        "from": "2024-03-15T08:00:00Z",
        "to": "2024-03-15T17:00:00Z"
      }]
    },
    {
      "name": "contractor-driver",
      "hourlyCost": 45,  // $45/hour
      "shifts": [{
        "from": "2024-03-15T08:00:00Z",
        "to": "2024-03-15T17:00:00Z"
      }]
    }
  ],
  "jobs": [
    {
      "name": "delivery-1",
      "duration": 1800
    }
  ]
}
```

<Tip>
  Hourly costs apply to the entire shift duration, not just driving time. Consider using activation costs if you only want to charge for actual usage.
</Tip>

### Activation Costs

Fixed costs incurred when a resource is used:

```json theme={null}
{
  "resources": [
    {
      "name": "rental-truck",
      "activationCost": 150,  // $150 fixed cost if used
      "hourlyCost": 0,      // No hourly charge
      "shifts": [{
        "from": "2024-03-15T08:00:00Z",
        "to": "2024-03-15T17:00:00Z"
      }]
    },
    {
      "name": "owned-vehicle",
      "activationCost": 50,   // $50 daily operating cost
      "hourlyCost": 15,      // $15/hour driver cost
      "shifts": [{
        "from": "2024-03-15T08:00:00Z",
        "to": "2024-03-15T17:00:00Z"
      }]
    }
  ],
  "jobs": [
    {
      "name": "job-1",
      "duration": 1800
    }
  ]
}
```

### Cost Calculation Examples

<Tabs>
  <Tab title="Employee Model">
    ```json theme={null}
    {
      "name": "full-time-driver",
      "hourlyCost": 30,
      "activationCost": 0
    }
    ```

    **8-hour shift cost**: 8 × $30 = $240
    **Used or not**: Same cost (salaried)
  </Tab>

  <Tab title="Contractor Model">
    ```json theme={null}
    {
      "name": "gig-driver",
      "hourlyCost": 40,
      "activationCost": 25
    }
    ```

    **5-hour usage**: $25 + (5 × $40) = \$225
    **Incentive**: Use fewer contractors
  </Tab>

  <Tab title="Rental Model">
    ```json theme={null}
    {
      "name": "rental-van",
      "hourlyCost": 0,
      "activationCost": 200
    }
    ```

    **Any usage**: Flat \$200
    **Strategy**: Maximize utilization once activated
  </Tab>
</Tabs>

## Travel Cost Optimization

### Using Cost-Based Configuration (Recommended)

The easiest way to optimize travel costs is using the `costs` configuration:

```json theme={null}
{
  "costs": {
    "drivingCostPerHour": 25.0,
    "distanceCostPerKm": 0.35
  }
}
```

This example says:

* Every hour of driving costs 25 EUR (driver wages, opportunity cost)
* Every kilometer driven costs 0.35 EUR (fuel, maintenance, depreciation)

The solver will balance both time and distance to minimize total cost.

<Tip>
  **Typical cost values:**

  * Driving cost: 20-40 EUR/hour (depending on driver wages)
  * Distance cost: 0.25-0.50 EUR/km (depending on vehicle type)
  * Small city car: \~0.25 EUR/km
  * Delivery van: \~0.35 EUR/km
  * Heavy truck: \~0.50 EUR/km
</Tip>

### Using Weight-Based Configuration (Advanced)

For fine-grained control, use the weights configuration:

```json theme={null}
{
  "weights": {
    "travelTimeWeight": 1,
    "waitTimeWeight": 0
  }
}
```

<ParamField path="travelTimeWeight" type="number" default="1">
  Multiplier for travel time in the objective function. Higher values prioritize shorter travel times.
</ParamField>

### Balancing Travel vs Other Objectives

<CodeGroup>
  ```json Minimize Travel theme={null}
  {
    "weights": {
      "travelTimeWeight": 10.0,
      "waitTimeWeight": 1.0,
      "urgencyWeight": 1.0
    }
  }
  ```

  ```json Balanced Approach theme={null}
  {
    "weights": {
      "travelTimeWeight": 1.0,
      "waitTimeWeight": 1.0,
      "urgencyWeight": 5.0
    }
  }
  ```

  ```json Priority Focus theme={null}
  {
    "weights": {
      "travelTimeWeight": 0.5,
      "waitTimeWeight": 0.5,
      "urgencyWeight": 20.0
    }
  }
  ```
</CodeGroup>

## Urgency-Based Optimization

### Basic Urgency Scoring

Prioritize time-sensitive jobs:

```json theme={null}
{
  "jobs": [
    {
      "name": "critical-repair",
      "urgency": 100,  // Highest priority
      "location": {"latitude": 52.520, "longitude": 13.405},
      "duration": 3600
    },
    {
      "name": "routine-maintenance",
      "urgency": 10,   // Lower priority
      "location": {"latitude": 52.520, "longitude": 13.405},
      "duration": 1800
    }
  ],
  "resources": [
    {
      "name": "technician-1",
      "shifts": [{
        "from": "2024-03-15T08:00:00Z",
        "to": "2024-03-15T17:00:00Z"
      }]
    }
  ],
  "weights": {
    "urgencyWeight": 50  // Strong urgency preference
  }
}
```

<ParamField path="urgency" type="integer" default="0">
  Priority score from 0-100. Higher values are scheduled earlier.
</ParamField>

### Urgency Calculation Formula

<Note>
  **Urgency Impact = urgency × urgencyWeight × time\_until\_scheduled**

  This creates increasing pressure to schedule urgent jobs sooner.
</Note>

## ASAP Scheduling

Schedule jobs as soon as possible across multiple days:

```json theme={null}
{
  "jobs": [
    {
      "name": "flexible-task-1",
      "dayIndex": 0,  // Available from day 1
      "windows": [
        {"from": "2024-03-15T08:00:00Z", "to": "2024-03-15T17:00:00Z"},
        {"from": "2024-03-16T08:00:00Z", "to": "2024-03-16T17:00:00Z"},
        {"from": "2024-03-17T08:00:00Z", "to": "2024-03-17T17:00:00Z"}
      ]
    },
    {
      "name": "flexible-task-2",
      "dayIndex": 1,  // Available from day 2
      "windows": [
        {"from": "2024-03-16T08:00:00Z", "to": "2024-03-16T17:00:00Z"},
        {"from": "2024-03-17T08:00:00Z", "to": "2024-03-17T17:00:00Z"}
      ]
    }
  ],
  "resources": [
    {
      "name": "driver-1",
      "shifts": [
        {
          "from": "2024-03-15T08:00:00Z",
          "to": "2024-03-15T17:00:00Z"
        },
        {
          "from": "2024-03-16T08:00:00Z",
          "to": "2024-03-16T17:00:00Z"
        },
        {
          "from": "2024-03-17T08:00:00Z",
          "to": "2024-03-17T17:00:00Z"
        }
      ]
    }
  ],
  "weights": {
    "asapWeight": 100  // Strong ASAP preference
  }
}
```

### DayIndex Strategy

<Steps>
  <Step title="Set dayIndex">
    `dayIndex: 0` = available immediately
    `dayIndex: 1` = available from day 2
    `dayIndex: 2` = available from day 3
  </Step>

  <Step title="Configure Weight">
    Higher `asapWeight` = stronger preference for early scheduling
  </Step>

  <Step title="Combine with Urgency">
    ```json theme={null}
    {
      "urgency": 80,
      "dayIndex": 0
    }
    ```
  </Step>
</Steps>

## Optimization Strategies

### Strategy 1: Cost Minimization

Focus on reducing operational costs:

```json theme={null}
{
  "resources": [
    {
      "name": "efficient-vehicle",
      "hourlyCost": 20,
      "activationCost": 100,
      "capacity": [1000],
      "shifts": [{
        "from": "2024-03-15T08:00:00Z",
        "to": "2024-03-15T17:00:00Z"
      }]
    },
    {
      "name": "large-vehicle",
      "hourlyCost": 35,
      "activationCost": 150,
      "capacity": [2000],
      "shifts": [{
        "from": "2024-03-15T08:00:00Z",
        "to": "2024-03-15T17:00:00Z"
      }]
    }
  ],
  "jobs": [
    {
      "name": "delivery-1",
      "load": [800]
    }
  ],
  "weights": {
    "travelTimeWeight": 0.5,  // Less important
    "activationWeight": 2.0   // Minimize vehicle use
  }
}
```

### Strategy 2: Service Level Optimization

Prioritize customer satisfaction:

```json theme={null}
{
  "resources": [
    {
      "name": "technician-1",
      "shifts": [{
        "from": "2024-03-15T08:00:00Z",
        "to": "2024-03-15T17:00:00Z"
      }]
    }
  ],
  "jobs": [
    {
      "name": "service-1",
      "urgency": 90,
      "duration": 3600
    }
  ],
  "weights": {
    "urgencyWeight": 100,        // Honor priorities
    "windowWeight": 50,          // Meet time preferences
    "waitTimeWeight": 20,        // Minimize customer waiting
    "preferredResourceWeight": 30 // Use preferred technicians
  }
}
```

### Strategy 3: Balanced Optimization

```json theme={null}
{
  "resources": [
    {
      "name": "driver-1",
      "shifts": [{
        "from": "2024-03-15T08:00:00Z",
        "to": "2024-03-15T17:00:00Z"
      }]
    }
  ],
  "jobs": [
    {
      "name": "job-1",
      "duration": 1800
    }
  ],
  "weights": {
    // Cost factors
    "travelTimeWeight": 1.0,
    "activationWeight": 1.0,
    "overtimeWeight": 50,
    
    // Service factors
    "urgencyWeight": 10,
    "windowWeight": 10,
    
    // Fairness factors
    "fairWorkloadPerResource": 5,
    "fairWorkloadPerTrip": 5
  }
}
```

## Cost Analysis in Results

When using the `costs` configuration, the response includes a detailed `estimatedCost` breakdown:

```json theme={null}
{
  "score": {"hard": 0, "soft": -125000, "feasible": true},
  "trips": [...],
  "totalTravelTimeInSeconds": 14400,
  "totalTravelDistanceInMeters": 120000,
  "estimatedCost": {
    "totalCostEur": 245.75,
    "travelTimeCostEur": 100.00,
    "distanceCostEur": 42.00,
    "waitTimeCostEur": 8.25,
    "laborCostEur": 75.00,
    "activationCostEur": 20.00,
    "penaltyCostEur": 0.50
  }
}
```

<Note>
  The `estimatedCost` field is only included when you provide a `costs` configuration in the request.
</Note>

### Understanding Cost Components

<Accordion title="Fixed Costs">
  * Resource activation costs
  * Daily vehicle fees
  * Equipment rental charges
  * Base operating costs
</Accordion>

<Accordion title="Variable Costs">
  * Hourly labor costs
  * Fuel costs (via travel time)
  * Overtime premiums
  * Distance-based charges
</Accordion>

<Accordion title="Penalty Costs">
  * Soft time window violations
  * Preference violations
  * Workload imbalance penalties
  * Capacity overages (if allowed)
</Accordion>

## Advanced Cost Scenarios

### Peak Hour Pricing

Different costs for different times:

```json theme={null}
{
  "resources": [
    {
      "name": "peak-driver",
      "shifts": [
        {
          "from": "2024-03-15T06:00:00Z",
          "to": "2024-03-15T10:00:00Z",
          "hourlyCost": 35  // Morning peak rate
        },
        {
          "from": "2024-03-15T10:00:00Z",
          "to": "2024-03-15T15:00:00Z",
          "hourlyCost": 25  // Standard rate
        },
        {
          "from": "2024-03-15T15:00:00Z",
          "to": "2024-03-15T19:00:00Z",
          "hourlyCost": 35  // Evening peak rate
        }
      ]
    }
  ],
  "jobs": [
    {
      "name": "delivery-1", 
      "duration": 1800
    }
  ]
}
```

### Multi-Objective Optimization

Balance competing objectives:

```json theme={null}
{
  "options": {
    "objectives": [
      {
        "name": "minimize_cost",
        "weights": {
          "travelTimeWeight": 1.0,
          "activationWeight": 2.0
        }
      },
      {
        "name": "maximize_service",
        "weights": {
          "urgencyWeight": 100,
          "windowWeight": 50
        }
      }
    ],
    "objectiveBalance": 0.6  // 60% cost, 40% service
  }
}
```

## Performance Tips

<Warning>
  **Cost Calculation Performance:**

  * Complex cost models increase computation time
  * Many soft constraints require more iterations
  * Large weight differences can cause instability

  **Recommendations:**

  * Keep weights in reasonable ratios (1:100 max)
  * Use hard constraints where possible
  * Profile different weight combinations
</Warning>

## Best Practices

<Steps>
  <Step title="Start with Defaults">
    Begin with default weights and adjust based on results
  </Step>

  <Step title="Measure Impact">
    Track these metrics:

    * Total operational cost
    * Cost per delivery/service
    * Resource utilization rates
    * Customer satisfaction scores
  </Step>

  <Step title="Iterate and Refine">
    * Adjust weights based on business priorities
    * Monitor unintended consequences
    * Document weight configurations
  </Step>

  <Step title="Consider Trade-offs">
    * Lower costs vs better service
    * Fewer vehicles vs more overtime
    * Urgency vs efficiency
  </Step>
</Steps>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Unexpected High Costs">
    **Check:**

    * Overtime penalties being triggered
    * Excessive activation of resources
    * Long travel times due to poor clustering
    * Soft constraint violations

    **Solutions:**

    * Review shift definitions
    * Adjust activation costs
    * Modify territory assignments
    * Convert critical soft constraints to hard
  </Accordion>

  <Accordion title="Poor Route Quality">
    **Check:**

    * Weight balance between objectives
    * Conflicting constraints
    * Insufficient resources

    **Solutions:**

    * Reduce focus on cost minimization
    * Increase service-related weights
    * Add resources or extend shifts
  </Accordion>

  <Accordion title="Urgency Not Respected">
    **Check:**

    * urgencyWeight value
    * Competing objectives
    * Time window conflicts

    **Solutions:**

    * Increase urgencyWeight significantly
    * Reduce other weight values
    * Review job time windows
  </Accordion>
</AccordionGroup>

## Related Features

<CardGroup cols={2}>
  <Card title="Resource Management" icon="users" href="/guides/vrp/features/resource-management">
    Configure resource costs and constraints
  </Card>

  <Card title="Time Windows" icon="clock" href="/guides/vrp/features/time-scheduling-advanced">
    Balance costs with time constraints
  </Card>

  <Card title="Workload Balancing" icon="balance-scale" href="/guides/vrp/features/fairness">
    Fair distribution vs cost optimization
  </Card>

  <Card title="Scoring System" icon="chart-line" href="/guides/vrp/concepts/scoring-explanation">
    How costs affect solution scoring
  </Card>
</CardGroup>
