Rmax_potential_Vesc_Mochima.ipynb 1.38 MB
Newer Older
1
2
3
4
5
6
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
7
8
    "collapsed": false,
    "hide_input": false
9
10
11
12
13
   },
   "outputs": [],
   "source": [
    "%matplotlib notebook\n",
    "%load_ext autoreload\n",
14
    "%autoreload 2"
15
16
17
18
19
20
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
21
    "collapsed": false,
22
    "hide_input": false
23
24
25
26
27
28
29
30
31
32
33
34
   },
   "outputs": [],
   "source": [
    "\n",
    "from scipy.stats import rv_continuous\n",
    "from scipy.interpolate import interp1d\n",
    "from matplotlib.patches import Circle\n",
    "from scipy.special import gamma\n",
    "import numpy as np\n",
    "import emcee\n",
    "from mpl_toolkits.axes_grid1 import make_axes_locatable\n",
    "from numpy import exp, sqrt\n",
35
    "from scipy.integrate import quad, dblquad, nquad\n",
36
37
38
39
40
41
42
43
44
45
46
47
48
49
    "import matplotlib.patches as patches\n",
    "from itertools import product\n",
    "from scipy.integrate import quad\n",
    "import scipy.optimize as optimize\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib as mpl\n",
    "from sklearn.neighbors import KDTree\n",
    "import sys\n",
    "import lmfit\n",
    "from py_unsio import *\n",
    "import pymc\n",
    "import os\n",
    "from pymodelfit import FunctionModel1DAuto\n",
    "import wkbl\n",
50
    "from wkbl.astro.halo_info import *\n",
51
52
53
54
55
56
57
58
    "from mpl_toolkits.mplot3d import axes3d\n",
    "from matplotlib import cm\n",
    "import wkbl.astro.nbody_essentials as nbe\n",
    "import cfalcon\n",
    "CF =cfalcon.CFalcon()\n",
    "import iminuit\n",
    "from iminuit import Minuit, describe, Struct\n",
    "import probfit\n",
59
    "from matplotlib.colors import LogNorm\n",
60
61
62
    "from matplotlib.ticker import FormatStrFormatter\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')"
63
64
   ]
  },
65
66
67
68
69
70
71
72
73
74
75
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "hydro = wkbl.astro.halo_info.MochimaHydro()"
   ]
  },
76
77
  {
   "cell_type": "code",
78
   "execution_count": 3,
79
80
   "metadata": {
    "collapsed": false,
81
    "hide_input": false,
82
    "scrolled": true
83
84
85
86
87
88
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
89
90
91
      "loading Dark matter..\n",
      "loading Stars..\n",
      "loading Gas..\n",
92
93
94
      "36844.594\n",
      "[20418.88714131 17567.72033332 17124.40448217]\n",
      "| r_200 = 212.70\n",
95
      "| Diagonal matrix computed \n",
96
97
98
      "|    | 20, 0, 0|\n",
      "| D =| 0, 14, 0|\n",
      "|    | 0,  0, 4|\n"
99
100
101
102
     ]
    }
   ],
   "source": [
103
    "#halo = HALOBHydro(where=\"home\") \n",
104
    "simname=\"Mochima\"\n",
105
106
107
    "pathsim = \"/data/OWN/SF1test/SF0/mstar1_T3600/output_00041\"\n",
    "myhydro = wkbl.Galaxy_Hound(pathsim)\n",
    "print myhydro.dm.pos3d[:,0].max()\n",
108
109
    "zoom_reg = np.where(myhydro.dm.mass==myhydro.dm.mass.min())\n",
    "nucenter = nbe.real_center(myhydro.dm.pos3d[zoom_reg], myhydro.dm.mass[zoom_reg])\n",
110
    "print nucenter\n",
111
    "myhydro.center_shift(nucenter)\n",
112
    "myhydro.r_virial(600,n=25)\n"
113
114
   ]
  },
115
116
  {
   "cell_type": "code",
117
118
119
   "execution_count": null,
   "metadata": {
    "collapsed": true
120
121
122
123
124
125
126
127
128
129
130
131
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
132
    {
133
134
135
136
137
138
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8.215e+11\n",
      "1.175e+11\n"
     ]
139
140
141
    }
   ],
   "source": [
142
143
    "print \"{0:.3e}\".format(np.sum(myhydro.dm.mass[myhydro.dm.r<myhydro.r200]))\n",
    "print \"{0:.3e}\".format(np.sum(myhydro.st.mass[myhydro.st.r<myhydro.r200]))"
144
145
146
147
   ]
  },
  {
   "cell_type": "code",
148
   "execution_count": 5,
149
   "metadata": {
150
    "collapsed": true
151
   },
152
   "outputs": [],
153
   "source": [
154
155
    "##############################################################################################33\n",
    "#########################################################################################3######"
156
   ]
157
158
159
  },
  {
   "cell_type": "code",
160
   "execution_count": 6,
161
   "metadata": {
162
163
    "collapsed": false,
    "hide_input": false
164
165
166
   },
   "outputs": [],
   "source": [
167
168
    "ok,myhydro.dm.rho,_= CF.getDensity(np.array(myhydro.dm.pos3d.reshape(len(myhydro.dm.pos3d)*3),\n",
    "                                    dtype=np.float32), myhydro.dm.mass)\n"
169
170
171
172
   ]
  },
  {
   "cell_type": "code",
173
   "execution_count": 7,
174
   "metadata": {
175
    "collapsed": false,
176
    "hide_input": false
177
   },
178
   "outputs": [],
179
   "source": [
180
181
    "ok,myhydro.st.rho,_= CF.getDensity(np.array(myhydro.st.pos3d.reshape(len(myhydro.st.pos3d)*3),\n",
    "                                    dtype=np.float32), myhydro.st.mass)"
182
183
184
185
   ]
  },
  {
   "cell_type": "code",
186
   "execution_count": 8,
187
   "metadata": {
188
189
    "collapsed": false,
    "hide_input": false
190
   },
191
192
193
194
195
196
197
198
199
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "32066676 32066676\n"
     ]
    }
   ],
200
   "source": [
201
202
203
204
205
    "pos_dm = np.array(myhydro.dm.pos3d.reshape(len(myhydro.dm.pos3d)*3),dtype=np.float32)\n",
    "pos_gs = np.array(myhydro.gs.pos3d.reshape(len(myhydro.gs.pos3d)*3),dtype=np.float32)\n",
    "pos_st = np.array(myhydro.st.pos3d.reshape(len(myhydro.st.pos3d)*3),dtype=np.float32)\n",
    "pos = np.concatenate((pos_dm, pos_st, pos_gs))\n",
    "phi_cord = np.concatenate((myhydro.dm.phi,myhydro.st.phi, myhydro.gs.phi))\n",
206
    "\n",
207
208
209
210
211
    "mass = np.concatenate((myhydro.dm.mass,myhydro.st.mass,myhydro.gs.mass))\n",
    "v = np.concatenate((myhydro.dm.v,myhydro.st.v,myhydro.gs.v))\n",
    "print len(mass)*3, len(pos)\n",
    "pos3d = pos.reshape(len(pos)/3,3)\n",
    "r2 = pos3d[:,0]**2 + pos3d[:,1]**2 +pos3d[:,2]**2"
212
213
214
215
   ]
  },
  {
   "cell_type": "code",
216
   "execution_count": null,
217
   "metadata": {
218
    "collapsed": false
219
220
   },
   "outputs": [],
221
   "source": []
222
223
224
  },
  {
   "cell_type": "code",
225
   "execution_count": 9,
226
   "metadata": {
227
228
    "collapsed": false,
    "hide_input": false
229
   },
230
   "outputs": [],
231
   "source": [
232
233
    "ok, acc, Phy = CF.getGravity(pos,mass,0.15,G=myhydro.p.G)\n",
    "Phy = Phy * myhydro.p.kpctokm**2"
234
235
236
237
   ]
  },
  {
   "cell_type": "code",
238
   "execution_count": 10,
239
   "metadata": {
240
    "collapsed": true
241
242
243
   },
   "outputs": [],
   "source": [
244
245
    "##############################################################################################33\n",
    "#########################################################################################3######"
246
247
248
249
   ]
  },
  {
   "cell_type": "code",
250
   "execution_count": 97,
251
   "metadata": {
252
253
    "collapsed": false,
    "hide_input": false
254
255
256
   },
   "outputs": [
    {
257
258
259
260
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3853.3405417848694\n"
261
262
263
264
     ]
    }
   ],
   "source": [
265
266
267
268
269
270
271
272
273
274
275
276
    "# center of big neighbour\n",
    "#neighbourg = myhydro.dm.rho[np.where((myhydro.dm.r<4000)&(myhydro.dm.r>myhydro.r200))].max()\n",
    "#myneighbourg = myhydro.dm.pos3d[np.where(myhydro.dm.rho==neighbourg)][0]\n",
    "supershell = np.where((r2>(3*myhydro.r200)**2))\n",
    "neighbourg = Phy[supershell].min()\n",
    "possupershell = pos3d[supershell]\n",
    "myneighbourg = possupershell[np.where(Phy[supershell]==neighbourg)][0]\n",
    "# its radius squared\n",
    "r_nei2 = myneighbourg[0]**2 + myneighbourg[1]**2 + myneighbourg[2]**2\n",
    "phi_neigh = np.arctan2(myneighbourg[1],myneighbourg[0])\n",
    "print np.sqrt(r_nei2)\n",
    "the_neigh = np.arccos(myneighbourg[0]/np.sqrt(r_nei2))\n",
277
278
    "\n",
    "\n",
279
280
281
282
283
284
285
286
287
288
289
    "# distance to every point proyected to the line conecting center to neigblourg \n",
    "adyacent = (pos3d[:,0]*myneighbourg[0] + pos3d[:,1]*myneighbourg[1] + pos3d[:,2]*myneighbourg[2]) / np.sqrt(r_nei2)\n",
    "# distance to each point\n",
    "hipoteneuse = np.sqrt(pos3d[:,0]**2 + pos3d[:,1]**2 + pos3d[:,2]**2)\n",
    "# angle of cone\n",
    "alpha = np.radians(3)\n",
    "cos_alpha = np.cos(alpha)\n",
    "# cosine of all particles respective to their angle to the l.o.s\n",
    "cos_all = adyacent / hipoteneuse \n",
    "# final selection of cone\n",
    "my_cone = pos3d[np.where((cos_all)>cos_alpha)]"
290
291
292
293
   ]
  },
  {
   "cell_type": "code",
294
   "execution_count": 98,
295
296
   "metadata": {
    "collapsed": false,
297
    "hide_input": false
298
299
300
   },
   "outputs": [
    {
301
302
303
304
305
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "the biggest neighbourg has a mass of 1.0509e+11 Msun and a r200 of 101.6018 kpc\n",
      "and it is located at 3853.3405 kpc from de center of our halo \n"
306
307
308
309
     ]
    }
   ],
   "source": [
310
311
312
313
314
315
316
317
318
319
320
321
    "# radii from center of neighbour\n",
    "r_neig = np.sqrt((pos3d[:,0] - myneighbourg[0])**2 +(pos3d[:,1] - myneighbourg[1])**2 +(pos3d[:,2] - myneighbourg[2])**2 )\n",
    "# calculating the R200 of neighbout\n",
    "mhist, rhist = np.histogram(r_neig,range=(0.0,np.sqrt(r_nei2)),bins=512, weights=mass )\n",
    "vol_bin = (4./3.)*np.pi*(rhist[:-1]**3)\n",
    "r_bin = rhist[:-1]+ 0.5*(rhist[2]-rhist[1])\n",
    "rho_s = np.cumsum(mhist) / vol_bin\n",
    "r200_neigh = r_bin[np.argmin(np.abs(rho_s - (200 * myhydro.p.rho_crit)))]\n",
    "# mass of neighbour\n",
    "mass_neigh = np.sum(mass[np.where(r_neig<r200_neigh)])\n",
    "print \"the biggest neighbourg has a mass of {0:.4e} Msun and a r200 of {1:.4f} kpc\".format(mass_neigh,r200_neigh)\n",
    "print \"and it is located at {0:.4f} kpc from de center of our halo \".format(np.sqrt(r_nei2))"
322
323
324
325
   ]
  },
  {
   "cell_type": "code",
326
   "execution_count": 99,
327
   "metadata": {
328
329
    "collapsed": false,
    "hide_input": false
330
331
332
   },
   "outputs": [],
   "source": [
333
334
335
336
337
338
339
340
341
342
    "los_condition = np.where((cos_all)>cos_alpha)\n",
    "cone_pos = my_cone\n",
    "cone_mass = mass[los_condition]\n",
    "cone_Phy = Phy[los_condition]\n",
    "cone_r2 = my_cone[:,0]**2 + my_cone[:,1]**2 + my_cone[:,2]**2\n",
    "# now the histogram\n",
    "bin_num = 1000\n",
    "pot_los, bins_pot_los = np.histogram(cone_r2,bins=bin_num,\n",
    "                                 weights=cone_Phy)\n",
    "n_los, _ = np.histogram(cone_r2,bins=bin_num)\n"
343
344
345
346
   ]
  },
  {
   "cell_type": "code",
347
   "execution_count": 100,
348
349
350
351
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
352
353
354
355
356
357
358
359
360
361
362
363
364
365
   "source": [
    "#a proyection Story\n",
    "th,ph,ep = the_neigh, phi_neigh, -3*np.pi/4.\n",
    "Ct, Cp, Ce = np.cos(th),np.cos(ph), np.cos(ep)\n",
    "St, Sp, Se = np.sin(th),np.sin(ph), np.sin(ep)\n",
    "#the rotation matrix\n",
    "rot = np.array([[(Ce*Ct*Cp)+(Se*Sp),(Ce*Ct*Sp)-(Se*Cp),Ce*St],\\\n",
    "                [(Se*Ct*Cp)-(Ce*Sp),(Se*Ct*Sp)+(Ce*Cp),Se*St],\\\n",
    "                [-Cp*St,-St*Sp,Ct]])\n",
    "cone_prox = rot[0,0]*cone_pos[:,0]+rot[0,1]*cone_pos[:,1]+rot[0,2]*cone_pos[:,2]\n",
    "cone_proy = rot[1,0]*cone_pos[:,0]+rot[1,1]*cone_pos[:,1]+rot[1,2]*cone_pos[:,2]\n",
    "neig_prox = rot[0,0]*myneighbourg[0]+rot[0,1]*myneighbourg[1]+rot[0,2]*myneighbourg[2]\n",
    "neig_proy = rot[1,0]*myneighbourg[0]+rot[1,1]*myneighbourg[1]+rot[1,2]*myneighbourg[2]"
   ]
366
367
368
  },
  {
   "cell_type": "code",
369
   "execution_count": 101,
370
   "metadata": {
371
372
    "collapsed": true,
    "hide_input": false
373
   },
374
   "outputs": [],
375
   "source": [
376
377
378
379
380
381
382
383
384
385
386
    "bins_pot_los = np.linspace(0.,myhydro.dm.r.max(),512)\n",
    "mean_phi_los = np.array([])\n",
    "std_phi_los = np.array([])\n",
    "r_phi_los = np.array([])\n",
    "for i in range(len(bins_pot_los)-1):\n",
    "    contidion = (cone_r2>bins_pot_los[i]**2)&(cone_r2<bins_pot_los[i+1]**2)\n",
    "    mean_phi_los = np.append(mean_phi_los,np.average(cone_Phy[contidion]))\n",
    "    std_phi_los = np.append(std_phi_los,np.std((cone_Phy[contidion])))\n",
    "    r_phi_los = np.append(r_phi_los, ((bins_pot_los[i])+(bins_pot_los[i+1]))/2)\n",
    "    \n",
    "    "
387
388
389
390
   ]
  },
  {
   "cell_type": "code",
391
   "execution_count": 102,
392
   "metadata": {
393
394
    "collapsed": false,
    "hide_input": false
395
   },
396
397
   "outputs": [
    {
398
399
400
401
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "r_neigh = 3853.34 kpc, r_max = 2908.43 kpc, pot_max = -27342.01 pc km^2 M_sun s^-2\n"
402
403
404
405
     ]
    }
   ],
   "source": [
406
407
408
409
410
    "tonei = (r_phi_los<np.sqrt(r_nei2))\n",
    "r_relevant = r_phi_los[tonei]\n",
    "R_MAXH = r_relevant[mean_phi_los[tonei]==(mean_phi_los[tonei]).max()][0]\n",
    "pot_maxH = mean_phi_los[tonei].max()\n",
    "print \"r_neigh = {0:.2f} kpc, r_max = {1:0.2f} kpc, pot_max = {2:.2f} pc km^2 M_sun s^-2\".format(np.sqrt(r_nei2),R_MAXH, pot_maxH)"
411
412
413
414
   ]
  },
  {
   "cell_type": "code",
415
   "execution_count": 103,
416
   "metadata": {
417
418
419
420
421
422
423
424
425
426
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#R_MAXH = 1725.09\n",
    "#pot_maxH = -21926.61"
   ]
  },
  {
   "cell_type": "code",
427
   "execution_count": 104,
428
429
   "metadata": {
    "collapsed": false
430
   },
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
   "outputs": [
    {
     "data": {
      "application/javascript": [
       "/* Put everything inside the global mpl namespace */\n",
       "window.mpl = {};\n",
       "\n",
       "mpl.get_websocket_type = function() {\n",
       "    if (typeof(WebSocket) !== 'undefined') {\n",
       "        return WebSocket;\n",
       "    } else if (typeof(MozWebSocket) !== 'undefined') {\n",
       "        return MozWebSocket;\n",
       "    } else {\n",
       "        alert('Your browser does not have WebSocket support.' +\n",
       "              'Please try Chrome, Safari or Firefox ≥ 6. ' +\n",
       "              'Firefox 4 and 5 are also supported but you ' +\n",
       "              'have to enable WebSockets in about:config.');\n",
       "    };\n",
       "}\n",
       "\n",
       "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n",
       "    this.id = figure_id;\n",
       "\n",
       "    this.ws = websocket;\n",
       "\n",
       "    this.supports_binary = (this.ws.binaryType != undefined);\n",
       "\n",
       "    if (!this.supports_binary) {\n",
       "        var warnings = document.getElementById(\"mpl-warnings\");\n",
       "        if (warnings) {\n",
       "            warnings.style.display = 'block';\n",
       "            warnings.textContent = (\n",
       "                \"This browser does not support binary websocket messages. \" +\n",
       "                    \"Performance may be slow.\");\n",
       "        }\n",
       "    }\n",
       "\n",
       "    this.imageObj = new Image();\n",
       "\n",
       "    this.context = undefined;\n",
       "    this.message = undefined;\n",
       "    this.canvas = undefined;\n",
       "    this.rubberband_canvas = undefined;\n",
       "    this.rubberband_context = undefined;\n",
       "    this.format_dropdown = undefined;\n",
       "\n",
       "    this.image_mode = 'full';\n",
       "\n",
       "    this.root = $('<div/>');\n",
       "    this._root_extra_style(this.root)\n",
       "    this.root.attr('style', 'display: inline-block');\n",
       "\n",
       "    $(parent_element).append(this.root);\n",
       "\n",
       "    this._init_header(this);\n",
       "    this._init_canvas(this);\n",
       "    this._init_toolbar(this);\n",
       "\n",
       "    var fig = this;\n",
       "\n",
       "    this.waiting = false;\n",
       "\n",
       "    this.ws.onopen =  function () {\n",
       "            fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n",
       "            fig.send_message(\"send_image_mode\", {});\n",
       "            fig.send_message(\"refresh\", {});\n",
       "        }\n",
       "\n",
       "    this.imageObj.onload = function() {\n",
       "            if (fig.image_mode == 'full') {\n",
       "                // Full images could contain transparency (where diff images\n",
       "                // almost always do), so we need to clear the canvas so that\n",
       "                // there is no ghosting.\n",
       "                fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n",
       "            }\n",
       "            fig.context.drawImage(fig.imageObj, 0, 0);\n",
       "        };\n",
       "\n",
       "    this.imageObj.onunload = function() {\n",
       "        this.ws.close();\n",
       "    }\n",
       "\n",
       "    this.ws.onmessage = this._make_on_message_function(this);\n",
       "\n",
       "    this.ondownload = ondownload;\n",
       "}\n",
       "\n",
       "mpl.figure.prototype._init_header = function() {\n",
       "    var titlebar = $(\n",
       "        '<div class=\"ui-dialog-titlebar ui-widget-header ui-corner-all ' +\n",
       "        'ui-helper-clearfix\"/>');\n",
       "    var titletext = $(\n",
       "        '<div class=\"ui-dialog-title\" style=\"width: 100%; ' +\n",
       "        'text-align: center; padding: 3px;\"/>');\n",
       "    titlebar.append(titletext)\n",
       "    this.root.append(titlebar);\n",
       "    this.header = titletext[0];\n",
       "}\n",
       "\n",
       "\n",
       "\n",
       "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n",
       "\n",
       "}\n",
       "\n",
       "\n",
       "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n",
       "\n",
       "}\n",
       "\n",
       "mpl.figure.prototype._init_canvas = function() {\n",
       "    var fig = this;\n",
       "\n",
       "    var canvas_div = $('<div/>');\n",
       "\n",
       "    canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n",
       "\n",
       "    function canvas_keyboard_event(event) {\n",
       "        return fig.key_event(event, event['data']);\n",
       "    }\n",
       "\n",
       "    canvas_div.keydown('key_press', canvas_keyboard_event);\n",
       "    canvas_div.keyup('key_release', canvas_keyboard_event);\n",
       "    this.canvas_div = canvas_div\n",
       "    this._canvas_extra_style(canvas_div)\n",
       "    this.root.append(canvas_div);\n",
       "\n",
       "    var canvas = $('<canvas/>');\n",
       "    canvas.addClass('mpl-canvas');\n",
       "    canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n",
       "\n",
       "    this.canvas = canvas[0];\n",
       "    this.context = canvas[0].getContext(\"2d\");\n",
       "\n",
       "    var rubberband = $('<canvas/>');\n",
       "    rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n",
       "\n",
       "    var pass_mouse_events = true;\n",
       "\n",
       "    canvas_div.resizable({\n",
       "        start: function(event, ui) {\n",
       "            pass_mouse_events = false;\n",
       "        },\n",
       "        resize: function(event, ui) {\n",
       "            fig.request_resize(ui.size.width, ui.size.height);\n",
       "        },\n",
       "        stop: function(event, ui) {\n",
       "            pass_mouse_events = true;\n",
       "            fig.request_resize(ui.size.width, ui.size.height);\n",
       "        },\n",
       "    });\n",
       "\n",
       "    function mouse_event_fn(event) {\n",
       "        if (pass_mouse_events)\n",
       "            return fig.mouse_event(event, event['data']);\n",
       "    }\n",
       "\n",
       "    rubberband.mousedown('button_press', mouse_event_fn);\n",
       "    rubberband.mouseup('button_release', mouse_event_fn);\n",
       "    // Throttle sequential mouse events to 1 every 20ms.\n",
       "    rubberband.mousemove('motion_notify', mouse_event_fn);\n",
       "\n",
       "    rubberband.mouseenter('figure_enter', mouse_event_fn);\n",
       "    rubberband.mouseleave('figure_leave', mouse_event_fn);\n",
       "\n",
       "    canvas_div.on(\"wheel\", function (event) {\n",
       "        event = event.originalEvent;\n",
       "        event['data'] = 'scroll'\n",
       "        if (event.deltaY < 0) {\n",
       "            event.step = 1;\n",
       "        } else {\n",
       "            event.step = -1;\n",
       "        }\n",
       "        mouse_event_fn(event);\n",
       "    });\n",
       "\n",
       "    canvas_div.append(canvas);\n",
       "    canvas_div.append(rubberband);\n",
       "\n",
       "    this.rubberband = rubberband;\n",
       "    this.rubberband_canvas = rubberband[0];\n",
       "    this.rubberband_context = rubberband[0].getContext(\"2d\");\n",
       "    this.rubberband_context.strokeStyle = \"#000000\";\n",
       "\n",
       "    this._resize_canvas = function(width, height) {\n",
       "        // Keep the size of the canvas, canvas container, and rubber band\n",
       "        // canvas in synch.\n",
       "        canvas_div.css('width', width)\n",
       "        canvas_div.css('height', height)\n",
       "\n",
       "        canvas.attr('width', width);\n",
       "        canvas.attr('height', height);\n",
       "\n",
       "        rubberband.attr('width', width);\n",
       "        rubberband.attr('height', height);\n",
       "    }\n",
       "\n",
       "    // Set the figure to an initial 600x600px, this will subsequently be updated\n",
       "    // upon first draw.\n",
       "    this._resize_canvas(600, 600);\n",
       "\n",
       "    // Disable right mouse context menu.\n",
       "    $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n",
       "        return false;\n",
       "    });\n",
       "\n",
       "    function set_focus () {\n",
       "        canvas.focus();\n",
       "        canvas_div.focus();\n",
       "    }\n",
       "\n",
       "    window.setTimeout(set_focus, 100);\n",
       "}\n",
       "\n",
       "mpl.figure.prototype._init_toolbar = function() {\n",
       "    var fig = this;\n",
       "\n",
       "    var nav_element = $('<div/>')\n",
       "    nav_element.attr('style', 'width: 100%');\n",
       "    this.root.append(nav_element);\n",
       "\n",
       "    // Define a callback function for later on.\n",
       "    function toolbar_event(event) {\n",
       "        return fig.toolbar_button_onclick(event['data']);\n",
       "    }\n",
       "    function toolbar_mouse_event(event) {\n",
       "        return fig.toolbar_button_onmouseover(event['data']);\n",
       "    }\n",
       "\n",
       "    for(var toolbar_ind in mpl.toolbar_items) {\n",
       "        var name = mpl.toolbar_items[toolbar_ind][0];\n",
       "        var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
       "        var image = mpl.toolbar_items[toolbar_ind][2];\n",
       "        var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
       "\n",
       "        if (!name) {\n",
       "            // put a spacer in here.\n",
       "            continue;\n",
       "        }\n",
       "        var button = $('<button/>');\n",
       "        button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +\n",
       "                        'ui-button-icon-only');\n",
       "        button.attr('role', 'button');\n",
       "        button.attr('aria-disabled', 'false');\n",
       "        button.click(method_name, toolbar_event);\n",
       "        button.mouseover(tooltip, toolbar_mouse_event);\n",
       "\n",
       "        var icon_img = $('<span/>');\n",
       "        icon_img.addClass('ui-button-icon-primary ui-icon');\n",
       "        icon_img.addClass(image);\n",
       "        icon_img.addClass('ui-corner-all');\n",
       "\n",
       "        var tooltip_span = $('<span/>');\n",
       "        tooltip_span.addClass('ui-button-text');\n",
       "        tooltip_span.html(tooltip);\n",
       "\n",
       "        button.append(icon_img);\n",
       "        button.append(tooltip_span);\n",
       "\n",
       "        nav_element.append(button);\n",
       "    }\n",
       "\n",
       "    var fmt_picker_span = $('<span/>');\n",
       "\n",
       "    var fmt_picker = $('<select/>');\n",
       "    fmt_picker.addClass('mpl-toolbar-option ui-widget ui-widget-content');\n",
       "    fmt_picker_span.append(fmt_picker);\n",
       "    nav_element.append(fmt_picker_span);\n",
       "    this.format_dropdown = fmt_picker[0];\n",
       "\n",
       "    for (var ind in mpl.extensions) {\n",
       "        var fmt = mpl.extensions[ind];\n",
       "        var option = $(\n",
       "            '<option/>', {selected: fmt === mpl.default_extension}).html(fmt);\n",
       "        fmt_picker.append(option)\n",
       "    }\n",
       "\n",
       "    // Add hover states to the ui-buttons\n",
       "    $( \".ui-button\" ).hover(\n",
       "        function() { $(this).addClass(\"ui-state-hover\");},\n",
       "        function() { $(this).removeClass(\"ui-state-hover\");}\n",
       "    );\n",
       "\n",
       "    var status_bar = $('<span class=\"mpl-message\"/>');\n",
       "    nav_element.append(status_bar);\n",
       "    this.message = status_bar[0];\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {\n",
       "    // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n",
       "    // which will in turn request a refresh of the image.\n",
       "    this.send_message('resize', {'width': x_pixels, 'height': y_pixels});\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.send_message = function(type, properties) {\n",
       "    properties['type'] = type;\n",
       "    properties['figure_id'] = this.id;\n",
       "    this.ws.send(JSON.stringify(properties));\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.send_draw_message = function() {\n",
       "    if (!this.waiting) {\n",
       "        this.waiting = true;\n",
       "        this.ws.send(JSON.stringify({type: \"draw\", figure_id: this.id}));\n",
       "    }\n",
       "}\n",
       "\n",
       "\n",
       "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
       "    var format_dropdown = fig.format_dropdown;\n",
       "    var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n",
       "    fig.ondownload(fig, format);\n",
       "}\n",
       "\n",
       "\n",
       "mpl.figure.prototype.handle_resize = function(fig, msg) {\n",
       "    var size = msg['size'];\n",
       "    if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {\n",
       "        fig._resize_canvas(size[0], size[1]);\n",
       "        fig.send_message(\"refresh\", {});\n",
       "    };\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.handle_rubberband = function(fig, msg) {\n",
       "    var x0 = msg['x0'];\n",
       "    var y0 = fig.canvas.height - msg['y0'];\n",
       "    var x1 = msg['x1'];\n",
       "    var y1 = fig.canvas.height - msg['y1'];\n",
       "    x0 = Math.floor(x0) + 0.5;\n",
       "    y0 = Math.floor(y0) + 0.5;\n",
       "    x1 = Math.floor(x1) + 0.5;\n",
       "    y1 = Math.floor(y1) + 0.5;\n",
       "    var min_x = Math.min(x0, x1);\n",
       "    var min_y = Math.min(y0, y1);\n",
       "    var width = Math.abs(x1 - x0);\n",
       "    var height = Math.abs(y1 - y0);\n",
       "\n",
       "    fig.rubberband_context.clearRect(\n",
       "        0, 0, fig.canvas.width, fig.canvas.height);\n",
       "\n",
       "    fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.handle_figure_label = function(fig, msg) {\n",
       "    // Updates the figure title.\n",
       "    fig.header.textContent = msg['label'];\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.handle_cursor = function(fig, msg) {\n",
       "    var cursor = msg['cursor'];\n",
       "    switch(cursor)\n",
       "    {\n",
       "    case 0:\n",
       "        cursor = 'pointer';\n",
       "        break;\n",
       "    case 1:\n",
       "        cursor = 'default';\n",
       "        break;\n",
       "    case 2:\n",
       "        cursor = 'crosshair';\n",
       "        break;\n",
       "    case 3:\n",
       "        cursor = 'move';\n",
       "        break;\n",
       "    }\n",
       "    fig.rubberband_canvas.style.cursor = cursor;\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.handle_message = function(fig, msg) {\n",
       "    fig.message.textContent = msg['message'];\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.handle_draw = function(fig, msg) {\n",
       "    // Request the server to send over a new figure.\n",
       "    fig.send_draw_message();\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.handle_image_mode = function(fig, msg) {\n",
       "    fig.image_mode = msg['mode'];\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.updated_canvas_event = function() {\n",
       "    // Called whenever the canvas gets updated.\n",
       "    this.send_message(\"ack\", {});\n",
       "}\n",
       "\n",
       "// A function to construct a web socket function for onmessage handling.\n",
       "// Called in the figure constructor.\n",
       "mpl.figure.prototype._make_on_message_function = function(fig) {\n",
       "    return function socket_on_message(evt) {\n",
       "        if (evt.data instanceof Blob) {\n",
       "            /* FIXME: We get \"Resource interpreted as Image but\n",
       "             * transferred with MIME type text/plain:\" errors on\n",
       "             * Chrome.  But how to set the MIME type?  It doesn't seem\n",
       "             * to be part of the websocket stream */\n",
       "            evt.data.type = \"image/png\";\n",
       "\n",
       "            /* Free the memory for the previous frames */\n",
       "            if (fig.imageObj.src) {\n",
       "                (window.URL || window.webkitURL).revokeObjectURL(\n",
       "                    fig.imageObj.src);\n",
       "            }\n",
       "\n",
       "            fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n",
       "                evt.data);\n",
       "            fig.updated_canvas_event();\n",
       "            fig.waiting = false;\n",
       "            return;\n",
       "        }\n",
       "        else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == \"data:image/png;base64\") {\n",
       "            fig.imageObj.src = evt.data;\n",
       "            fig.updated_canvas_event();\n",
       "            fig.waiting = false;\n",
       "            return;\n",
       "        }\n",
       "\n",
       "        var msg = JSON.parse(evt.data);\n",
       "        var msg_type = msg['type'];\n",
       "\n",
       "        // Call the  \"handle_{type}\" callback, which takes\n",
       "        // the figure and JSON message as its only arguments.\n",
       "        try {\n",
       "            var callback = fig[\"handle_\" + msg_type];\n",
       "        } catch (e) {\n",
       "            console.log(\"No handler for the '\" + msg_type + \"' message type: \", msg);\n",
       "            return;\n",
       "        }\n",
       "\n",
       "        if (callback) {\n",
       "            try {\n",
       "                // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n",
       "                callback(fig, msg);\n",
       "            } catch (e) {\n",
       "                console.log(\"Exception inside the 'handler_\" + msg_type + \"' callback:\", e, e.stack, msg);\n",
       "            }\n",
       "        }\n",
       "    };\n",
       "}\n",
       "\n",
       "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n",
       "mpl.findpos = function(e) {\n",
       "    //this section is from http://www.quirksmode.org/js/events_properties.html\n",
       "    var targ;\n",
       "    if (!e)\n",
       "        e = window.event;\n",
       "    if (e.target)\n",
       "        targ = e.target;\n",
       "    else if (e.srcElement)\n",
       "        targ = e.srcElement;\n",
       "    if (targ.nodeType == 3) // defeat Safari bug\n",
       "        targ = targ.parentNode;\n",
       "\n",
       "    // jQuery normalizes the pageX and pageY\n",
       "    // pageX,Y are the mouse positions relative to the document\n",
       "    // offset() returns the position of the element relative to the document\n",
       "    var x = e.pageX - $(targ).offset().left;\n",
       "    var y = e.pageY - $(targ).offset().top;\n",
       "\n",
       "    return {\"x\": x, \"y\": y};\n",
       "};\n",
       "\n",
       "/*\n",
       " * return a copy of an object with only non-object keys\n",
       " * we need this to avoid circular references\n",
       " * http://stackoverflow.com/a/24161582/3208463\n",
       " */\n",
       "function simpleKeys (original) {\n",
       "  return Object.keys(original).reduce(function (obj, key) {\n",
       "    if (typeof original[key] !== 'object')\n",
       "        obj[key] = original[key]\n",
       "    return obj;\n",
       "  }, {});\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.mouse_event = function(event, name) {\n",
       "    var canvas_pos = mpl.findpos(event)\n",
       "\n",
       "    if (name === 'button_press')\n",
       "    {\n",
       "        this.canvas.focus();\n",
       "        this.canvas_div.focus();\n",
       "    }\n",
       "\n",
       "    var x = canvas_pos.x;\n",
       "    var y = canvas_pos.y;\n",
       "\n",
       "    this.send_message(name, {x: x, y: y, button: event.button,\n",
       "                             step: event.step,\n",
       "                             guiEvent: simpleKeys(event)});\n",
       "\n",
       "    /* This prevents the web browser from automatically changing to\n",
       "     * the text insertion cursor when the button is pressed.  We want\n",
       "     * to control all of the cursor setting manually through the\n",
       "     * 'cursor' event from matplotlib */\n",
       "    event.preventDefault();\n",
       "    return false;\n",
       "}\n",
       "\n",
       "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
       "    // Handle any extra behaviour associated with a key event\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.key_event = function(event, name) {\n",
       "\n",
       "    // Prevent repeat events\n",
       "    if (name == 'key_press')\n",
       "    {\n",
       "        if (event.which === this._key)\n",
       "            return;\n",
       "        else\n",
       "            this._key = event.which;\n",
       "    }\n",
       "    if (name == 'key_release')\n",
       "        this._key = null;\n",
       "\n",
       "    var value = '';\n",
       "    if (event.ctrlKey && event.which != 17)\n",
       "        value += \"ctrl+\";\n",
       "    if (event.altKey && event.which != 18)\n",
       "        value += \"alt+\";\n",
       "    if (event.shiftKey && event.which != 16)\n",
       "        value += \"shift+\";\n",
       "\n",
       "    value += 'k';\n",
       "    value += event.which.toString();\n",
       "\n",
       "    this._key_event_extra(event, name);\n",
       "\n",
       "    this.send_message(name, {key: value,\n",
       "                             guiEvent: simpleKeys(event)});\n",
       "    return false;\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.toolbar_button_onclick = function(name) {\n",
       "    if (name == 'download') {\n",
       "        this.handle_save(this, null);\n",
       "    } else {\n",
       "        this.send_message(\"toolbar_button\", {name: name});\n",
       "    }\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.toolbar_button_onmouseover = function(tooltip) {\n",
       "    this.message.textContent = tooltip;\n",
       "};\n",
       "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to  previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Pan axes with left mouse, zoom with right\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n",
       "\n",
       "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n",
       "\n",
       "mpl.default_extension = \"png\";var comm_websocket_adapter = function(comm) {\n",
       "    // Create a \"websocket\"-like object which calls the given IPython comm\n",
       "    // object with the appropriate methods. Currently this is a non binary\n",
       "    // socket, so there is still some room for performance tuning.\n",
       "    var ws = {};\n",
       "\n",
       "    ws.close = function() {\n",
       "        comm.close()\n",
       "    };\n",
       "    ws.send = function(m) {\n",
       "        //console.log('sending', m);\n",
       "        comm.send(m);\n",
       "    };\n",
       "    // Register the callback with on_msg.\n",
       "    comm.on_msg(function(msg) {\n",
       "        //console.log('receiving', msg['content']['data'], msg);\n",
       "        // Pass the mpl event to the overriden (by mpl) onmessage function.\n",
       "        ws.onmessage(msg['content']['data'])\n",
       "    });\n",
       "    return ws;\n",
       "}\n",
       "\n",
For faster browsing, not all history is shown. View entire blame