Skip to main content

Matrix

Struct Matrix 

Source
pub struct Matrix { /* private fields */ }
Expand description

Dense square matrix of travel costs between units.

Implementations§

Source§

impl Matrix

Source

pub fn from_vec(n: usize, data: Vec<f64>) -> Result<Self, String>

Build from a row-major vector of length n * n.

Examples found in repository?
examples/benchmark.rs (line 137)
102fn main() {
103    let args: Vec<String> = std::env::args().collect();
104    let dir = args.get(1).expect("directory with instances");
105    let iterations: usize = args.get(2).and_then(|v| v.parse().ok()).unwrap_or(2000);
106    let time_limit: f64 = args
107        .get(3)
108        .and_then(|v| v.parse().ok())
109        .unwrap_or(f64::INFINITY);
110    let mut files: Vec<_> = std::fs::read_dir(dir)
111        .expect("read dir")
112        .filter_map(|e| e.ok().map(|e| e.path()))
113        .filter(|p| {
114            matches!(
115                p.extension().and_then(|e| e.to_str()),
116                Some("tsp") | Some("vrp")
117            )
118        })
119        .collect();
120    files.sort();
121    println!(
122        "{:<12} {:>5} {:>7} {:>9} {:>9} {:>7} {:>8} {:>6}",
123        "instance", "n", "routes", "cost", "optimum", "gap%", "bound%", "sec"
124    );
125    for f in files {
126        let p = parse(&f);
127        let n = p.coords.len();
128        let mut data = vec![0.0; n * n];
129        for i in 0..n {
130            for j in 0..n {
131                let d = ((p.coords[i].0 - p.coords[j].0).powi(2)
132                    + (p.coords[i].1 - p.coords[j].1).powi(2))
133                .sqrt();
134                data[i * n + j] = d.round();
135            }
136        }
137        let m = Matrix::from_vec(n, data).unwrap();
138        let units: Vec<usize> = (0..n).filter(|&i| i != p.depot).collect();
139        let limits = RouteLimits {
140            max_length: f64::INFINITY,
141            max_stops: usize::MAX,
142            capacity: p.capacity,
143        };
144        let options = GraspOptions {
145            iterations,
146            time_limit,
147            alpha: 0.3,
148            seed: 1,
149        };
150        let start = Instant::now();
151        let sol = solve_routes(&m, p.depot, &units, &[], &p.demand, limits, options).unwrap();
152        let secs = start.elapsed().as_secs_f64();
153        let gap = p.optimum.map(|o| 100.0 * (sol.total - o) / o);
154        let bound_gap = 100.0 * (sol.total - sol.lower_bound) / sol.total;
155        println!(
156            "{:<12} {:>5} {:>7} {:>9.0} {:>9} {:>7} {:>8.2} {:>6.1}",
157            p.name,
158            units.len(),
159            sol.routes.len(),
160            sol.total,
161            p.optimum.map_or("?".to_string(), |o| format!("{o:.0}")),
162            gap.map_or("?".to_string(), |g| format!("{g:.2}")),
163            bound_gap,
164            secs
165        );
166    }
167}
Source

pub fn len(&self) -> usize

Number of units.

Source

pub fn is_empty(&self) -> bool

Whether the matrix is empty.

Source

pub fn get(&self, i: usize, j: usize) -> f64

Travel cost from i to j.

Source

pub fn as_slice(&self) -> &[f64]

The underlying row-major data.

Trait Implementations§

Source§

impl Clone for Matrix

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Matrix

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for Matrix

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Matrix

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.