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']}")
def compare_f_dia(shot, time, EQ_exp, EQ_diag, EQ_ed):
    from Plotting_Configuration import plt
    EQObj = EQData(shot, EQ_exp=EQ_exp, EQ_diag=EQ_diag, EQ_ed=EQ_ed)
    EQ_t = EQObj.GetSlice(time)
    rho = np.linspace(0.0, 1.0, 100)
    ffp = EQObj.getQuantity(rho, "FFP", time)
    ffp_spl = InterpolatedUnivariateSpline(rho, ffp)
    f_sq_spl = ffp_spl.antiderivative(1)
    magn_field_axis = EQObj.MBI_shot.getSignal("BTFABB", \
                                              tBegin=time - 5.e-5, tEnd=time + 5.e-5)
    f_spl = InterpolatedUnivariateSpline(rho, np.sign(magn_field_axis) * \
                                                               (np.sqrt(2.0 * f_sq_spl(rho) + \
                                                                        (EQ_t.R_ax * magn_field_axis)**2)))
    psi_prof = EQObj.rhop_to_Psi(time, rho)
    plt.plot(psi_prof, f_spl(rho))
    gpol = EQObj.getQuantity(rho, "Jpol", time) * cnst.mu_0 / 2.0 / np.pi
    plt.plot(psi_prof, gpol, "--")
    plt.show()
Beispiel #3
0
def put_TRANSP_U_profiles_in_Scenario(Scenario, filename, time, scenario_name):
    from ufilelib import UFILELIB
    from Plotting_Configuration import plt
    u_file = UFILELIB()
    u_file.readfile(filename)
    it = np.argmin(np.abs(Scenario.plasma_dict["time"] - time))
    eq_slice = Scenario.plasma_dict["eq_data"][it]
    Scenario.plasma_dict["time"] = np.array([time])
    Scenario.plasma_dict["eq_data"] = [eq_slice]
    it_u_file = np.argmin(np.abs(u_file.ufdict["TE"]["Time"]))
    Scenario.plasma_dict["Te"] = [u_file.ufdict["TE"]["data"][it_u_file]]
    plt.plot(u_file.ufdict["TE"]["rho_tor"],
             u_file.ufdict["TE"]["data"][it_u_file] / 1.e3)
    it_u_file = np.argmin(np.abs(u_file.ufdict["NE"]["Time"]))
    Scenario.plasma_dict["ne"] = [
        u_file.ufdict["NE"]["data"][it_u_file] * 1.e6
    ]
    Scenario.plasma_dict["prof_reference"] = "rhot_prof"
    Scenario.plasma_dict["rhot_prof"] = u_file.ufdict["NE"]["rho_tor"]
    Scenario.to_mat_file(filename=scenario_name)
    plt.plot(u_file.ufdict["NE"]["rho_tor"],
             u_file.ufdict["NE"]["data"][it_u_file] / 1.e13)
    plt.show()
            self.ECRad_results.ray[field + mode][it][ich][iray] = values

    def save(self, new_filename, comment=""):
        if (new_filename == self.org_results_file):
            print("This routine does not allow overwriting of the old file!")
            return
        self.ECRad_results.to_mat_file(new_filename, comment)


if (__name__ == "__main__"):
    from Plotting_Configuration import plt
    ECRad_manip = ECRadRayManipulator(
        "/mnt/c/Users/Severin/ECRad/Yu/ECRad_179328_EXT_ed10.mat")
    R, z = ECRad_manip.get_Rz_single_ray(0, 0)
    Te_spl = RectBivariateSpline(ECRad_manip.ECRad_results.Scenario.plasma_dict["eq_data"][0].R, \
                                 ECRad_manip.ECRad_results.Scenario.plasma_dict["eq_data"][0].z, \
                                 ECRad_manip.ECRad_results.Scenario.plasma_dict["Te"][0])
    rhop = ECRad_manip.get_field_single_ray("rhop", 0, 0)
    plt.plot(rhop[rhop >=0], \
             ECRad_manip.get_field_single_ray("Te", 0, 0)[rhop >= 0], "+",  label="before")
    ECRad_manip.set_field_single_ray("Te",
                                     Te_spl(R, z, grid=False) * 1.5, 0, 0)
    ECRad_manip.save("/mnt/c/Users/Severin/ECRad/Yu/ECRad_179328_EXT_ed10_1.5Te.mat", \
                     "increased Te by a factpr pf1.5")
    ECRad_manip = ECRadRayManipulator(
        "/mnt/c/Users/Severin/ECRad/Yu/ECRad_179328_EXT_ed10_1.5Te.mat")
    plt.plot(rhop[rhop >=0], \
             ECRad_manip.get_field_single_ray("Te", 0, 0)[rhop >= 0], "^", label="after")
    plt.legend()
    plt.show()
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))
        return Result
        

if(__name__ == "__main__"):
    from Plotting_Configuration import plt
    ECRad_folder = "/mnt/c/Users/Severin/ECRad/"
    os.chdir(globalsettings.ECRadLibDir)
    print(os.getcwd())
    ECRad_file = os.path.join(ECRad_folder, "ECRad_35662_EXT_ed1.mat")
#     ECRad_file = "/gss_efgw_work/work/g2sdenk/ECRad_runs/ECRad_20180823016002_EXT_ed20.mat"
    Scenario = ECRadScenario(True)
    Config = ECRadConfig(True)
    Config.from_mat(path_in=ECRad_file)
    Scenario.from_mat(path_in=ECRad_file)
    Config.working_dir = ECRad_folder
    Config.scratch_dir = Config.working_dir
    Config.extra_output =False
    Config.batch = False
    ecrad_f2py_interface = ECRadF2PYInterface(Config, Scenario)
    ecrad_f2py_interface.set_config_and_diag(Config, Scenario, 0)
    rhop_out = ecrad_f2py_interface.set_equilibrium(Scenario, 0 )
    rhop = Scenario.plasma_dict["rhop_prof"][0]
    ne = Scenario.plasma_dict["ne"][0]
    Te = Scenario.plasma_dict["Te"][0]
    rhop_out = ecrad_f2py_interface.make_rays(Scenario, 0)
    fm_flag = np.zeros(ecrad_f2py_interface.N_ch, dtype=np.bool)
    fm_flag[:] = True
    ecrad_f2py_interface.set_fm_flag(fm_flag)
    Trad, tau = ecrad_f2py_interface.eval_Trad(Scenario, Config, 0)
    plt.plot(rhop_out, Trad / 1.e3, "+")
    plt.show()
Beispiel #7
0
    tau = 4.0 * np.pi * cnst.epsilon_0**2 * cnst.m_e**2 * cnst.c**3 / (
        ne * cnst.e**4 * lambda_C)
    tau_r = 6.0 * np.pi * cnst.epsilon_0 * (cnst.m_e *
                                            cnst.c)**3 / (cnst.e**4 * B**2)
    alpha = 2.0 * tau / (3.0 * tau_r * epsilon)
    print(alpha)
    g0 = g0_approx(alpha, u)
    g2 = g2_approx(alpha, u)
    if (np.isscalar(g2) and not np.isscalar(zeta)):
        f = np.zeros(zeta.shape)
    elif (not np.isscalar(g2) and np.isscalar(zeta)):
        f = np.zeros(g2.shape)
    else:
        print(
            "Matrox evaluation not yet supported - supply either scalar u or scalar zeta"
        )
    f += g2
    f *= 3.0 * (zeta**2 - 1.0) / 2.0
    f += g0
    return g0, g2, f


if (__name__ == "__main__"):
    from Plotting_Configuration import plt
    u_par = np.linspace(0, 0.5, 200)
    u_perp = 0.0
    Te = 6.e3
    plt.plot(u_par,
             Juettner2D(u_par, u_perp, Te) / Maxwell2D(u_par, u_perp, Te), "-")
    plt.show()