{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# IN3050/IN4050 - Week 3\n",
    "## Representations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1. ![Naming_Question](EA_Terms.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Name the terms shown in the picture above."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A: Locus: the position of a gene\n",
    "\n",
    "B: Allele = 0 or 1 (What values a gene can have)\n",
    "\n",
    "\n",
    "C: Gene: one element of the array\n",
    "\n",
    "\n",
    "D: Genotype: a set of gene values\n",
    "\n",
    "\n",
    "E: Phenotype: What could be built/developed based on the genotype"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. Mention some of the most common representations of genomes."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Answer:\n",
    "* Binary\n",
    "* Integer\n",
    "* Cardinal/enumerated/symbolic\n",
    "* Real-Valued or Floating-Point\n",
    "* Permutation\n",
    "* Tree"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3. Perform a mutation operation on the representations given below.\n",
    "\n",
    "binary = $[1, 0, 1, 1]$;\n",
    "integer = $[4, 2, 4, 1]$;\n",
    "real_valued = $[2.53, 1.42, 3.14, 1.68]$;\n",
    "permutation = $[3, 4, 1, 2]$\n",
    "\n",
    "**Solution:**\n",
    "\n",
    "Binary:\n",
    "* bit-flip - Alter each gene independently with a probability $p_{m}$\n",
    "\n",
    "\n",
    "Integer: \n",
    "* Creep - Adding a small (positive or negative) value to each gene with probability $p$\n",
    "* Random resetting - With a probability $p_{m}$ a new value is chosen at random.\n",
    "\n",
    "Real Valued:\n",
    "* Uniform Mutation - For each gene draw randomly (uniform) from $[\\text{LB}_{i}, \\text{UB}_{i}]$\n",
    "* Non-uniform mutations - Add a random deviate to each gene separately, taken from $N(0, \\sigma)$ **Gaussian distribution**. \n",
    "\n",
    "Permutation:\n",
    "* Swap mutation - Pick two alleles at random and swap their positions.\n",
    "* Insert Mutation - Pick two allele values at random and move the second to follow the first, shifting the rest.\n",
    "* Scramble mutation - Pick a subset of genes at random, and randomly rearrange the alleles in those positions. \n",
    "* Inversion mutation - Pick two alleles at random and then invert the substring between them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Before mutation: [1, 0, 1, 1]; And after mutation [0, 1, 1, 0]\n",
      "Before mutation: [4, 2, 4, 1]; And after mutation [4, -10, 1, 5]\n",
      "Before mutation: [2.53, 1.42, 3.14, 1.68]; And after mutation [2.5547667148610773, 1.5188094808033545, 3.1103612346984164, 1.5571344726715721]\n",
      "[0 5]\n",
      "Before mutation: [3, 4, 1, 2, 6, 5]; And after mutation [3, 5, 4, 1, 2, 6]\n"
     ]
    }
   ],
   "source": [
    "# Code\n",
    "import random\n",
    "import numpy as np\n",
    "\n",
    "binary = [1, 0, 1, 1]\n",
    "integer = [4, 2, 4, 1]\n",
    "real_valued = [2.53, 1.42, 3.14, 1.68]\n",
    "permutation = [3, 4, 1, 2, 6, 5]\n",
    "# Solution\n",
    "\n",
    "def bit_flip(genotype, pm=0.5):\n",
    "    \"\"\"Performs a bit-flip mutation on a genotype\n",
    "    \n",
    "    Mutates each gene with a probability of pm\n",
    "    \n",
    "    Args:\n",
    "        genotype: A genotype in a binary format\n",
    "        pm: Probability for mutation\n",
    "        \n",
    "    Returns:\n",
    "        The genotype after the mutation\n",
    "    \"\"\"\n",
    "    for i in range(len(genotype)):\n",
    "        if random.random() < pm:\n",
    "            genotype[i] = 1 - genotype[i]\n",
    "    return genotype\n",
    "\n",
    "def creep(genotype, pm=0.5):\n",
    "    \"\"\"Performs a creep mutation on an integer genotype\n",
    "    \n",
    "    Mutates each gene with a random (positive or negative) value wth probability pm.\n",
    "    \n",
    "    Args:\n",
    "        genotype: A genotype in an integer format\n",
    "        pm: Probability for mutation\n",
    "        \n",
    "    Returns:\n",
    "        The genotype after the mutation\n",
    "    \"\"\"\n",
    "    for i in range(len(genotype)):\n",
    "        if random.random() < pm:\n",
    "            genotype[i] = genotype[i] + np.random.randint(-5, 5)\n",
    "    return genotype\n",
    "\n",
    "def random_resetting(genotype, min_reset=-10, max_reset=10, pm=0.5):\n",
    "    \"\"\"Perform a random resetting mutation on an integer genotype\n",
    "    \n",
    "    With a probability of pm a new value is chosen at random\n",
    "    \n",
    "    Args:\n",
    "        genotype: A genotype in an integer format\n",
    "        min_reset: Minimum value for the random reset (Default: -10)\n",
    "        max_reset: Maximum value for the random reset (Default:  10)\n",
    "        pm: Probability for mutation\n",
    "        \n",
    "    Returns:\n",
    "        The genotype after the mutation\n",
    "    \"\"\"\n",
    "    for i in range(len(genotype)):\n",
    "        if random.random() < pm:\n",
    "            genotype[i] = np.random.randint(min_reset, max_reset)\n",
    "    return genotype\n",
    "\n",
    "def uniform_mutation(genotype, lower=-10, upper=10, pm=1.0):\n",
    "    \"\"\"Perform a uniform mutation on a real valued genotype\n",
    "    \n",
    "     For each gene draw randomly (uniform) from [lower, upper]\n",
    "    \n",
    "    Args:\n",
    "        genotype: A genotype in an real value format\n",
    "        lower: Lower bound for the uniform draw (Default: -10)\n",
    "        upper: Upper bound for the uniform draw (Default:  10)\n",
    "        pm: Probability for mutation\n",
    "        \n",
    "    Returns:\n",
    "        The genotype after the mutation\n",
    "    \"\"\"\n",
    "    for i in range(len(genotype)):\n",
    "        if random.random() < pm:\n",
    "            genotype[i] = np.random.uniform(lower, upper)\n",
    "    return genotype\n",
    "\n",
    "def gaussian_mutation(genotype, sigma=0.1, pm=1.0):\n",
    "    \"\"\"Perform a non-uniform mutation on a real valued genotype\n",
    "    \n",
    "    Add a random deviate to each gene separately, taken from  𝑁(0,𝜎) Gaussian distribution\n",
    "    \n",
    "    Args:\n",
    "        genotype: A genotype in an real value format\n",
    "        sigma: Th standard deviation for the Gaussian distribution\n",
    "        pm: Probability for mutation\n",
    "        \n",
    "    Returns:\n",
    "        The genotype after the mutation\n",
    "    \"\"\"\n",
    "    for i in range(len(genotype)):\n",
    "        if random.random() < pm:\n",
    "            genotype[i] = genotype[i] + np.random.normal(0, sigma)\n",
    "    return genotype\n",
    "\n",
    "def swap_mutation(genotype):\n",
    "    \"\"\"Performs a swap mutation on a permutation genotype\n",
    "    \n",
    "    Pick two alleles at random and swap their positions\n",
    "    \n",
    "    Args:\n",
    "        genotype: A genotype in a permutation format\n",
    "        \n",
    "    Returns:\n",
    "        The genotype after the mutation    \n",
    "    \"\"\"\n",
    "    locuses = np.random.choice(len(genotype), 2, replace=False)\n",
    "    genotype[locuses[0]], genotype[locuses[1]] = genotype[locuses[1]], genotype[locuses[0]]\n",
    "    return genotype\n",
    "\n",
    "def insert_mutation(genotype):\n",
    "    \"\"\"Performs an insert mutation on a permutation genotype\n",
    "    \n",
    "    Pick two allele values at random and move the second to follow the first, shifting the rest\n",
    "    \n",
    "    Args:\n",
    "        genotype: A genotype in a permutation format\n",
    "        \n",
    "    Returns:\n",
    "        The genotype after the mutation    \n",
    "    \"\"\"\n",
    "    inserts = np.random.choice(len(genotype), 2, replace=False) #Selecting the locations of the two values\n",
    "    if inserts[0] + 1 == inserts[1]: #Inserting second after the first, skip if it's already there.\n",
    "        pass\n",
    "    elif inserts[0] < inserts[1]:\n",
    "        temp = genotype.pop(inserts[1])\n",
    "        genotype.insert(inserts[0]+1,temp)\n",
    "    else:\n",
    "        genotype.insert(inserts[0], genotype.pop(inserts[1]))\n",
    "    print(inserts)\n",
    "\n",
    "    return genotype\n",
    "\n",
    "def scramble_mutation(genotype):\n",
    "    \"\"\"Performs a scramble mutation on a permutation genotype\n",
    "    \n",
    "    Pick a subset of genes at random, and randomly rearrange the alleles in those positions\n",
    "    \n",
    "    Args:\n",
    "        genotype: A genotype in a permutation format\n",
    "        \n",
    "    Returns:\n",
    "        The genotype after the mutation    \n",
    "    \"\"\"\n",
    "    genotype_copy = genotype.copy()\n",
    "    locuses = np.random.choice(len(genotype), np.random.randint(2, len(genotype)), replace=False)\n",
    "    locuses_list = locuses.tolist()\n",
    "    for locus in locuses:\n",
    "        if len(locuses_list) == 1:\n",
    "            genotype[locus] = genotype_copy[locuses_list[0]]\n",
    "        else:\n",
    "            genotype[locus] = genotype_copy[locuses_list.pop(np.random.randint(0, len(locuses_list)))]\n",
    "        \n",
    "    return genotype\n",
    "\n",
    "def inversion_mutation(genotype):\n",
    "    \"\"\"Performs inversion mutation on a permutation genotype\n",
    "    \n",
    "    Pick two locations in the genotype random, and randomly rearrange the alleles between them\n",
    "    \n",
    "    Args:\n",
    "        genotype: A genotype in a permutation format\n",
    "        \n",
    "    Returns:\n",
    "        The genotype after the mutation    \n",
    "    \"\"\"\n",
    "    inserts = np.random.choice(len(genotype), 2, replace=False) #Selecting 2 random locations to invert between\n",
    "    print(inserts)\n",
    "    if inserts[0] > inserts[1]: #Swapping the two locations if they are in the reverse order\n",
    "        temp = inserts[0]\n",
    "        inserts[0] = inserts[1]\n",
    "        inserts[1] = temp\n",
    "    genotype[inserts[0]:inserts[1]+1] = genotype[inserts[0]:inserts[1]+1][::-1] #Inverting between the locations\n",
    "        \n",
    "    return genotype\n",
    "\n",
    "\n",
    "# Test solutions\n",
    "print(f'Before mutation: {binary}; And after mutation {bit_flip(binary)}')\n",
    "print(f'Before mutation: {integer}; And after mutation {random_resetting(integer)}')\n",
    "print(f'Before mutation: {real_valued}; And after mutation {gaussian_mutation(real_valued)}')\n",
    "print(f'Before mutation: {permutation}; And after mutation {insert_mutation(permutation)}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4. Given the sequences (2,4,7,1,3,6,8,9,5) and (5,9,8,6,2,4,1,3,7). Implement these algorithms to create a new pair of solutions: "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### a. Partially mapped crossover (PMX)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Code\n",
    "def pmx(a, b, start, stop):\n",
    "    child = [None]*len(a)\n",
    "    \n",
    "    # Copy a slice from first paret:\n",
    "    child[start:stop] = a[start:stop]\n",
    "    \n",
    "    # Map the same slice in parent b to child using indices from parent a:\n",
    "    for ind, x in enumerate(b[start:stop]):\n",
    "        ind += start\n",
    "        if x not in child:\n",
    "            while child[ind] != None:\n",
    "                ind = b.index(a[ind])\n",
    "            child[ind] = x\n",
    "    # Copy over the rest from parent b\n",
    "    for ind, x in enumerate(child):\n",
    "        if x == None:\n",
    "            child[ind] = b[ind]\n",
    "            \n",
    "    return child\n",
    "\n",
    "\n",
    "def pmx_pair(a, b):\n",
    "    half = len(a) // 2\n",
    "    start = np.random.randint(0, len(a)-half)\n",
    "    stop = start+half\n",
    "    return pmx(a, b, start, stop), pmx(b, a, start, stop)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### b. Order crossover"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Code\n",
    "def order_crossover(a, b, start, stop):\n",
    "    child = [None]*len(a)\n",
    "    \n",
    "    # Copy a slice from first parent:\n",
    "    child[start:stop] = a[start:stop]\n",
    "    \n",
    "    # Fill using order from second parent:\n",
    "    b_ind = stop\n",
    "    c_ind = stop\n",
    "    l = len(a)\n",
    "    while None in child:\n",
    "        if b[b_ind % l] not in child:\n",
    "            child[c_ind % l] = b[b_ind % l]\n",
    "            c_ind += 1\n",
    "        b_ind += 1\n",
    "        \n",
    "    return child\n",
    "\n",
    "def order_crossover_pair(a, b):\n",
    "    half = len(a) // 2\n",
    "    start = np.random.randint(0, len(a)-half)\n",
    "    stop = start + half\n",
    "    return order_crossover(a, b, start, stop), order_crossover(b, a, start, stop)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### c. Cycle crossover"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Code\n",
    "def cycle_crossover(a, b):\n",
    "    child = [None]*len(a)\n",
    "    while None in child:\n",
    "        ind = child.index(None)\n",
    "        indices = []\n",
    "        values = []\n",
    "        while ind not in indices:\n",
    "            val = a[ind]\n",
    "            indices.append(ind)\n",
    "            values.append(val)\n",
    "            ind = a.index(b[ind])\n",
    "        for ind, val in zip(indices, values):\n",
    "            child[ind] = val\n",
    "        a, b = b, a\n",
    "        \n",
    "    return child\n",
    "\n",
    "def cycle_crossover_pair(a, b):\n",
    "    return cycle_crossover(a, b), cycle_crossover(b, a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Test crossovers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Parents: [2, 4, 7, 1, 3, 6, 8, 9, 5] and [5, 9, 8, 6, 2, 4, 1, 3, 7]\n",
      "Children after PMX: [5, 9, 7, 1, 3, 6, 4, 2, 8] and [3, 1, 8, 6, 2, 4, 7, 9, 5]\n",
      "Children after Order Crossover: [5, 2, 4, 1, 3, 6, 8, 9, 7] and [7, 6, 8, 9, 2, 4, 1, 3, 5]\n",
      "Children after Cycle Crossover: [2, 4, 7, 1, 3, 6, 8, 9, 5] and [5, 9, 8, 6, 2, 4, 1, 3, 7]\n"
     ]
    }
   ],
   "source": [
    "a = [2, 4, 7, 1, 3, 6, 8, 9, 5]\n",
    "b = [5, 9, 8, 6, 2, 4, 1, 3, 7]\n",
    "c, d = pmx_pair(a, b)\n",
    "e, f = order_crossover_pair(a, b)\n",
    "g, h = cycle_crossover_pair(a, b)\n",
    "print(f\"Parents: {a} and {b}\")\n",
    "print(f\"Children after PMX: {c} and {d}\")\n",
    "print(f\"Children after Order Crossover: {e} and {f}\")\n",
    "print(f\"Children after Cycle Crossover: {g} and {h}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
