> ## 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.

# VRP Constraint System

> Understanding how constraints shape and optimize your routing solutions

# VRP Constraint System

The Vehicle Routing Problem solver uses a sophisticated constraint system to transform business rules into optimized routes. This guide explains the fundamental concepts, types of constraints, and how they work together to create feasible and efficient solutions.

## What Are Constraints?

Constraints are rules that define what makes a valid solution. They represent real-world limitations and preferences:

```mermaid theme={null}
flowchart LR
    subgraph "Business Rules"
        A["'Deliver by 5 PM'"]
        B["'Max 8 hours driving'"]
        C["'Prefer senior techs'"]
    end
    
    subgraph "Constraints"
        D["Time Window Constraint"]
        E["Drive Time Constraint"]
        F["Ranking Soft Constraint"]
    end
    
    subgraph "Solution"
        G["Routes respect deadlines"]
        H["Legal compliance"]
        I["Optimized assignments"]
    end
    
    A --> D --> G
    B --> E --> H
    C --> F --> I
    
    style A fill:#e1f5fe
    style B fill:#e1f5fe
    style C fill:#e1f5fe
    style D fill:#fff3e0
    style E fill:#fff3e0
    style F fill:#fff3e0
    style G fill:#e8f5e9
    style H fill:#e8f5e9
    style I fill:#e8f5e9
```

## Constraint Hierarchy

The VRP solver organizes constraints into three levels:

### 1. Hard Constraints (Mandatory)

Must be satisfied for a feasible solution. Violations make the solution invalid.

<Tabs>
  <Tab title="Examples">
    * Vehicle capacity limits
    * Required time windows
    * Skill/equipment requirements
    * Legal driving limits
    * Shift boundaries
  </Tab>

  <Tab title="Configuration">
    ```json theme={null}
    {
      "job": {
        "windows": [{
          "from": "2024-03-15T09:00:00Z",
          "to": "2024-03-15T17:00:00Z",
          "hard": true  // Makes this mandatory
        }],
        "tags": [{
          "name": "electrical",
          "hard": true  // Required skill
        }]
      }
    }
    ```
  </Tab>

  <Tab title="Impact">
    * Score: -1000 per violation (typical)
    * Result: Solution marked infeasible
    * Priority: Solved first before any optimization
  </Tab>
</Tabs>

### 2. Medium Constraints (Important)

Should be satisfied but can be violated if necessary. Used for strong preferences.

<Info>
  Medium constraints are less common but useful for:

  * Overtime penalties (when overtime is allowed but discouraged)
  * Strong customer preferences
  * Priority job sequencing
</Info>

### 3. Soft Constraints (Optimize)

Preferences that improve solution quality. Always violated to some degree - the goal is minimization.

<Tabs>
  <Tab title="Examples">
    * Minimize travel time
    * Minimize wait time
    * Balance workload
    * Minimize vehicles used
    * Customer preferences
  </Tab>

  <Tab title="Configuration">
    ```json theme={null}
    {
      "options": {
        "weights": {
          "travelTimeWeight": 1,
          "waitTimeWeight": 10,
          "workloadSpreadWeight": 50
        }
      }
    }
    ```
  </Tab>

  <Tab title="Impact">
    * Score: Weighted penalties
    * Result: Quality optimization
    * Priority: Optimized after feasibility
  </Tab>
</Tabs>

## How Constraints Work

### Constraint Evaluation Process

<Steps>
  <Step title="Input Validation">
    The solver first validates that constraints are properly configured and compatible.
  </Step>

  <Step title="Initial Solution">
    Creates an initial solution, possibly violating many constraints.
  </Step>

  <Step title="Hard Constraint Resolution">
    Focuses on eliminating hard constraint violations through moves and swaps.
  </Step>

  <Step title="Soft Constraint Optimization">
    Once feasible, optimizes soft constraints while maintaining feasibility.
  </Step>

  <Step title="Continuous Improvement">
    Iteratively improves the solution until time limit or optimal solution is found.
  </Step>
</Steps>

### Constraint Interactions

Constraints often interact and conflict with each other:

<AccordionGroup>
  <Accordion title="Time Windows vs Travel Time">
    **Conflict**: Tight time windows may require more vehicles to minimize travel.

    **Resolution**: The solver balances based on weights:

    ```json theme={null}
    {
      "weights": {
        "minimizeResourcesWeight": 3600,  // High cost for extra vehicle
        "travelTimeWeight": 1  // Lower priority
      }
    }
    ```
  </Accordion>

  <Accordion title="Capacity vs Route Efficiency">
    **Conflict**: Optimal routes might exceed vehicle capacity.

    **Resolution**: Hard capacity constraints force route splits, soft constraints optimize the splits.
  </Accordion>

  <Accordion title="Skills vs Workload Balance">
    **Conflict**: Skilled resources may get overloaded.

    **Resolution**: Workload balancing weights compete with skill requirements:

    ```json theme={null}
    {
      "weights": {
        "workloadSpreadWeight": 100  // Strong preference for balance
      }
    }
    ```
  </Accordion>
</AccordionGroup>

## Built-in Constraints

The VRP solver includes many pre-configured constraints:

### Capacity Constraints

```mermaid theme={null}
flowchart LR
    A["Start<br/>0/1000kg"] --> B["Job 1: Pickup<br/>500/1000kg"]
    B --> C["Job 2: Pickup<br/>800/1000kg"]
    C --> D["Job 3: Delivery<br/>300/1000kg"]
    
    style A fill:#f0f4c3
    style B fill:#ffccbc
    style C fill:#ffab91
    style D fill:#c5e1a5
```

**Types**:

* Single dimension (weight OR volume)
* Multi-dimensional (weight AND volume AND count)
* Dynamic (changes with pickups/deliveries)

### Time Constraints

**Categories**:

* **Time Windows**: When jobs can be serviced
* **Shift Times**: When resources can work
* **Drive Time**: Maximum continuous driving
* **Service Duration**: How long jobs take

<Tip>
  Time constraints often cascade - arriving late at one job affects all subsequent jobs.
</Tip>

### Skill/Tag Constraints

Match job requirements with resource capabilities:

```json theme={null}
{
  "job": {
    "tags": [
      {"name": "plumbing", "hard": true},    // Must have
      {"name": "certified", "hard": false}   // Preferred
    ]
  },
  "resource": {
    "tags": ["plumbing", "electrical", "certified"]  // Has all needed tags
  }
}
```

### Relation Constraints

Define dependencies between jobs:

* **SEQUENCE**: Order matters, gaps allowed
* **SAME\_TRIP**: Must be on same route
* **PICKUP\_AND\_DELIVERY**: Paired operations
* **SAME\_TIME**: Synchronized arrival

## Constraint Configuration

### Weight System

Weights determine the relative importance of soft constraints:

<CodeGroup>
  ```json Default Weights theme={null}
  {
    "weights": {
      "travelTimeWeight": 1,
      "priorityWeight": 1,
      "workloadSpreadWeight": 1,
      "minimizeResourcesWeight": 1
    }
  }
  ```

  ```json Minimize Vehicles theme={null}
  {
    "weights": {
      "travelTimeWeight": 1,
      "minimizeResourcesWeight": 7200  // 2 hours of travel
    }
  }
  ```

  ```json Balanced Workload theme={null}
  {
    "weights": {
      "workloadSpreadWeight": 100,  // Very important
      "travelTimeWeight": 1
    }
  }
  ```
</CodeGroup>

### Weight Guidelines

<Warning>
  **Weight Setting Best Practices**:

  1. Start with defaults (all weights = 1)
  2. Identify underperforming objectives
  3. Increase weights by 5-10x to see impact
  4. Fine-tune based on results
  5. Document your weight choices
</Warning>

### Making Constraints Configurable

Design flexible constraints for different scenarios:

<Tabs>
  <Tab title="Flexible Time Windows">
    ```json theme={null}
    {
      "hardTimeWindow": {
        "from": "08:00",
        "to": "18:00",
        "hard": true
      },
      "preferredTimeWindow": {
        "from": "09:00",
        "to": "12:00",
        "hard": false,
        "weight": 50
      }
    }
    ```
  </Tab>

  <Tab title="Conditional Capacity">
    ```json theme={null}
    {
      "normalCapacity": [1000],
      "rushHourCapacity": [800],  // Reduced during traffic
      "overtimeCapacity": [1200]   // Can carry more with overtime
    }
    ```
  </Tab>

  <Tab title="Dynamic Skills">
    ```json theme={null}
    {
      "requiredSkills": ["basic-repair"],
      "preferredSkills": ["certified-tech", "senior-level"],
      "conditionalSkills": {
        "weekend": ["emergency-certified"],
        "night": ["security-cleared"]
      }
    }
    ```
  </Tab>
</Tabs>

## Constraint Patterns

### Pattern 1: Graceful Degradation

Start strict, then relax if needed:

<Steps>
  <Step title="Attempt Strict">
    ```json theme={null}
    {"partialPlanning": false, "timeWindows": {"hard": true}}
    ```
  </Step>

  <Step title="If Infeasible, Relax">
    ```json theme={null}
    {"partialPlanning": true, "timeWindows": {"hard": false, "weight": 100}}
    ```
  </Step>

  <Step title="Further Relaxation">
    ```json theme={null}
    {"partialPlanning": true, "timeWindows": {"hard": false, "weight": 10}}
    ```
  </Step>
</Steps>

### Pattern 2: Progressive Tightening

Start loose, then optimize:

```json theme={null}
// Phase 1: Get feasible solution
{
  "options": {
    "partialPlanning": true,
    "weights": {"minimizeResourcesWeight": 1}
  }
}

// Phase 2: Optimize quality
{
  "options": {
    "partialPlanning": false,
    "weights": {"minimizeResourcesWeight": 3600}
  }
}
```

### Pattern 3: Multi-Objective Balancing

Balance competing objectives:

```json theme={null}
{
  "weights": {
    "travelTimeWeight": 1,        // Baseline
    "workloadSpreadWeight": 20,   // Important
    "urgencyWeight": 50,          // More important
    "priorityWeight": 100         // Most important
  }
}
```

## Performance Impact

Different constraints have varying computational costs:

### Low Impact

* Basic capacity checks
* Simple time windows
* Fixed assignments

### Medium Impact

* Multi-dimensional capacity
* Overlapping time windows
* Skill matching

### High Impact

* Complex job relations
* Many soft constraints
* Fine-grained time slots

<Tip>
  **Performance Optimization**:

  1. Use hard constraints sparingly
  2. Combine related soft constraints
  3. Set reasonable time windows
  4. Limit job relations complexity
  5. Use appropriate solve time limits
</Tip>

## Debugging Constraints

When solutions aren't meeting expectations:

<Steps>
  <Step title="Check Feasibility">
    ```bash theme={null}
    # Get explanation
    GET /v2/vrp/jobs/{id}/explanation
    ```

    Look for hard constraint violations first.
  </Step>

  <Step title="Analyze Weights">
    Compare soft constraint scores to understand trade-offs.
  </Step>

  <Step title="Test Incrementally">
    Add constraints one at a time to identify conflicts.
  </Step>

  <Step title="Use Partial Planning">
    Allow some jobs to be unassigned to understand bottlenecks.
  </Step>
</Steps>

## Best Practices

<Check>
  **Constraint Design Guidelines**:

  1. **Start Simple**: Begin with essential hard constraints only
  2. **Validate Early**: Test feasibility with a subset of data
  3. **Document Rules**: Explain why each constraint exists
  4. **Monitor Impact**: Track how constraints affect solution quality
  5. **Iterate**: Refine based on real-world results
  6. **Balance**: Avoid over-constraining - flexibility enables optimization
</Check>

## Related Topics

<CardGroup cols={2}>
  <Card title="Scoring System" icon="star" href="/guides/vrp/concepts/scoring-explanation">
    Deep dive into score calculation
  </Card>

  <Card title="Advanced Constraints" icon="cog" href="/guides/vrp/features/advanced-constraints">
    Specific constraint features
  </Card>

  <Card title="Performance Guide" icon="gauge" href="/guides/vrp/concepts/performance-guide">
    Optimize constraint performance
  </Card>

  <Card title="Unassigned Reasons" icon="lightbulb" href="/guides/vrp/features/unassigned-reasons">
    Debug constraint violations
  </Card>
</CardGroup>
