{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "EA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "N_CITIES = 606  \n",
    "CROSS_RATE = 0.1\n",
    "MUTATE_RATE = 0.02\n",
    "POP_SIZE = 500\n",
    "N_GENERATIONS = 500"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "class GA(object):\n",
    "    def __init__(self, DNA_size, cross_rate, mutation_rate, pop_size, ):\n",
    "        self.DNA_size = DNA_size\n",
    "        self.cross_rate = cross_rate\n",
    "        self.mutate_rate = mutation_rate\n",
    "        self.pop_size = pop_size\n",
    "\n",
    "        self.pop = np.vstack([np.random.permutation(DNA_size) for _ in range(pop_size)])\n",
    "\n",
    "    def translateDNA(self, DNA, city_position):     # get cities' coord in order\n",
    "        line_x = np.empty_like(DNA, dtype=np.float64)\n",
    "        line_y = np.empty_like(DNA, dtype=np.float64)\n",
    "        for i, d in enumerate(DNA):\n",
    "            city_coord = city_position[d]\n",
    "            line_x[i, :] = city_coord[:, 0]\n",
    "            line_y[i, :] = city_coord[:, 1]\n",
    "        return line_x, line_y\n",
    "\n",
    "    def get_fitness(self, line_x, line_y):\n",
    "        total_distance = np.empty((line_x.shape[0],), dtype=np.float64)\n",
    "        for i, (xs, ys) in enumerate(zip(line_x, line_y)):\n",
    "            total_distance[i] = np.sum(np.sqrt(np.square(np.diff(xs)) + np.square(np.diff(ys))))\n",
    "        fitness = np.exp(self.DNA_size * 2 / total_distance)\n",
    "        return fitness, total_distance\n",
    "\n",
    "    def select(self, fitness):\n",
    "        idx = np.random.choice(np.arange(self.pop_size), size=self.pop_size, replace=True, p=fitness / fitness.sum())\n",
    "        return self.pop[idx]\n",
    "\n",
    "    def crossover(self, parent, pop):\n",
    "        if np.random.rand() < self.cross_rate:\n",
    "            i_ = np.random.randint(0, self.pop_size, size=1)                        # select another individual from pop\n",
    "            cross_points = np.random.randint(0, 2, self.DNA_size).astype(np.bool)   # choose crossover points\n",
    "            keep_city = parent[~cross_points]                                       # find the city number\n",
    "            swap_city = pop[i_, np.isin(pop[i_].ravel(), keep_city, invert=True)]\n",
    "            parent[:] = np.concatenate((keep_city, swap_city))\n",
    "        return parent\n",
    "\n",
    "    def mutate(self, child):\n",
    "        for point in range(self.DNA_size):\n",
    "            if np.random.rand() < self.mutate_rate:\n",
    "                swap_point = np.random.randint(0, self.DNA_size)\n",
    "                swapA, swapB = child[point], child[swap_point]\n",
    "                child[point], child[swap_point] = swapB, swapA\n",
    "        return child\n",
    "\n",
    "    def evolve(self, fitness):\n",
    "        pop = self.select(fitness)\n",
    "        pop_copy = pop.copy()\n",
    "        for parent in pop:  # for every parent\n",
    "            child = self.crossover(parent, pop_copy)\n",
    "            child = self.mutate(child)\n",
    "            parent[:] = child\n",
    "        self.pop = pop\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "class TravelItinerary(object):\n",
    "    def __init__(self, n_cities):\n",
    "        self.city_position = np.random.rand(n_cities, 2)\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "__init__() missing 1 required positional argument: 'n_cities'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-5-8c6af9fcf237>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mTravelItinerary\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: __init__() missing 1 required positional argument: 'n_cities'"
     ]
    }
   ],
   "source": [
    "TravelItinerary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}