1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
//! This module provides functionality to automatically check that given solution is feasible
//! which means that there is no constraint violations.

#[cfg(test)]
#[path = "../../tests/unit/checker/checker_test.rs"]
mod checker_test;

use crate::format::problem::*;
use crate::format::solution::*;
use crate::format::Location;
use crate::parse_time;
use hashbrown::{HashMap, HashSet};
use std::sync::Arc;
use vrp_core::models::common::TimeWindow;
use vrp_core::models::Problem as CoreProblem;

/// Stores problem and solution together and provides some helper methods.
pub struct CheckerContext {
    /// An original problem definition.
    pub problem: Problem,
    /// Routing matrices.
    pub matrices: Option<Vec<Matrix>>,
    /// Solution to be checked
    pub solution: Solution,

    job_map: HashMap<String, Job>,
    core_problem: Arc<CoreProblem>,
}

/// Represents all possible activity types.
enum ActivityType {
    Terminal,
    Job(Box<Job>),
    Depot(VehicleDispatch),
    Break(VehicleBreak),
    Reload(VehicleReload),
}

impl CheckerContext {
    /// Creates an instance of `CheckerContext`
    pub fn new(
        core_problem: Arc<CoreProblem>,
        problem: Problem,
        matrices: Option<Vec<Matrix>>,
        solution: Solution,
    ) -> Self {
        let job_map = problem.plan.jobs.iter().map(|job| (job.id.clone(), job.clone())).collect();

        Self { problem, matrices, solution, job_map, core_problem }
    }

    /// Performs solution check.
    pub fn check(&self) -> Result<(), Vec<String>> {
        let errors = check_vehicle_load(&self)
            .err()
            .into_iter()
            .chain(check_relations(&self).err().into_iter())
            .chain(check_breaks(&self).err().into_iter())
            .chain(check_assignment(&self).err().into_iter())
            .chain(check_routing(&self).err().into_iter())
            .chain(check_limits(&self).err().into_iter())
            .flatten()
            .collect::<Vec<_>>();

        // avoid duplicates keeping original order
        let (_, errors) = errors.into_iter().fold((HashSet::new(), Vec::default()), |(mut used, mut errors), error| {
            if !used.contains(&error) {
                errors.push(error.clone());
                used.insert(error);
            }

            (used, errors)
        });

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Gets vehicle by its id.
    fn get_vehicle(&self, vehicle_id: &str) -> Result<&VehicleType, String> {
        self.problem
            .fleet
            .vehicles
            .iter()
            .find(|v| v.vehicle_ids.contains(&vehicle_id.to_string()))
            .ok_or_else(|| format!("cannot find vehicle with id '{}'", vehicle_id))
    }

    /// Gets activity operation time range in seconds since Unix epoch.
    fn get_activity_time(&self, stop: &Stop, activity: &Activity) -> TimeWindow {
        let time = activity
            .time
            .clone()
            .unwrap_or_else(|| Interval { start: stop.time.arrival.clone(), end: stop.time.departure.clone() });

        TimeWindow::new(parse_time(&time.start), parse_time(&time.end))
    }

    /// Gets activity location.
    fn get_activity_location(&self, stop: &Stop, activity: &Activity) -> Location {
        activity.location.clone().unwrap_or_else(|| stop.location.clone())
    }

    /// Gets vehicle shift where activity is used.
    fn get_vehicle_shift(&self, tour: &Tour) -> Result<VehicleShift, String> {
        let tour_time = TimeWindow::new(
            parse_time(
                &tour.stops.first().as_ref().ok_or_else(|| "cannot get first activity".to_string())?.time.arrival,
            ),
            parse_time(&tour.stops.last().as_ref().ok_or_else(|| "cannot get last activity".to_string())?.time.arrival),
        );

        self.get_vehicle(&tour.vehicle_id)?
            .shifts
            .iter()
            .find(|shift| {
                let shift_time = TimeWindow::new(
                    parse_time(&shift.start.earliest),
                    shift.end.as_ref().map_or_else(|| f64::MAX, |place| parse_time(&place.latest)),
                );
                shift_time.intersects(&tour_time)
            })
            .cloned()
            .ok_or_else(|| format!("cannot find shift for tour with vehicle if: '{}'", tour.vehicle_id))
    }

    /// Returns stop's activity type names.
    fn get_stop_activity_types(&self, stop: &Stop) -> Vec<String> {
        stop.activities.iter().map(|a| a.activity_type.clone()).collect()
    }

    /// Gets wrapped activity type.
    fn get_activity_type(&self, tour: &Tour, stop: &Stop, activity: &Activity) -> Result<ActivityType, String> {
        let shift = self.get_vehicle_shift(tour)?;
        let time = self.get_activity_time(stop, activity);
        let location = self.get_activity_location(stop, activity);

        match activity.activity_type.as_str() {
            "departure" | "arrival" => Ok(ActivityType::Terminal),
            "pickup" | "delivery" | "service" | "replacement" => {
                self.job_map.get(activity.job_id.as_str()).map_or_else(
                    || Err(format!("cannot find job with id '{}'", activity.job_id)),
                    |job| Ok(ActivityType::Job(Box::new(job.clone()))),
                )
            }
            "break" => shift
                .breaks
                .as_ref()
                .and_then(|breaks| {
                    breaks.iter().find(|b| match &b.time {
                        VehicleBreakTime::TimeWindow(tw) => parse_time_window(tw).intersects(&time),
                        VehicleBreakTime::TimeOffset(offset) => {
                            assert_eq!(offset.len(), 2);
                            // NOTE make expected time window wider due to reschedule departure
                            let stops = &tour.stops;
                            let start = parse_time(&stops.first().unwrap().time.arrival) + *offset.first().unwrap();
                            let end = parse_time(&stops.first().unwrap().time.departure) + *offset.last().unwrap();

                            TimeWindow::new(start, end).intersects(&time)
                        }
                    })
                })
                .map(|b| ActivityType::Break(b.clone()))
                .ok_or_else(|| format!("cannot find break for tour '{}'", tour.vehicle_id)),
            "reload" => shift
                .reloads
                .as_ref()
                // TODO match reload's time windows
                .and_then(|reload| reload.iter().find(|r| r.location == location && r.tag == activity.job_tag))
                .map(|r| ActivityType::Reload(r.clone()))
                .ok_or_else(|| format!("cannot find reload for tour '{}'", tour.vehicle_id)),
            "dispatch" => shift
                .dispatch
                .as_ref()
                .and_then(|dispatch| dispatch.iter().find(|d| d.location == location))
                .map(|d| ActivityType::Depot(d.clone()))
                .ok_or_else(|| format!("cannot find dispatch for tour '{}'", tour.vehicle_id)),
            _ => Err(format!("unknown activity type: '{}'", activity.activity_type)),
        }
    }

    fn get_job_by_id(&self, job_id: &str) -> Option<&Job> {
        self.problem.plan.jobs.iter().find(|job| job.id == job_id)
    }

    fn visit_job<F1, F2, R>(
        &self,
        activity: &Activity,
        activity_type: &ActivityType,
        job_visitor: F1,
        other_visitor: F2,
    ) -> Result<R, String>
    where
        F1: Fn(&Job, &JobTask) -> R,
        F2: Fn() -> R,
    {
        match activity_type {
            ActivityType::Job(job) => {
                let pickups = job_task_size(&job.pickups);
                let deliveries = job_task_size(&job.deliveries);
                let tasks = pickups + deliveries + job_task_size(&job.services) + job_task_size(&job.replacements);

                if tasks < 2 || (tasks == 2 && pickups == 1 && deliveries == 1) {
                    match_job_task(activity.activity_type.as_str(), job, |tasks| tasks.first())
                } else {
                    activity.job_tag.as_ref().ok_or_else(|| {
                        format!("checker requires that multi job activity must have tag: '{}'", activity.job_id)
                    })?;

                    match_job_task(activity.activity_type.as_str(), job, |tasks| {
                        tasks.iter().find(|task| task.tag == activity.job_tag)
                    })
                }
                .map(|task| job_visitor(job, task))
            }
            .ok_or_else(|| "cannot match activity to job place".to_string()),
            _ => Ok(other_visitor()),
        }
    }
}

fn job_task_size(tasks: &Option<Vec<JobTask>>) -> usize {
    tasks.as_ref().map_or(0, |p| p.len())
}

fn match_job_task<'a>(
    activity_type: &str,
    job: &'a Job,
    tasks_fn: impl Fn(&'a Vec<JobTask>) -> Option<&'a JobTask>,
) -> Option<&'a JobTask> {
    let tasks = match activity_type {
        "pickup" => job.pickups.as_ref(),
        "delivery" => job.deliveries.as_ref(),
        "service" => job.services.as_ref(),
        "replacement" => job.replacements.as_ref(),
        _ => None,
    };

    tasks.and_then(|tasks| tasks_fn(tasks))
}

fn parse_time_window(tw: &[String]) -> TimeWindow {
    TimeWindow::new(parse_time(tw.first().unwrap()), parse_time(tw.last().unwrap()))
}

fn get_time_window(stop: &Stop, activity: &Activity) -> TimeWindow {
    let (start, end) = activity
        .time
        .as_ref()
        .map_or_else(|| (&stop.time.arrival, &stop.time.departure), |interval| (&interval.start, &interval.end));

    TimeWindow::new(parse_time(start), parse_time(end))
}

fn get_location(stop: &Stop, activity: &Activity) -> Location {
    activity.location.as_ref().unwrap_or(&stop.location).clone()
}

mod assignment;
use crate::checker::assignment::check_assignment;

mod capacity;
use crate::checker::capacity::check_vehicle_load;

mod limits;
use crate::checker::limits::check_limits;

mod breaks;
use crate::checker::breaks::check_breaks;

mod relations;
use crate::checker::relations::check_relations;

mod routing;
use crate::checker::routing::check_routing;