optimization-checkpoint.ipynb 9.48 KB
Newer Older
TeacherZhu committed
1 2 3 4 5 6 7 8 9 10 11
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 图的遍历"
   ]
  },
  {
   "cell_type": "code",
20200519029 committed
12
   "execution_count": 1,
TeacherZhu committed
13
   "metadata": {},
20200519029 committed
14
   "outputs": [],
TeacherZhu committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
   "source": [
    "\n",
    "def BFS(graph, s):\n",
    "    queue = [] # \n",
    "    queue.append(s)\n",
    "    seen = set() # \n",
    "    while len(queue) > 0:\n",
    "        vertex = queue.pop(0)\n",
    "        nodes = graph[vertex]\n",
    "        for w in nodes:\n",
    "            if w not in seen:\n",
    "                queue.append(w)\n",
    "                seen.add(w)\n",
    "\n",
    "        # print(vertex)\n",
    "\n",
    "    print(seen)\n",
    "\n",
    "\n",
    "graph = {\n",
    "    \"A\": [\"B\", \"C\"],\n",
    "    \"B\": [\"A\", \"C\", \"D\"],\n",
    "    \"C\": [\"A\", \"B\", \"E\", \"D\"],\n",
    "    \"D\": [\"B\", \"C\", \"E\", \"F\"],\n",
    "    \"F\": [\"D\"],\n",
    "    \"E\": [\"C\", \"D\"],\n",
    "}\n",
    "\n",
    "BFS(graph, \"F\")\n",
    "#\n",
    "# def breadth_travel(root):\n",
    "#     \"\"\"利⽤队列实现树的层次遍历\"\"\"\n",
    "#     if root == None:\n",
    "#         return\n",
    "#     queue = []\n",
    "#     queue.append(root)\n",
    "#     while queue:\n",
    "#         node = queue.pop(0)\n",
    "#         print(node.elem)\n",
    "#         if node.lchild is not None:\n",
    "#             queue.append(node.lchild)\n",
    "#         if node.rchild != None:\n",
    "#             queue.append(node.rchild)\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# dijkstra heap"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import heapq as hp\n",
    "import math\n",
    "\n",
    "graph = {\n",
    "\n",
    "    \"A\": {\"B\": 5, \"C\": 1},\n",
    "    \"B\": {\"A\": 5, \"C\": 2, \"D\": 1},\n",
    "    \"C\": {\"A\": 1, \"B\": 2, \"E\": 8, \"D\": 4},\n",
    "    \"D\": {\"B\": 1, \"C\": 4, \"E\": 3, \"F\": 6},\n",
    "    \"F\": {\"D\": 6},\n",
    "    \"E\": {\"C\": 8, \"D\": 3},\n",
    "}\n",
    "\n",
    "\n",
    "def init_distance(graph, s):\n",
    "    distance = {s: 0}\n",
    "    for key in graph:\n",
    "        if key != s:\n",
    "            distance[key] = math.inf\n",
    "    return distance\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
20200519029 committed
111
      "<module 'heapq' from 'F:\\\\Installpath\\\\Anaconda3\\\\lib\\\\heapq.py'>\n",
TeacherZhu committed
112 113 114 115 116 117 118 119 120 121 122 123 124
      "{'A': 0, 'B': inf, 'C': inf, 'D': inf, 'F': inf, 'E': inf}\n",
      "seen:    {'A'}\n",
      "nodes:    dict_keys(['B', 'C'])\n",
      "change distance for B:    {'A': 0, 'B': 5, 'C': inf, 'D': inf, 'F': inf, 'E': inf}\n",
      "change distance for C:    {'A': 0, 'B': 5, 'C': 1, 'D': inf, 'F': inf, 'E': inf}\n",
      "seen:    {'A', 'C'}\n",
      "nodes:    dict_keys(['A', 'B', 'E', 'D'])\n",
      "change distance for B:    {'A': 0, 'B': 3, 'C': 1, 'D': inf, 'F': inf, 'E': inf}\n",
      "change distance for E:    {'A': 0, 'B': 3, 'C': 1, 'D': inf, 'F': inf, 'E': 9}\n",
      "change distance for D:    {'A': 0, 'B': 3, 'C': 1, 'D': 5, 'F': inf, 'E': 9}\n",
      "seen:    {'A', 'B', 'C'}\n",
      "nodes:    dict_keys(['A', 'C', 'D'])\n",
      "change distance for D:    {'A': 0, 'B': 3, 'C': 1, 'D': 4, 'F': inf, 'E': 9}\n",
20200519029 committed
125
      "seen:    {'A', 'D', 'B', 'C'}\n",
TeacherZhu committed
126 127 128
      "nodes:    dict_keys(['B', 'C', 'E', 'F'])\n",
      "change distance for E:    {'A': 0, 'B': 3, 'C': 1, 'D': 4, 'F': inf, 'E': 7}\n",
      "change distance for F:    {'A': 0, 'B': 3, 'C': 1, 'D': 4, 'F': 10, 'E': 7}\n",
20200519029 committed
129
      "seen:    {'A', 'D', 'B', 'C'}\n",
TeacherZhu committed
130
      "nodes:    dict_keys(['A', 'C', 'D'])\n",
20200519029 committed
131
      "seen:    {'A', 'D', 'B', 'C'}\n",
TeacherZhu committed
132
      "nodes:    dict_keys(['B', 'C', 'E', 'F'])\n",
20200519029 committed
133
      "seen:    {'D', 'E', 'A', 'C', 'B'}\n",
TeacherZhu committed
134
      "nodes:    dict_keys(['C', 'D'])\n",
20200519029 committed
135
      "seen:    {'D', 'E', 'A', 'C', 'B'}\n",
TeacherZhu committed
136
      "nodes:    dict_keys(['C', 'D'])\n",
20200519029 committed
137
      "seen:    {'D', 'E', 'A', 'C', 'F', 'B'}\n",
TeacherZhu committed
138 139 140 141 142 143 144 145 146 147
      "nodes:    dict_keys(['D'])\n",
      "{'A': 0, 'B': 3, 'C': 1, 'D': 4, 'F': 10, 'E': 7}\n"
     ]
    }
   ],
   "source": [
    "def dijkstra(graph, s):\n",
    "    pqueue = []\n",
    "    hp.heappush(pqueue, (0, s)) #\n",
    "    print(hp)\n",
20200519029 committed
148
    "    seen = set()\n",
TeacherZhu committed
149 150 151 152 153 154
    "    distance = init_distance(graph, s)\n",
    "    print(distance)\n",
    "    while len(pqueue) > 0:\n",
    "        pair = hp.heappop(pqueue)\n",
    "        dist = pair[0] # \n",
    "        node = pair[1] #\n",
20200519029 committed
155
    "        seen.add(node)\n",
TeacherZhu committed
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
    "        print(\"seen:   \", seen)\n",
    "        nodes = graph[node].keys() # \n",
    "        print(\"nodes:   \", nodes)\n",
    "        #\n",
    "        for w in nodes:\n",
    "            if dist + graph[node][w] < distance[w]:\n",
    "                hp.heappush(pqueue, (dist + graph[node][w], w))\n",
    "                distance[w] = dist + graph[node][w]\n",
    "                print(f\"change distance for {w}:   \", distance)\n",
    "    return distance\n",
    "\n",
    "\n",
    "d = dijkstra(graph, \"A\")\n",
    "print(d)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# dijkstra 动态规划"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 3, 1, 4, 7, 10]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "10"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Inf = float('inf')\n",
    "Adjacent = [[0, 5, 1, Inf, Inf, Inf],\n",
    "            [5, 0, 2, 1, Inf, Inf],\n",
    "            [1, 2, 0, 4, 8, Inf],\n",
    "            [Inf, 1, 4, 0, 3, 6],\n",
    "            [Inf, Inf, 8, 3, 0, Inf],\n",
    "            [Inf, Inf, Inf, 6, Inf, 0]]\n",
    "Src, Dst, N = 0, 5, 6\n",
    "\n",
    "\n",
    "# 动态规划\n",
    "def dijstra(adj, src, dst, n):\n",
    "    dist = [Inf] * n  #\n",
    "    dist[src] = 0\n",
    "    book = [0] * n  # 记录已经确定的顶点\n",
    "    # 每次找到起点到该点的最短途径\n",
    "    u = src\n",
    "    for _ in range(n - 1):  # 找n-1次\n",
    "        book[u] = 1  # 已经确定\n",
    "        # 更新距离并记录最小距离的结点\n",
    "        next_u, minVal = None, float('inf')\n",
    "        for v in range(n):  # w\n",
    "            w = adj[u][v]\n",
    "            if w == Inf:  # 结点u和v之间没有边\n",
    "                continue\n",
    "            if not book[v] and dist[u] + w < dist[v]:  # 判断结点是否已经确定了\n",
    "                dist[v] = dist[u] + w\n",
    "                if dist[v] < minVal:\n",
    "                    next_u, minVal = v, dist[v]\n",
    "        # 开始下一轮遍历\n",
    "        u = next_u\n",
    "    print(dist)\n",
    "    return dist[dst]\n",
    "\n",
    "\n",
    "dijstra(Adjacent, Src, Dst, N)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 模拟退火"
   ]
  },
  {
   "cell_type": "code",
20200519029 committed
250
   "execution_count": null,
TeacherZhu committed
251
   "metadata": {},
20200519029 committed
252
   "outputs": [],
TeacherZhu committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
   "source": [
    "from __future__ import division\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import math\n",
    " \n",
    "#define aim function\n",
    "def aimFunction(x):\n",
    "    y=x**3-60*x**2-4*x+6\n",
    "    return y\n",
    "x=[i/10 for i in range(1000)]\n",
    "y=[0 for i in range(1000)]\n",
    "for i in range(1000):\n",
    "    y[i]=aimFunction(x[i])\n",
    "\n",
    "plt.plot(x,y)\n",
    "plt.show()\n",
    "\n",
    "print('最小值',y.index(min(y)))   \n",
    "print(\"最优值\",x[400], min(y))"
   ]
  },
  {
   "cell_type": "code",
20200519029 committed
277
   "execution_count": null,
TeacherZhu committed
278
   "metadata": {},
20200519029 committed
279
   "outputs": [],
TeacherZhu committed
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
   "source": [
    "T=1000 #initiate temperature\n",
    "Tmin=10 #minimum value of terperature\n",
    "x=np.random.uniform(low=0,high=100)#initiate x\n",
    "k=50 #times of internal circulation \n",
    "y=0#initiate result\n",
    "t=0#time\n",
    "while T>=Tmin:\n",
    "    for i in range(k):\n",
    "        #calculate y\n",
    "        y=aimFunction(x)\n",
    "        #generate a new x in the neighboorhood of x by transform function\n",
    "        xNew=x+np.random.uniform(low=-0.055,high=0.055)*T\n",
    "        if (0<=xNew and xNew<=100):\n",
    "            yNew=aimFunction(xNew)\n",
    "            if yNew-y<0:\n",
    "                x=xNew\n",
    "            else:\n",
    "                #metropolis principle\n",
    "                p=math.exp(-(yNew-y)/T)\n",
    "                r=np.random.uniform(low=0,high=1)\n",
    "                if r<p:\n",
    "                    x=xNew\n",
    "    t+=1\n",
    "#     print(t)\n",
    "    T=1000/(1+t)\n",
    "    \n",
    "print (x,aimFunction(x))"
   ]
  },
  {
   "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",
20200519029 committed
334
   "version": "3.7.0"
TeacherZhu committed
335 336 337 338 339
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}