| 34 | from ocelot import * |
| 35 | from ocelot.gui.accelerator import * |
| 36 | |
| 37 | def func(x): |
| 38 | global cnt, QM1, QM2, tws, lat, tws0 |
| 39 | x0=x[:,0][0] |
| 40 | x1=x[:,1][0] |
| 41 | |
| 42 | # update optics |
| 43 | QM1.k1 = x0 |
| 44 | QM2.k1 = x1 |
| 45 | lat.update_transfer_maps() |
| 46 | tws = twiss(lat, tws0, nPoints=1000) |
| 47 | |
| 48 | idx = -1 # last point of the lattice |
| 49 | sx = np.sqrt(tws[idx].beta_x) |
| 50 | sy = np.sqrt(tws[idx].beta_y) |
| 51 | |
| 52 | # Evaluation Function Example |
| 53 | val = np.abs(sx) + np.abs(sy) |
| 54 | # val = np.abs(sx*sy) |
| 55 | # val = np.log(np.abs((sx+10)*(sy+10))) |
| 56 | # val = -1.0/np.abs((sx+10)*(sy+10)) |
| 57 | |
| 58 | print("%d: %+8.3f,%+8.3f,%+8.3f,%+8.3f,%+8.3f"%(cnt, x0, x1, sx, sy, val)) |
| 59 | cnt = cnt + 1 |
| 60 | return val |
| 61 | |
| 62 | |
| 63 | # ==== Main ===== |
| 64 | |
| 65 | # Define Optics |
| 66 | ## Drift |
| 67 | L20 = Drift(l=0.2, eid='L20') |
| 68 | L50 = Drift(l=0.5, eid='L50') |
| 69 | ## Quadrupoles |
| 70 | QM1 = Quadrupole(l=0.2, k1=3.9, eid='QM1') |
| 71 | QM2 = Quadrupole(l=0.2, k1=-3.25, eid='QM2') |
| 72 | ## Lattice |
| 73 | cell = (L50, QM1, L20, QM2, L50, L50) |
| 74 | lat = MagneticLattice(cell, stop=None) |
| 75 | print("length of the cell: ", lat.totalLen, " m") |
| 76 | tws0 = Twiss() |
| 77 | tws0.beta_x = 20.0 |
| 78 | tws0.beta_y = 30.0 |
| 79 | tws0.alpha_x = -10.0 |
| 80 | tws0.alpha_y = -5.0 |
| 81 | tws0.emit_x = 1.0 |
| 82 | tws0.emit_y = 1.0 |
| 83 | tws0.E = 1.0 |
| 84 | |
| 85 | tws = twiss(lat, tws0, nPoints=1000) |
| 86 | |
| 87 | # GP Optimization |
| 88 | print("==== start ====") |
| 89 | print("# cnt, x0, x1, sx, sy, eval_val") |
| 90 | |
| 91 | cnt = 0 |
| 92 | bounds = [{'name':'x0', 'type':'continuous', 'domain':(-20, 20)}, |
| 93 | {'name':'x1', 'type':'continuous', 'domain':(-20, 20)}] |
| 94 | |
| 95 | myBopt = GPyOpt.methods.BayesianOptimization(f=func,domain=bounds,initial_design_numdata=10,acquisition_type='LCB') |
| 96 | |
| 97 | myBopt.run_optimization(max_iter=50) |
| 98 | myBopt.plot_acquisition() |
| 99 | myBopt.plot_convergence() |
| 100 | print("Best = ", myBopt.x_opt) |
| 101 | print("eval_val = ", func(np.array([myBopt.x_opt]))) |
| 102 | |
| 103 | QM1.k1 = myBopt.x_opt[0] |
| 104 | QM2.k1 = myBopt.x_opt[1] |
| 105 | lat.update_transfer_maps() |
| 106 | tws = twiss(lat, tws0, nPoints=1000) |
| 107 | |
| 108 | s = [p.s for p in tws] |
| 109 | beta_x = [p.beta_x for p in tws] |
| 110 | beta_y = [p.beta_y for p in tws] |
| 111 | |
| 112 | plt.plot(s, beta_x, 'b-'); |
| 113 | plt.plot(s, beta_y, 'r-'); |
| 114 | |
| 115 | plt.legend(['Horiz', 'Vert']) |
| 116 | plt.xlabel('s [m]') |
| 117 | plt.ylabel('beta [m]') |
| 118 | plt.grid(True) |
| 119 | plt.show() |