Пример #1
0
def verify_CECE_LOS(ECRad_results_file):
    res = ECRadResults()
    res.load(ECRad_results_file)
    x,y = plot1DECE(project="toroidal" , freq=res.Scenario["diagnostic"]["f"][0][0]/1.e9,doPlot=False, verb=False)
    R,z = plot1DECE(project="poloidal" , freq=res.Scenario["diagnostic"]["f"][0][0]/1.e9,doPlot=False, verb=False)
    fig_top = plt.figure()
    ax_top = fig_top.add_subplot(111)
    fig_side = plt.figure()
    ax_side = fig_side.add_subplot(111)
    label_Pedro = "Pedro"
    for i in [0, 2, 4]:
        ax_top.plot(x, y.T[i], "--", label=label_Pedro)
        ax_side.plot(R, z.T[i], "--", label=label_Pedro)
        label_Pedro =None
    label_ECRad = "ECRad"
    for ir in range(res.Config["Physics"]["N_ray"]):
        phi = np.arctan2(np.array(res["ray"]["y"][0][0][0][ir],dtype=np.float), 
                         np.array(res["ray"]["x"][0][0][0][ir],dtype=np.float))
        phi_rot = 22.5 * 8.5
        x_ECRad = res["ray"]["R"][0][0][0][ir] * np.cos(phi - np.deg2rad(phi_rot))
        y_ECRad = res["ray"]["R"][0][0][0][ir] * np.sin(phi - np.deg2rad(phi_rot))
        ax_top.plot(x_ECRad, y_ECRad, "-", label=label_ECRad)
        ax_side.plot(res["ray"]["R"][0][0][0][ir], res["ray"]["z"][0][0][0][ir], "-", label=label_ECRad)
        label_ECRad = None
    ax_top.set_xlabel(r"$x$ [m]")
    ax_top.set_xlim(1,3)
    ax_top.set_ylim(-0.1,0.2)
    ax_top.set_ylabel(r"$y$ [m]")
    ax_side.set_xlabel(r"$R$ [m]")
    ax_side.set_ylabel(r"$z$ [m]")
    ax_side.set_xlim(1,3)
    ax_side.set_ylim(-0.1,0.2)
    ax_top.legend()
    ax_side.legend()
    plt.show()
Пример #2
0
def get_BPD_width(Results, itime=0, logfile=None):
    # Gaussian fit of all BPD
    plt.figure()
    for ich in range(len(Results.Scenario["diagnostic"]["f"][itime])):
        params = np.zeros(3)
        params[0] = np.max(Results["BPD"]["BPD"][itime][ich][0])
        params[1] = Results["resonance"]["rhop_warm"][0][itime][ich]
        params[2] = 0.05
        fitted_params, unc = make_fit("gauss", Results["BPD"]["rhop"][itime][ich][0], Results["BPD"]["BPD"][itime][ich][0], 
                p_est = params)
        plt.plot(Results["BPD"]["rhop"][itime][ich][0], Results["BPD"]["BPD"][itime][ich][0], label=f"original ch. {ich+1}")
        plt.plot(Results["BPD"]["rhop"][itime][ich][0], 
                gauss_fit_func(Results["BPD"]["rhop"][itime][ich][0], fitted_params[0], 
                               fitted_params[1], fitted_params[2]), linestyle="--", label=f"fit ch. {ich+1}")
        if(logfile is not None):
            logfile.write("Channel {0:d} rho_pol position: {1:1.3f}\n".format(ich + 1, fitted_params[1]))
            logfile.write("Channel {0:d} rho_pol width: {1:1.3f}\n".format(ich + 1, fitted_params[2]))
        else:
            print("Channel {0:d} rho_pol width: {1:1.3f}".format(ich + 1, fitted_params[2]))
        mask = Results["ray"]["rhop"][itime][ich][0][0] > 0.0
        R_center_spl = InterpolatedUnivariateSpline(Results["ray"]["s"][itime][ich][0][0][mask], 
                                                    Results["ray"]["rhop"][itime][ich][0][0][mask]
                                                    - fitted_params[1])
        R_in_spl = InterpolatedUnivariateSpline(Results["ray"]["s"][itime][ich][0][0][mask], 
                                                Results["ray"]["rhop"][itime][ich][0][0][mask]
                                                 - fitted_params[1] + fitted_params[2]/2.0)
        R_out_spl = InterpolatedUnivariateSpline(Results["ray"]["s"][itime][ich][0][0][mask], 
                                                Results["ray"]["rhop"][itime][ich][0][0][mask]
                                                 - fitted_params[1] - fitted_params[2]/2.0)
        R_spl =  InterpolatedUnivariateSpline(Results["ray"]["s"][itime][ich][0][0], 
                                              Results["ray"]["R"][itime][ich][0][0]) 
        s_center_roots = R_center_spl.roots()
        s_center = s_center_roots[np.argmin(np.abs(s_center_roots - Results["resonance"]["s_cold"][0][itime][ich]))]                        
        s_in_roots = R_in_spl.roots()
        s_in = s_in_roots[np.argmin(np.abs(s_in_roots - Results["resonance"]["s_cold"][0][itime][ich]))]
        s_out_roots = R_out_spl.roots()
        s_out = s_out_roots[np.argmin(np.abs(s_out_roots - Results["resonance"]["s_cold"][0][itime][ich]))]
        width = np.abs(R_spl(s_in)-R_spl(s_out))
        if(logfile is not None):
            logfile.write("Channel {0:d} R position: {1:1.3f} cm\n".format(ich + 1, R_spl(s_center)))
            logfile.write("Channel {0:d} R width: {1:1.3f} cm\n".format(ich + 1, width*1.e2))
        else:
            print("Channel {0:d} R width: {1:1.3f} cm\n".format(ich + 1, width*1.e2))
    plt.legend()
    plt.gca().set_xlabel(r"$\rho_\mathrm{pol}$")
    plt.gca().set_ylabel(r"$D_\omega$")
    plt.suptitle(f"\# {Results.Scenario['shot']}")
Пример #3
0
def plot_harmonics_and_frequencies(res_file):
    Results = ECRadResults()
    Results.load(res_file)
    fig = plt.figure()
    pc_obj = PlottingCore(fig=fig)
    ich_list = np.arange(0,
                         len(Results.Scenario["diagnostic"]["f"][0]),
                         3,
                         dtype=np.int)
    imode_list = np.zeros(ich_list.shape, dtype=np.int)
    ir_list = np.zeros(ich_list.shape, dtype=np.int)
    pc_obj.B_plot(Results, 0, ich_list, imode_list, ir_list)
    plt.show()
 def plot_Te_ne(self):
     from Plotting_Configuration import plt
     fig = plt.figure()
     ax = fig.add_subplot(211)
     ax_ne = fig.add_subplot(212, sharex=ax)
     ax.plot(self.rhop_1D_profs, self.Te_init/1.e3, label=r"$T_\mathrm{e,init}$")
     ax.plot(self.rhop, self.Te/1.e3, label=r"$T_\mathrm{e}$")
     ax_ne.plot(self.rhop_1D_profs, self.ne_init / 1.e19, label=r"$n_\mathrm{e,init}$")
     ax_ne.plot(self.rhop, self.ne / 1.e19, label=r"$n_\mathrm{e}$")
     ax_ne.set_xlabel(r"$\rho_\mathrm{pol}$")
     ax.set_ylabel(r"$T_\mathrm{e}$ [keV]")
     ax_ne.set_ylabel(r"$n_\mathrm{e}$ [10$^{19}\times$ m$^{-3}$]")
     ax.legend()
     ax_ne.legend()
    def __init__(self, parent, figure_width=12.0, figure_height=8.5):
        wx.Panel.__init__(self, parent, wx.ID_ANY)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(self.sizer)
        self.ctrl_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.fig = plt.figure(figsize=(figure_width, figure_height),
                              tight_layout=True,
                              frameon=False)
        self.fig.clf()
        self.linestyles = ["-", "--", ":", "-."]
        self.markers = ["^", "v", "+", "d", "o"]
        self.cmap = plt.cm.ScalarMappable(plt.Normalize(0, 1), "rainbow")
        self.canvas = FigureCanvas(self, -1, self.fig)
        self.axlist = []
        self.canvas.mpl_connect('motion_notify_event', self.UpdateCoords)
        self.Bind(EVT_DONE_PLOTTING, self.OnDonePlotting)
        self.plot_toolbar = NavigationToolbar2Wx(self.canvas)
        fw, th = self.plot_toolbar.GetSize().Get()
        self.plot_toolbar.SetSize(wx.Size(fw, th))
        self.plot_toolbar.Realize()
        self.ctrl_sizer.Add(self.plot_toolbar, 0, wx.ALL | \
                wx.ALIGN_CENTER_VERTICAL , 5)
        self.lower_lim_tc = simple_label_tc(self, "lower limit", 0.0, "real")
        self.upper_lim_tc = simple_label_tc(self, "upper limit", 0.0, "real")
        self.axis_choice = wx.Choice(self, wx.ID_ANY)
        self.axis_choice.Append("x")
        self.axis_choice.Append("y1")
        self.axis_choice.Append("y2")
        self.axis_choice.Select(0)
        self.set_lim_button = wx.Button(self, wx.ID_ANY, "Set axis limits")
        self.set_lim_button.Bind(wx.EVT_BUTTON, self.OnSetLim)
        self.auto_lim_button = wx.Button(self, wx.ID_ANY, "Auto limits")
        self.auto_lim_button.Bind(wx.EVT_BUTTON, self.OnAutoLim)
        self.ctrl_sizer.Add(self.lower_lim_tc, 0, wx.ALL | \
                wx.ALIGN_CENTER_VERTICAL , 5)
        self.ctrl_sizer.Add(self.upper_lim_tc, 0, wx.ALL | \
                wx.ALIGN_CENTER_VERTICAL , 5)
        self.ctrl_sizer.Add(self.axis_choice, 0, wx.ALL | \
                wx.ALIGN_CENTER_VERTICAL , 5)
        self.ctrl_sizer.Add(self.set_lim_button, 0, wx.ALL | \
                wx.ALIGN_CENTER_VERTICAL , 5)
        self.ctrl_sizer.Add(self.auto_lim_button, 0, wx.ALL | \
                wx.ALIGN_CENTER_VERTICAL , 5)
        self.sizer.Add(self.ctrl_sizer, 0, wx.ALL | wx.LEFT, 5)
        self.sizer.Add(self.canvas, 0, wx.ALL | \
                       wx.LEFT, 5)
Пример #6
0
def current_weight(DistWaveFile,
                   shot,
                   time,
                   EQ_exp,
                   EQ_diag,
                   EQ_ed,
                   fig=None,
                   ax=None):
    dist_obj = load_f_from_mat(DistWaveFile, True)
    dist_mat = loadmat(DistWaveFile, squeeze_me=True)
    waves = read_dist_mat_to_beam(dist_mat, True)
    ECCD_weight = np.zeros(dist_obj.f_cycl[0].shape)
    j_spl = InterpolatedUnivariateSpline(waves.rhop, waves.j)
    j_tot = j_spl.integral(waves.rhop[0], waves.rhop[-1])
    EQ_aug_obj = EQData(shot, EQ_exp=EQ_exp, EQ_diag=EQ_diag, EQ_ed=EQ_ed)
    EQ_aug_obj.init_read_from_shotfile()
    Vol = EQ_aug_obj.getQuantity(dist_obj.rhop, "Vol", time)
    Vol_spl = InterpolatedUnivariateSpline(dist_obj.rhop, Vol)
    for irhop, rhop in enumerate(dist_obj.rhop):
        weight = np.abs(waves.j[irhop] / j_tot) * Vol_spl(rhop, nu=1)
        for i, u_par in enumerate(dist_obj.ull):
            for j, u_perp in enumerate(dist_obj.uxx):
                f_diff = dist_obj.f_cycl[irhop][i, j] - Juettner2D(
                    u_par, u_perp, dist_obj.Te[irhop])
                ECCD_weight[i,
                            j] += weight * f_diff * u_par / np.sqrt(1.0 +
                                                                    u_par**2 +
                                                                    u_perp**2)
    ECCD_weight /= np.max(np.abs(ECCD_weight.flatten()))
    if (fig is None):
        fig = plt.figure()
    if (ax is None):
        ax = fig.add_subplot(111)
    ax.contourf(dist_obj.uxx, dist_obj.ull, ECCD_weight, \
                 levels = np.linspace(-1,1,30), cmap = plt.get_cmap("coolwarm"))
    ax.set_ylabel(r"$u_\parallel$")
    ax.set_xlabel(r"$u_\perp$")
    m = cm.ScalarMappable(cmap=plt.cm.get_cmap("coolwarm"))
    m.set_array(np.linspace(-1.0, 1.0, 30))
    cb_j = fig.colorbar(m, pad=0.15, ticks=[-1.0, 0.0, 1.0])
    cb_j.set_label(r"$(f - f_0) \beta_\parallel [\si{{a.u.}}]$")
    ax.set_aspect("equal")
Пример #7
0
def torbeam_interface(working_dir, shot, time, itime, plasma_dict, eq_slice, ece_launch, R_res, z_res,
                      wg=8, dtoECESI=0.055, corr=0.85, logfile=None, TB_plot=True, only_TB=False):
    cece_launches = []
    for ich in range(len(ece_launch["f"])):
        cece_launches.append(launch())
        cece_launches[-1].parse_custom(ece_launch["f"][ich], ece_launch["R"][ich] * np.cos(np.deg2rad(ece_launch["phi"][ich])), 
                                ece_launch["R"][ich] * np.sin(np.deg2rad(ece_launch["phi"][ich])), ece_launch["z"][ich], 
                                ece_launch["phi_tor"][ich], ece_launch["theta_pol"][ich], ece_launch["width"][ich], ece_launch["dist_focus"][ich])
    make_TORBEAM_no_data_load(working_dir, shot, time, plasma_dict["rhop_prof"][itime], plasma_dict["Te"][itime], plasma_dict["ne"][itime], 
                              eq_slice.R, eq_slice.z, eq_slice.Psi, eq_slice.Br, eq_slice.Bt, eq_slice.Bz,
                              eq_slice.Psi_ax, eq_slice.Psi_sep, cece_launches, ITM=False, 
                              ITER=False, mode = -1)
    for ich in range(len(ece_launch["f"])):
        TB_failed = False
        Rz_data = np.loadtxt(os.path.join(working_dir, "{0:d}_{1:1.3f}_rays".format(shot, time), 
                             "Rz_beam_{0:1d}.dat".format(ich + 1).replace(",", "")))
        R_center = Rz_data.T[0] * 1.e-2
        mask = np.logical_and(R_center > np.min(eq_slice.R), R_center < np.max(eq_slice.R))
        z_center = Rz_data.T[1] * 1.e-2
        mask[np.logical_and(z_center < np.min(eq_slice.z), z_center > np.max(eq_slice.z))] = False
        x = None
        z = None
        try:
            if(not np.any(mask)):
                raise ValueError("No points inside flux Matrix!")
            if(TB_plot):
                plt.figure()
                plt.plot(R_center, z_center)
                plt.plot(Rz_data.T[2]*1.e-2, Rz_data.T[3]*1.e-2, "--")
                plt.plot(Rz_data.T[4]*1.e-2, Rz_data.T[5]*1.e-2, "--")
                x, z = plot1DECE(wgIn=wg, freq=ece_launch["f"][ich]/1.e9, dtoECE=dtoECESI*1.e3, project='poloidal', doPlot=False)
                plt.plot(R_center, z_center)
                plt.plot(x, z.T[0], ":")
                plt.plot(x, z.T[1], ":")
                plt.plot(x, z.T[2], "-.")
                plt.plot(x, z.T[3], ":")
                plt.plot(x, z.T[4], ":")
                v_min = min(np.min(z), np.min(Rz_data.T[1:][::2]*1.e-2))
                v_max = max(np.max(z), np.max(Rz_data.T[1:][::2]*1.e-2))
                plt.vlines([R_res[ich]], v_min, v_max, linestyles="--", colors="k")
                plt.gca().set_xlabel(r"$R$ [m]")
                plt.gca().set_ylabel(r"$z$ [m]")
                plt.gca().set_aspect("equal")
            i_min = np.argmin(np.abs((R_center[mask]-R_res[ich])**2 + (z_center[mask]-z_res[ich])**2))
            width = np.sqrt((Rz_data.T[2][i_min]*1.e-2 - R_center[i_min])**2 
                            + (Rz_data.T[3][i_min]*1.e-2 - z_center[i_min])**2)
            if(logfile is not None):
                logfile.write("TORBEAM width channel {0:d}: {1:1.3f} cm\n".format(ich+1, width*1.e2))
            else:
                print("TORBEAM width channel {0:d}: {1:1.3f} cm\n".format(ich+1, width*1.e2))
            if only_TB:
                return
        except ValueError:
            print("Failed to run TORBEAM. Using vacuum values!")
            TB_failed = True
        if(not only_TB or TB_failed):
            if(x is None or z is None):
                x, z = plot1DECE(wgIn=wg, freq=ece_launch["f"][ich]/1.e9, dtoECE=dtoECESI*1.e3, project='poloidal', doPlot=False)
            waist = np.zeros(len(x))
            waist = np.sqrt( ((z[:,2]-z[:,0])**2)+((z[:,2]-z[:, 1])**2) ) 
            waist += np.sqrt( ((z[:,2]-z[:,3])**2)+((z[:,2]-z[:, 4])**2) )
            waist /= 2
            R_center = x
            mask = np.logical_and(R_center > np.min(eq_slice.R), R_center < np.max(eq_slice.R))
            z_center = z.T[2]
            mask[np.logical_or(z_center < np.min(eq_slice.z), z_center > np.max(eq_slice.z))] = False
            if(not np.any(mask)):
                raise ValueError("No resonance found!")
            i_min = np.argmin(np.abs((R_center-R_res[ich])**2 + (z_center-z_res[ich])**2))
            if(logfile is not None):
                logfile.write("Vacuum width channel {0:d}: {1:1.3f} cm\n".format(ich + 1, waist[i_min] * 100.0))
            else:
                print("Vacuum width channel {0:d}: {1:1.3f} cm\n".format(ich + 1, waist[i_min]  * 100.0))
Пример #8
0
        ax = fig.add_subplot(111)
    ax.contourf(dist_obj.uxx, dist_obj.ull, ECCD_weight, \
                 levels = np.linspace(-1,1,30), cmap = plt.get_cmap("coolwarm"))
    ax.set_ylabel(r"$u_\parallel$")
    ax.set_xlabel(r"$u_\perp$")
    m = cm.ScalarMappable(cmap=plt.cm.get_cmap("coolwarm"))
    m.set_array(np.linspace(-1.0, 1.0, 30))
    cb_j = fig.colorbar(m, pad=0.15, ticks=[-1.0, 0.0, 1.0])
    cb_j.set_label(r"$(f - f_0) \beta_\parallel [\si{{a.u.}}]$")
    ax.set_aspect("equal")


#     plt.show()

if (__name__ == "__main__"):
    fig = plt.figure(figsize=(12.5, 8.5))
    ax = fig.add_subplot(111)
    current_weight(
        "/tokp/work/sdenk/DRELAX_35662_rdiff_prof/ECRad_35662_ECECTCCTA_run3204.mat",
        35662, 3.84, "AUGD", "IDE", 0, fig, ax)
    diag_weight_stand_alone(fig, ax, "/tokp/work/sdenk/DRELAX_35662_rdiff_prof/ECRad_35662_ECECTCCTA_run3204.mat", 3.84, 88, \
                            "/tokp/work/sdenk/DRELAX_35662_rdiff_prof/ECRad_35662_ECECTCCTA_run3204.mat")
    diag_weight_stand_alone(fig, ax, "/tokp/work/sdenk/DRELAX_35662_rdiff_prof/ECRad_35662_ECECTCCTA_run3204.mat", 3.84, 136, \
                            "/tokp/work/sdenk/DRELAX_35662_rdiff_prof/ECRad_35662_ECECTCCTA_run3204.mat")
    #
    #     plt.pause(-1)

    # #     plt.hold(True)
    #     current_weight("/tokp/work/sdenk/DRELAX_35662_rdiff_prof/ECRad_35662_ECECTCCTA_run3224.mat", 35662, 3.84, "AUGD", "IDE", 0, fig, ax)
    #     ECRH_weight(fig, "/tokp/work/sdenk/DRELAX_35662_rdiff_prof/ECRad_35662_ECECTCCTA_run3224.mat", 3.84, 0, \
    # #                 "/tokp/work/sdenk/DRELAX_35662_rdiff_prof/ECRad_35662_ECECTCCTA_run3224.mat", beam_freq=105.e9, ax=ax)