<commit_before>use lerp;

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

pub fn noise(x: f32, y: f32, z: f32) -> f32 {
    // Compute noise cell coordinates and offsets
    let mut ix = x.floor() as usize;
    let mut iy = x.floor() as usize;
    let mut iz = x.floor() as usize;
    let dx = x - ix as f32;
    let dy = y - iy as f32;
    let dz = z - iz as f32;

    // Compute gradient weights
    ix &= NOISE_PERM_SIZE - 1;
    iy &= NOISE_PERM_SIZE - 1;
    iz &= NOISE_PERM_SIZE - 1;
    let w000 = grad(ix, iy, iz, dx, dy, dz);
    let w100 = grad(ix + 1, iy, iz, dx - 1.0, dy, dz);
    let w010 = grad(ix, iy + 1, iz, dx, dy - 1.0, dz);
    let w110 = grad(ix + 1, iy + 1, iz, dx - 1.0, dy - 1.0, dz);
    let w001 = grad(ix, iy, iz + 1, dx, dy, dz - 1.0);
    let w101 = grad(ix + 1, iy, iz + 1, dx - 1.0, dy, dz - 1.0);
    let w011 = grad(ix, iy + 1, iz + 1, dx, dy - 1.0, dz - 1.0);
    let w111 = grad(ix + 1, iy + 1, iz + 1, dx - 1.0, dy - 1.0, dz - 1.0);

    // Compute trilinear interpolation of weights
    let wx = noise_weight(dx);
    let wy = noise_weight(dy);
    let wz = noise_weight(dz);
    let x00 = lerp(wx, w000, w100);
    let x10 = lerp(wx, w010, w110);
    let x01 = lerp(wx, w001, w101);
    let x11 = lerp(wx, w011, w111);
    let y0 = lerp(wy, x00, x10);
    let y1 = lerp(wy, x10, x11);

    lerp(wz, y0, y1)
}

#[inline]
fn grad(x: usize, y: usize, z: usize, dx: f32, dy: f32, dz: f32) -> f32 {
    let mut h = NOISE_PERM[NOISE_PERM[NOISE_PERM[x as usize] + y as usize] + z as usize];
    h &= 15;
    let u = if h < 8 || h == 12 || h == 13 { dx } else { dy };
    let v = if h < 4 || h == 12 || h == 13 { dy } else { dz };

    (if h & 1 != 0 { -u } else { u }) + (if h & 2 != 0 { -v } else { v })
}

#[inline]
fn noise_weight(t: f32) -> f32 {
    let t3 = t * t * t;
    let t4 = t3 * t;
    6.0 * t4 * t - 15.0 * t4 + 10.0 * t3
}
<commit_msg>Add Fractional Brownian Motion (FBm) noise function<commit_after>use na::{clamp, Norm};

use {lerp, Point3f, Vector3f};

/// Perlin noise
pub fn noise3(p: &Point3f) -> f32 {
    noise(p.x, p.y, p.z)
}

pub fn noise(x: f32, y: f32, z: f32) -> f32 {
    // Compute noise cell coordinates and offsets
    let mut ix = x.floor() as usize;
    let mut iy = x.floor() as usize;
    let mut iz = x.floor() as usize;
    let dx = x - ix as f32;
    let dy = y - iy as f32;
    let dz = z - iz as f32;

    // Compute gradient weights
    ix &= NOISE_PERM_SIZE - 1;
    iy &= NOISE_PERM_SIZE - 1;
    iz &= NOISE_PERM_SIZE - 1;
    let w000 = grad(ix, iy, iz, dx, dy, dz);
    let w100 = grad(ix + 1, iy, iz, dx - 1.0, dy, dz);
    let w010 = grad(ix, iy + 1, iz, dx, dy - 1.0, dz);
    let w110 = grad(ix + 1, iy + 1, iz, dx - 1.0, dy - 1.0, dz);
    let w001 = grad(ix, iy, iz + 1, dx, dy, dz - 1.0);
    let w101 = grad(ix + 1, iy, iz + 1, dx - 1.0, dy, dz - 1.0);
    let w011 = grad(ix, iy + 1, iz + 1, dx, dy - 1.0, dz - 1.0);
    let w111 = grad(ix + 1, iy + 1, iz + 1, dx - 1.0, dy - 1.0, dz - 1.0);

    // Compute trilinear interpolation of weights
    let wx = noise_weight(dx);
    let wy = noise_weight(dy);
    let wz = noise_weight(dz);
    let x00 = lerp(wx, w000, w100);
    let x10 = lerp(wx, w010, w110);
    let x01 = lerp(wx, w001, w101);
    let x11 = lerp(wx, w011, w111);
    let y0 = lerp(wy, x00, x10);
    let y1 = lerp(wy, x10, x11);

    lerp(wz, y0, y1)
}

/// Fractional Brownian Motion
pub fn fbm(p: &Point3f,
           dpdx: &Vector3f,
           dpdy: &Vector3f,
           dpdz: &Vector3f,
           omega: f32,
           max_octaves: u32)
           -> f32 {
    // Compute number of octaves for antialiased FBm
    let len2 = dpdx.norm_squared().max(dpdy.norm_squared());
    let n = clamp(-1.0 - 0.5 * len2.log2(), 0.0, max_octaves as f32);
    let n_int = n.floor() as u32;

    // Compute sum of octaves of noise for FBm
    let mut sum = 0.0;
    let mut lambda = 1.0;
    let mut o = 1.0;
    for i in 0..n_int {
        sum += o * noise3(&(lambda * *p));
        lambda *= 1.99;
        o *= omega;
    }
    let n_partial = n - n_int as f32;
    sum += o * smooth_step(0.3, 0.7, n_partial) * noise3(&(lambda * *p));

    sum
}

#[inline]
fn grad(x: usize, y: usize, z: usize, dx: f32, dy: f32, dz: f32) -> f32 {
    let mut h = NOISE_PERM[NOISE_PERM[NOISE_PERM[x as usize] + y as usize] + z as usize];
    h &= 15;
    let u = if h < 8 || h == 12 || h == 13 { dx } else { dy };
    let v = if h < 4 || h == 12 || h == 13 { dy } else { dz };

    (if h & 1 != 0 { -u } else { u }) + (if h & 2 != 0 { -v } else { v })
}

#[inline]
fn noise_weight(t: f32) -> f32 {
    let t3 = t * t * t;
    let t4 = t3 * t;
    6.0 * t4 * t - 15.0 * t4 + 10.0 * t3
}

#[inline]
fn smooth_step(min: f32, max: f32, value: f32) -> f32 {
    let v = clamp((value - min) / (max - min), 0.0, 1.0);

    v * v * (-2.0 * v + 3.0)
}

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


<commit_before>use std::cmp::{self, Ordering};
use std::f32;
use std::convert::From;
use rand::Rng;
use std::ops::Sub;

pub trait Mate<T> {
    fn mate(&mut self, p1: &T, p2: &T) -> T;
}

pub trait Dominate<Rhs=Self> {
    fn dominates(&self, other: &Rhs) -> bool;
}

fn dominates_slices<T: Sized + PartialOrd>(sa: &[T], sb: &[T]) -> bool {
    assert!(sa.len() == sb.len());
    assert!(sa.len() > 0);

    let mut less_cnt = 0;
    for (a, b) in sa.iter().zip(sb.iter()) {
        if a > b {
            return false;
        } else if a < b {
            less_cnt += 1;
        }
    }

    return less_cnt > 0;
}

pub trait MultiObjective {
    fn num_objectives() -> usize;

    fn cmp_objective(&self, other: &Self, objective: usize) -> Ordering;

    // Distance between self and other
    fn dist_objective(&self, other: &Self, objective: usize) -> f32;
}

#[derive(Debug, Clone)]
pub struct MultiObjective2<T>
    where T: Sized + PartialOrd + Copy + Clone
{
    objectives: [T; 2],
}

impl<T:Sized+PartialOrd+Copy+Clone> From<(T, T)> for MultiObjective2<T> {
    fn from(t: (T, T)) -> MultiObjective2<T> {
        MultiObjective2 { objectives: [t.0, t.1] }
    }
}

impl<T,R> MultiObjective for MultiObjective2<T>
where T: Copy + PartialOrd + Sub<Output=R>,
      R: Into<f32> {
    fn num_objectives() -> usize {
        2
    }
    fn cmp_objective(&self, other: &Self, objective: usize) -> Ordering {
        self.objectives[objective].partial_cmp(&other.objectives[objective]).unwrap()
    }
    fn dist_objective(&self, other: &Self, objective: usize) -> f32 {
        (self.objectives[objective] - other.objectives[objective]).into()
    }
}

impl<T:Sized+PartialOrd> Dominate for MultiObjective2<T> {
    fn dominates(&self, other: &Self) -> bool {
        dominates_slices(&self.objectives[..], &other.objectives[..])
    }
}

#[derive(Debug, Clone)]
pub struct MultiObjective3<T>
    where T: Sized + PartialOrd + Copy + Clone
{
    objectives: [T; 3],
}

impl<T:Sized+PartialOrd+Copy+Clone> From<(T, T, T)> for MultiObjective3<T> {
    fn from(t: (T, T, T)) -> MultiObjective3<T> {
        MultiObjective3 { objectives: [t.0, t.1, t.2] }
    }
}

impl<T,R> MultiObjective for MultiObjective3<T>
where T: Copy + PartialOrd + Sub<Output=R>,
      R: Into<f32> {
    fn num_objectives() -> usize {
        3
    }
    fn cmp_objective(&self, other: &Self, objective: usize) -> Ordering {
        self.objectives[objective].partial_cmp(&other.objectives[objective]).unwrap()
    }
    fn dist_objective(&self, other: &Self, objective: usize) -> f32 {
        (self.objectives[objective] - other.objectives[objective]).into()
    }
}

impl<T:Sized+PartialOrd> Dominate for MultiObjective3<T> {
    fn dominates(&self, other: &Self) -> bool {
        dominates_slices(&self.objectives[..], &other.objectives[..])
    }
}

/// Stop after we have found `n` solutions (we include the whole pareto front, so it are probably more solutions).
fn fast_non_dominated_sort<P: Dominate>(solutions: &[P], n: usize) -> Vec<Vec<usize>> {
    let mut fronts: Vec<Vec<usize>> = Vec::new();
    let mut current_front = Vec::new();

    let mut domination_count: Vec<usize> = (0..solutions.len()).map(|_| 0).collect();
    let mut dominated_solutions: Vec<Vec<usize>> = (0..solutions.len())
                                                       .map(|_| Vec::new())
                                                       .collect();
    let mut found_solutions: usize = 0;

    for (i, p) in solutions.iter().enumerate() {
        for (j, q) in solutions.iter().enumerate() {
            if i == j {
                continue;
            }
            if p.dominates(q) {
                // Add `q` to the set of solutions dominated by `p`.
                dominated_solutions[i].push(j);
            } else if q.dominates(p) {
                // Increment domination counter of `p`.
                domination_count[i] += 1;
            }
        }

        if domination_count[i] == 0 {
            // `p` belongs to the first front as it is not dominated by any
            // other solution.
            current_front.push(i);
        }
    }

    while !current_front.is_empty() {
        found_solutions += current_front.len();
        if found_solutions >= n {
            fronts.push(current_front);
            break;
        } else {
            // we haven't found enough solutions yet.
            let mut next_front = Vec::new();
            for &p_i in current_front.iter() {
                for &q_i in dominated_solutions[p_i].iter() {
                    domination_count[q_i] -= 1;
                    if domination_count[q_i] == 0 {
                        // q belongs to the next front
                        next_front.push(q_i);
                    }
                }
            }
            fronts.push(current_front);
            current_front = next_front;
        }
    }

    return fronts;
}

#[derive(Debug)]
pub struct SolutionRankDist {
    pub idx: usize,
    pub rank: u32,
    pub dist: f32,
}

impl PartialEq for SolutionRankDist {
    #[inline]
    fn eq(&self, other: &SolutionRankDist) -> bool {
        self.rank == other.rank && self.dist == other.dist
    }
}

// Implement the crowding-distance comparison operator.
impl PartialOrd for SolutionRankDist {
    #[inline]
    // compare on rank first (ASC), then on dist (DESC)
    fn partial_cmp(&self, other: &SolutionRankDist) -> Option<Ordering> {
        match self.rank.partial_cmp(&other.rank) {
            Some(Ordering::Equal) => {
                // first criterion equal, second criterion decides
                // reverse ordering
                self.dist.partial_cmp(&other.dist).map(|i| i.reverse())
            }
            other => {
                other
            }
        }
    }
}

fn crowding_distance_assignment<P: MultiObjective>(solutions: &[P],
                                                   common_rank: u32,
                                                   individuals_idx: &[usize])
                                                   -> Vec<SolutionRankDist> {
    let l = individuals_idx.len();
    let mut distance: Vec<f32> = (0..l).map(|_| 0.0).collect();
    let mut indices: Vec<usize> = (0..l).map(|i| i).collect();

    for m in 0..P::num_objectives() {
        // sort using objective `m`
        indices.sort_by(|&a, &b| {
            solutions[individuals_idx[a]].cmp_objective(&solutions[individuals_idx[b]], m)
        });
        distance[indices[0]] = f32::INFINITY;
        distance[indices[l - 1]] = f32::INFINITY;

        let min_idx = individuals_idx[indices[0]];
        let max_idx = individuals_idx[indices[l - 1]];

        let dist_max_min = solutions[max_idx].dist_objective(&solutions[min_idx], m);
        if dist_max_min != 0.0 {
            let norm = P::num_objectives() as f32 * dist_max_min;
            debug_assert!(norm != 0.0);
            for i in 1..(l - 1) {
                let next_idx = individuals_idx[indices[i + 1]];
                let prev_idx = individuals_idx[indices[i - 1]];
                distance[indices[i]] += solutions[next_idx]
                                            .dist_objective(&solutions[prev_idx], m) /
                                        norm;
            }
        }
    }

    return indices.iter()
                  .map(|&i| {
                      SolutionRankDist {
                          idx: individuals_idx[i],
                          rank: common_rank,
                          dist: distance[i],
                      }
                  })
                  .collect();
}

/// Select `n` out of the `solutions`, assigning rank and distance.
pub fn select<P: Dominate + MultiObjective>(solutions: &[P], n: usize) -> Vec<SolutionRankDist> {
    let mut selection = Vec::with_capacity(cmp::min(solutions.len(), n));

    let pareto_fronts = fast_non_dominated_sort(solutions, n);

    for (rank, front) in pareto_fronts.iter().enumerate() {
        if selection.len() >= n {
            break;
        }
        let missing: usize = n - selection.len();

        let mut solution_rank_dist = crowding_distance_assignment(solutions,
                                                                  rank as u32,
                                                                  &front[..]);
        if solution_rank_dist.len() <= missing {
            // whole front fits into result.
            selection.extend(solution_rank_dist);
            assert!(selection.len() <= n);
        } else {
            // choose only best from this front, according to the crowding distance.
            solution_rank_dist.sort_by(|a, b| {
                debug_assert!(a.rank == b.rank);
                a.partial_cmp(b).unwrap()
            });
            selection.extend(solution_rank_dist.into_iter().take(missing));
            assert!(selection.len() == n);
            break;
        }
    }

    return selection;
}

pub trait FitnessEval<I, F:Dominate+MultiObjective+Clone> {
    fn fitness(&mut self, &[I]) -> Vec<F>;
}

pub fn iterate<R: Rng,
               I: Clone,
               M: Mate<I>,
               F: Dominate + MultiObjective + Clone,
               E: FitnessEval<I, F>>
    (rng: &mut R,
     population: Vec<I>,
     fitness: Vec<F>,
     fitness_eval: &mut E,
     pop_size: usize,
     offspring_size: usize,
     mating: &mut M)
     -> (Vec<I>, Vec<F>) {
    assert!(population.len() == fitness.len());

    // evaluate rank and crowding distance (using select()).
    let rank_dist = select(&fitness[..], pop_size);
    assert!(rank_dist.len() == pop_size);

    // create `offspring_size` new offspring using binary tournament (randomly
    // select two mating partners)
    let offspring: Vec<_> = (0..offspring_size)
                                .map(|_| {
                                    // first parent. two candidates
                                    let p1cand = (rng.gen_range(0, rank_dist.len()),
                                                  rng.gen_range(0, rank_dist.len()));

                                    // second parent. two candidates
                                    let p2cand = (rng.gen_range(0, rank_dist.len()),
                                                  rng.gen_range(0, rank_dist.len()));

                                    // choose the better candiate (first parent)
                                    let p1 = if rank_dist[p1cand.0] < rank_dist[p1cand.1] {
                                        p1cand.0
                                    } else {
                                        p1cand.1
                                    };

                                    // choose the better candiate (second parent)
                                    let p2 = if rank_dist[p2cand.0] < rank_dist[p2cand.1] {
                                        p2cand.0
                                    } else {
                                        p2cand.1
                                    };

                                    // cross-over the two parents and produce one child (throw away
                                    // second child)
                                    mating.mate(&population[p1], &population[p2])
                                })
                                .collect();

    assert!(offspring.len() == offspring_size);

    // evaluate fitness of offspring
    let fitness_offspring = fitness_eval.fitness(&offspring[..]);
    assert!(fitness_offspring.len() == offspring.len());

    // merge population and offspring, then select
    let mut new_pop = Vec::with_capacity(rank_dist.len() + offspring.len());
    let mut new_fit = Vec::with_capacity(rank_dist.len() + offspring.len());
    for rd in rank_dist {
        new_pop.push(population[rd.idx].clone());
        new_fit.push(fitness[rd.idx].clone());
    }

    new_pop.extend(offspring);
    new_fit.extend(fitness_offspring);

    assert!(new_pop.len() == pop_size + offspring_size);
    assert!(new_fit.len() == pop_size + offspring_size);

    return (new_pop, new_fit);
}

#[test]
fn test_dominates() {
    let a = MultiObjective2 { objectives: [1.0, 0.1] };
    let b = MultiObjective2 { objectives: [0.1, 0.1] };
    let c = MultiObjective2 { objectives: [0.1, 1.0] };

    assert_eq!(false, a.dominates(&a));
    assert_eq!(false, a.dominates(&b));
    assert_eq!(false, a.dominates(&c));

    assert_eq!(true, b.dominates(&a));
    assert_eq!(false, b.dominates(&b));
    assert_eq!(true, b.dominates(&c));

    assert_eq!(false, c.dominates(&a));
    assert_eq!(false, c.dominates(&b));
    assert_eq!(false, c.dominates(&c));
}

fn main() {
    let mut solutions: Vec<MultiObjective2<f32>> = Vec::new();
    solutions.push(MultiObjective2 { objectives: [1.0, 0.1] });
    solutions.push(MultiObjective2 { objectives: [0.1, 0.1] });
    solutions.push(MultiObjective2 { objectives: [0.1, 1.0] });
    solutions.push(MultiObjective2 { objectives: [0.5, 0.5] });
    solutions.push(MultiObjective2 { objectives: [0.5, 0.5] });

    println!("solutions: {:?}", solutions);
    let selection = select(&solutions[..], 5);
    println!("selection: {:?}", selection);

    let fronts = fast_non_dominated_sort(&solutions[..], 10);
    println!("solutions: {:?}", solutions);
    println!("fronts: {:?}", fronts);

    for (rank, front) in fronts.iter().enumerate() {
        let distances = crowding_distance_assignment(&solutions[..], rank as u32, &front[..]);
        println!("front: {:?}", front);
        println!("distances: {:?}", distances);
    }
}
<commit_msg>Make objectives public<commit_after>use std::cmp::{self, Ordering};
use std::f32;
use std::convert::From;
use rand::Rng;
use std::ops::Sub;

pub trait Mate<T> {
    fn mate(&mut self, p1: &T, p2: &T) -> T;
}

pub trait Dominate<Rhs=Self> {
    fn dominates(&self, other: &Rhs) -> bool;
}

fn dominates_slices<T: Sized + PartialOrd>(sa: &[T], sb: &[T]) -> bool {
    assert!(sa.len() == sb.len());
    assert!(sa.len() > 0);

    let mut less_cnt = 0;
    for (a, b) in sa.iter().zip(sb.iter()) {
        if a > b {
            return false;
        } else if a < b {
            less_cnt += 1;
        }
    }

    return less_cnt > 0;
}

pub trait MultiObjective {
    fn num_objectives() -> usize;

    fn cmp_objective(&self, other: &Self, objective: usize) -> Ordering;

    // Distance between self and other
    fn dist_objective(&self, other: &Self, objective: usize) -> f32;
}

#[derive(Debug, Clone)]
pub struct MultiObjective2<T>
    where T: Sized + PartialOrd + Copy + Clone
{
    pub objectives: [T; 2],
}

impl<T:Sized+PartialOrd+Copy+Clone> From<(T, T)> for MultiObjective2<T> {
    fn from(t: (T, T)) -> MultiObjective2<T> {
        MultiObjective2 { objectives: [t.0, t.1] }
    }
}

impl<T,R> MultiObjective for MultiObjective2<T>
where T: Copy + PartialOrd + Sub<Output=R>,
      R: Into<f32> {
    fn num_objectives() -> usize {
        2
    }
    fn cmp_objective(&self, other: &Self, objective: usize) -> Ordering {
        self.objectives[objective].partial_cmp(&other.objectives[objective]).unwrap()
    }
    fn dist_objective(&self, other: &Self, objective: usize) -> f32 {
        (self.objectives[objective] - other.objectives[objective]).into()
    }
}

impl<T:Sized+PartialOrd> Dominate for MultiObjective2<T> {
    fn dominates(&self, other: &Self) -> bool {
        dominates_slices(&self.objectives[..], &other.objectives[..])
    }
}

#[derive(Debug, Clone)]
pub struct MultiObjective3<T>
    where T: Sized + PartialOrd + Copy + Clone
{
    pub objectives: [T; 3],
}

impl<T:Sized+PartialOrd+Copy+Clone> From<(T, T, T)> for MultiObjective3<T> {
    fn from(t: (T, T, T)) -> MultiObjective3<T> {
        MultiObjective3 { objectives: [t.0, t.1, t.2] }
    }
}

impl<T,R> MultiObjective for MultiObjective3<T>
where T: Copy + PartialOrd + Sub<Output=R>,
      R: Into<f32> {
    fn num_objectives() -> usize {
        3
    }
    fn cmp_objective(&self, other: &Self, objective: usize) -> Ordering {
        self.objectives[objective].partial_cmp(&other.objectives[objective]).unwrap()
    }
    fn dist_objective(&self, other: &Self, objective: usize) -> f32 {
        (self.objectives[objective] - other.objectives[objective]).into()
    }
}

impl<T:Sized+PartialOrd> Dominate for MultiObjective3<T> {
    fn dominates(&self, other: &Self) -> bool {
        dominates_slices(&self.objectives[..], &other.objectives[..])
    }
}

/// Stop after we have found `n` solutions (we include the whole pareto front, so it are probably more solutions).
fn fast_non_dominated_sort<P: Dominate>(solutions: &[P], n: usize) -> Vec<Vec<usize>> {
    let mut fronts: Vec<Vec<usize>> = Vec::new();
    let mut current_front = Vec::new();

    let mut domination_count: Vec<usize> = (0..solutions.len()).map(|_| 0).collect();
    let mut dominated_solutions: Vec<Vec<usize>> = (0..solutions.len())
                                                       .map(|_| Vec::new())
                                                       .collect();
    let mut found_solutions: usize = 0;

    for (i, p) in solutions.iter().enumerate() {
        for (j, q) in solutions.iter().enumerate() {
            if i == j {
                continue;
            }
            if p.dominates(q) {
                // Add `q` to the set of solutions dominated by `p`.
                dominated_solutions[i].push(j);
            } else if q.dominates(p) {
                // Increment domination counter of `p`.
                domination_count[i] += 1;
            }
        }

        if domination_count[i] == 0 {
            // `p` belongs to the first front as it is not dominated by any
            // other solution.
            current_front.push(i);
        }
    }

    while !current_front.is_empty() {
        found_solutions += current_front.len();
        if found_solutions >= n {
            fronts.push(current_front);
            break;
        } else {
            // we haven't found enough solutions yet.
            let mut next_front = Vec::new();
            for &p_i in current_front.iter() {
                for &q_i in dominated_solutions[p_i].iter() {
                    domination_count[q_i] -= 1;
                    if domination_count[q_i] == 0 {
                        // q belongs to the next front
                        next_front.push(q_i);
                    }
                }
            }
            fronts.push(current_front);
            current_front = next_front;
        }
    }

    return fronts;
}

#[derive(Debug)]
pub struct SolutionRankDist {
    pub idx: usize,
    pub rank: u32,
    pub dist: f32,
}

impl PartialEq for SolutionRankDist {
    #[inline]
    fn eq(&self, other: &SolutionRankDist) -> bool {
        self.rank == other.rank && self.dist == other.dist
    }
}

// Implement the crowding-distance comparison operator.
impl PartialOrd for SolutionRankDist {
    #[inline]
    // compare on rank first (ASC), then on dist (DESC)
    fn partial_cmp(&self, other: &SolutionRankDist) -> Option<Ordering> {
        match self.rank.partial_cmp(&other.rank) {
            Some(Ordering::Equal) => {
                // first criterion equal, second criterion decides
                // reverse ordering
                self.dist.partial_cmp(&other.dist).map(|i| i.reverse())
            }
            other => {
                other
            }
        }
    }
}

fn crowding_distance_assignment<P: MultiObjective>(solutions: &[P],
                                                   common_rank: u32,
                                                   individuals_idx: &[usize])
                                                   -> Vec<SolutionRankDist> {
    let l = individuals_idx.len();
    let mut distance: Vec<f32> = (0..l).map(|_| 0.0).collect();
    let mut indices: Vec<usize> = (0..l).map(|i| i).collect();

    for m in 0..P::num_objectives() {
        // sort using objective `m`
        indices.sort_by(|&a, &b| {
            solutions[individuals_idx[a]].cmp_objective(&solutions[individuals_idx[b]], m)
        });
        distance[indices[0]] = f32::INFINITY;
        distance[indices[l - 1]] = f32::INFINITY;

        let min_idx = individuals_idx[indices[0]];
        let max_idx = individuals_idx[indices[l - 1]];

        let dist_max_min = solutions[max_idx].dist_objective(&solutions[min_idx], m);
        if dist_max_min != 0.0 {
            let norm = P::num_objectives() as f32 * dist_max_min;
            debug_assert!(norm != 0.0);
            for i in 1..(l - 1) {
                let next_idx = individuals_idx[indices[i + 1]];
                let prev_idx = individuals_idx[indices[i - 1]];
                distance[indices[i]] += solutions[next_idx]
                                            .dist_objective(&solutions[prev_idx], m) /
                                        norm;
            }
        }
    }

    return indices.iter()
                  .map(|&i| {
                      SolutionRankDist {
                          idx: individuals_idx[i],
                          rank: common_rank,
                          dist: distance[i],
                      }
                  })
                  .collect();
}

/// Select `n` out of the `solutions`, assigning rank and distance.
pub fn select<P: Dominate + MultiObjective>(solutions: &[P], n: usize) -> Vec<SolutionRankDist> {
    let mut selection = Vec::with_capacity(cmp::min(solutions.len(), n));

    let pareto_fronts = fast_non_dominated_sort(solutions, n);

    for (rank, front) in pareto_fronts.iter().enumerate() {
        if selection.len() >= n {
            break;
        }
        let missing: usize = n - selection.len();

        let mut solution_rank_dist = crowding_distance_assignment(solutions,
                                                                  rank as u32,
                                                                  &front[..]);
        if solution_rank_dist.len() <= missing {
            // whole front fits into result.
            selection.extend(solution_rank_dist);
            assert!(selection.len() <= n);
        } else {
            // choose only best from this front, according to the crowding distance.
            solution_rank_dist.sort_by(|a, b| {
                debug_assert!(a.rank == b.rank);
                a.partial_cmp(b).unwrap()
            });
            selection.extend(solution_rank_dist.into_iter().take(missing));
            assert!(selection.len() == n);
            break;
        }
    }

    return selection;
}

pub trait FitnessEval<I, F:Dominate+MultiObjective+Clone> {
    fn fitness(&mut self, &[I]) -> Vec<F>;
}

pub fn iterate<R: Rng,
               I: Clone,
               M: Mate<I>,
               F: Dominate + MultiObjective + Clone,
               E: FitnessEval<I, F>>
    (rng: &mut R,
     population: Vec<I>,
     fitness: Vec<F>,
     fitness_eval: &mut E,
     pop_size: usize,
     offspring_size: usize,
     mating: &mut M)
     -> (Vec<I>, Vec<F>) {
    assert!(population.len() == fitness.len());

    // evaluate rank and crowding distance (using select()).
    let rank_dist = select(&fitness[..], pop_size);
    assert!(rank_dist.len() == pop_size);

    // create `offspring_size` new offspring using binary tournament (randomly
    // select two mating partners)
    let offspring: Vec<_> = (0..offspring_size)
                                .map(|_| {
                                    // first parent. two candidates
                                    let p1cand = (rng.gen_range(0, rank_dist.len()),
                                                  rng.gen_range(0, rank_dist.len()));

                                    // second parent. two candidates
                                    let p2cand = (rng.gen_range(0, rank_dist.len()),
                                                  rng.gen_range(0, rank_dist.len()));

                                    // choose the better candiate (first parent)
                                    let p1 = if rank_dist[p1cand.0] < rank_dist[p1cand.1] {
                                        p1cand.0
                                    } else {
                                        p1cand.1
                                    };

                                    // choose the better candiate (second parent)
                                    let p2 = if rank_dist[p2cand.0] < rank_dist[p2cand.1] {
                                        p2cand.0
                                    } else {
                                        p2cand.1
                                    };

                                    // cross-over the two parents and produce one child (throw away
                                    // second child)
                                    mating.mate(&population[p1], &population[p2])
                                })
                                .collect();

    assert!(offspring.len() == offspring_size);

    // evaluate fitness of offspring
    let fitness_offspring = fitness_eval.fitness(&offspring[..]);
    assert!(fitness_offspring.len() == offspring.len());

    // merge population and offspring, then select
    let mut new_pop = Vec::with_capacity(rank_dist.len() + offspring.len());
    let mut new_fit = Vec::with_capacity(rank_dist.len() + offspring.len());
    for rd in rank_dist {
        new_pop.push(population[rd.idx].clone());
        new_fit.push(fitness[rd.idx].clone());
    }

    new_pop.extend(offspring);
    new_fit.extend(fitness_offspring);

    assert!(new_pop.len() == pop_size + offspring_size);
    assert!(new_fit.len() == pop_size + offspring_size);

    return (new_pop, new_fit);
}

#[test]
fn test_dominates() {
    let a = MultiObjective2 { objectives: [1.0, 0.1] };
    let b = MultiObjective2 { objectives: [0.1, 0.1] };
    let c = MultiObjective2 { objectives: [0.1, 1.0] };

    assert_eq!(false, a.dominates(&a));
    assert_eq!(false, a.dominates(&b));
    assert_eq!(false, a.dominates(&c));

    assert_eq!(true, b.dominates(&a));
    assert_eq!(false, b.dominates(&b));
    assert_eq!(true, b.dominates(&c));

    assert_eq!(false, c.dominates(&a));
    assert_eq!(false, c.dominates(&b));
    assert_eq!(false, c.dominates(&c));
}

fn main() {
    let mut solutions: Vec<MultiObjective2<f32>> = Vec::new();
    solutions.push(MultiObjective2 { objectives: [1.0, 0.1] });
    solutions.push(MultiObjective2 { objectives: [0.1, 0.1] });
    solutions.push(MultiObjective2 { objectives: [0.1, 1.0] });
    solutions.push(MultiObjective2 { objectives: [0.5, 0.5] });
    solutions.push(MultiObjective2 { objectives: [0.5, 0.5] });

    println!("solutions: {:?}", solutions);
    let selection = select(&solutions[..], 5);
    println!("selection: {:?}", selection);

    let fronts = fast_non_dominated_sort(&solutions[..], 10);
    println!("solutions: {:?}", solutions);
    println!("fronts: {:?}", fronts);

    for (rank, front) in fronts.iter().enumerate() {
        let distances = crowding_distance_assignment(&solutions[..], rank as u32, &front[..]);
        println!("front: {:?}", front);
        println!("distances: {:?}", distances);
    }
}
<|endoftext|>


<commit_before>//
//  SOS: the Stupid Operating System
//  by Hawk Weisman (hi@hawkweisman.me)
//
//  Copyright (c) 2015 Hawk Weisman
//  Released under the terms of the MIT license. See `LICENSE` in the root
//  directory of this repository for more information.
//
//! Panic handling and stack unwinding

use core::fmt::{Arguments, Write};
use super::io::term;
use super::arch::drivers::vga::Color;

#[lang = "panic_fmt"]
#[no_mangle] #[inline(never)] #[cold]
pub extern fn rust_begin_unwind( args: Arguments
                               , file: &'static str
                               , line: usize ) -> !
{
    write!(term::CONSOLE.lock()
                        .set_colors(Color::White, Color::Red)
                        .clear()
          , "KERNEL PANIC \
            \nSomething has gone horribly wrong in {} at line {} \
            \n     {}"
          , file, line, args
          );
    loop { }
}

/// Required for Rust stack unwinding
#[lang = "eh_personality"]
#[no_mangle] #[inline(never)] #[cold]
pub extern fn eh_personality() {
    // TODO: add support for stack unwinding
}

#[lang = "stack_exhausted"]
#[no_mangle] #[inline(never)] #[cold]
pub extern "C" fn __morestack() -> ! {
    loop { }
}

#[allow(non_snake_case)]
#[no_mangle] #[inline(never)] #[cold]
pub extern "C" fn _Unwind_Resume() -> ! {
    loop { }
}

// #[lang = "begin_unwind"]
// #[no_mangle] #[inline(never)] #[cold]
// pub fn begin_unwind<M: Send>(msg: M
//                             , file_line: &(&'static str, usize))  -> !
// { loop { } }
<commit_msg>This fixes nothing but it makes the kernel panic message prettier So there's that, I guess.<commit_after>//
//  SOS: the Stupid Operating System
//  by Hawk Weisman (hi@hawkweisman.me)
//
//  Copyright (c) 2015 Hawk Weisman
//  Released under the terms of the MIT license. See `LICENSE` in the root
//  directory of this repository for more information.
//
//! Panic handling and stack unwinding

use core::fmt::{Arguments, Write};
use super::io::term;
use super::arch::drivers::vga::Color;

#[lang = "panic_fmt"]
#[no_mangle] #[inline(never)] #[cold]
pub extern fn rust_begin_unwind( args: Arguments
                               , file: &'static str
                               , line: usize ) -> !
{
    write!(term::CONSOLE.lock()
                        .set_colors(Color::White, Color::Red)
                        .clear()
          , "KERNEL PANIC: {} \
            \nSomething has gone horribly wrong in {} at line {}."
          , args
          , file, line
          );
    loop { }
}

/// Required for Rust stack unwinding
#[lang = "eh_personality"]
#[no_mangle] #[inline(never)] #[cold]
pub extern fn eh_personality() {
    // TODO: add support for stack unwinding
}

#[lang = "stack_exhausted"]
#[no_mangle] #[inline(never)] #[cold]
pub extern "C" fn __morestack() -> ! {
    loop { }
}

#[allow(non_snake_case)]
#[no_mangle] #[inline(never)] #[cold]
pub extern "C" fn _Unwind_Resume() -> ! {
    loop { }
}

// #[lang = "begin_unwind"]
// #[no_mangle] #[inline(never)] #[cold]
// pub fn begin_unwind<M: Send>(msg: M
//                             , file_line: &(&'static str, usize))  -> !
// { loop { } }
<|endoftext|>