Exemplo n.º 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()
class ECRadRayManipulator(object):
    '''
    classdocs
    '''
    def __init__(self, ECRad_result_file):
        '''
        Constructor
        '''
        self.org_results_file = ECRad_result_file
        self.ECRad_results = ECRadResults()
        self.ECRad_results.from_mat_file(ECRad_result_file)
        self.N_ch = self.ECRad_results.Scenario.ray_launch[0]["f"]
        self.N_ray = self.ECRad_results.Config["Physics"]["N_ray"]
        if (self.ECRad_results.Config["Physics"]["considered_modes"] == 1):
            self.modes = ["X"]
        elif (self.ECRad_results.Config["Physics"]["considered_modes"] == 2):
            self.modes = ["O"]
        elif (self.ECRad_results.Config["Physics"]["considered_modes"] == 3):
            self.modes = ["X", "O"]
        else:
            raise ValueError("Invalid value in considered modes")

    def get_Rz_single_ray(self, it, ich, mode="X", iray=0):
        if (self.N_ray == 1):
            R = np.sqrt(self.ECRad_results.ray["x"+mode][it][ich]**2 + \
                        self.ECRad_results.ray["y"+mode][it][ich]**2)
            return R, self.ECRad_results.ray["z" + mode][it][ich]
        else:
            R = np.sqrt(self.ECRad_results.ray["x"+mode][it][ich][iray]**2 + \
                        self.ECRad_results.ray["y"+mode][it][ich][iray]**2)
            return R, self.ECRad_results.ray["z" + mode][it][ich][iray]

    def get_field_single_ray(self, field, it, ich, mode="X", iray=0):
        if (self.N_ray == 1):
            return self.ECRad_results.ray[field + mode][it][ich]
        else:
            return self.ECRad_results.ray[field + mode][it][ich][iray]

    def set_field_single_ray(self, field, values, it, ich, mode="X", iray=0):
        if (self.N_ray == 1):
            if (self.ECRad_results.ray[field + mode][it][ich].shape !=
                    values.shape):
                raise ValueError(
                    "The new values must have the same shape as the original values"
                )
            self.ECRad_results.ray[field + mode][it][ich] = values
        else:
            if (self.ECRad_results.ray[field + mode][it][ich][iray].shape !=
                    values.shape):
                raise ValueError(
                    "The new values must have the same shape as the original values"
                )
            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)
Exemplo n.º 3
0
def CECE_workflow(working_dir, Results_filename, time):
    Results = ECRadResults()
    Results.load(Results_filename)
    logfile = open(os.path.join(working_dir, f"CECE_params_{Results.Scenario['shot']}"), "w")
    run_ECE_TORBEAM_ECRad_Scenario(working_dir, Results, time, logfile=logfile)
    get_BPD_width(Results, 0, logfile=logfile)
    logfile.close()
    plt.show()
Exemplo n.º 4
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()
Exemplo n.º 5
0
def diag_weight_stand_alone(fig,
                            ax,
                            Result_file,
                            time_point,
                            ch,
                            DistWaveFile=None):
    Results = ECRadResults()
    Results.from_mat_file(Result_file)
    fig = diag_weight(fig,
                      Results,
                      time_point,
                      ch,
                      DistWaveFile=DistWaveFile,
                      ax=ax)
 def get_other_results(self, args):
     paths = args[0]
     new_results = {}
     for path in paths:
         result = ECRadResults()
         try:
             result.load(path)
             new_results[str(result.Scenario["shot"]) + "_" +
                         str(result.edition)] = result
         except:
             print("Failed to load result at: " + path)
     evt_out = GenerticEvt(Unbound_EVT_OTHER_RESULTS_LOADED, self.GetId())
     evt_out.insertData(new_results)
     wx.PostEvent(self, evt_out)
def repair_ECRad_results(folder_in, folder_out=None):
    # Allows to make bulk modification of result files using glob
    # If folder_out is True it overwrites!
    filelist = glob.glob(os.path.join(folder_in, "*.mat"))
#     filelist = ['/tokp/work/sdenk/DRELAX_Results/ECRad_35662_ECECTACTC_run0208.mat']
    cur_result = ECRadResults()
    for filename in filelist:
        cur_result.reset()
        cur_result.from_mat_file(filename)
        # Enter bulk modifcations here
        cur_result.Scenario.used_diags_dict["CTC"].diag = "CTC"
        if(folder_out is None):
            cur_result.to_mat_file(filename)
        else:
            cur_result.to_mat_file(os.path.join(folder_out, os.path.basename(filename)))    
 def FinishUpECRad(self):
     if(self.Results.Scenario["dimensions"]["N_time"] == 0):
         # Unsuccessful termination
         print("None of the ECRad runs were completed succesfully - sorry")
         self.Results = ECRadResults()
         # We have deleted all entries from the Scenario we need to rebuilt this
         self.Results.Scenario.plasma_set = False
         self.Progress_label.SetLabel("No ECRad run in progress")
         self.ProgressBar.SetRange(1)
         self.ProgressBar.SetValue(1)
         evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
         evt.SetStatus('ECRad failed - sorry!')
         self.GetEventHandler().ProcessEvent(evt)
         self.stop_current_evaluation = True
         self.StartECRadButton.Enable()
         return
     if(not self.Results.Config["Execution"]["batch"]):
         # Remove time points in case of early termination
         for i in range(self.index, self.Results.Scenario["dimensions"]["N_time"]):
             self.Results.Scenario.drop_time_point(i)
         self.Results.tidy_up(False)
     self.TimeBox.Clear()
     for t in self.Results.Scenario["time"]:
         self.TimeBox.Append("{0:1.4f}".format(t))
     self.KillECRadButton.Disable()
     self.stop_current_evaluation = False
     self.ExportButton.Enable()
     self.NameButton.Enable()
     self.Progress_label.SetLabel("No ECRad run in progress")
     self.ProgressBar.SetRange(self.index)
     self.ProgressBar.SetValue(self.index)
     evt = wx.PyCommandEvent()
     evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
     evt.SetStatus('ECRad has Finished!')
     wx.PostEvent(self, evt)
     if(not self.Results.Config["Execution"]["batch"]):
         print("Now saving results")
         print("This takes a moment please wait")
         WorkerThread(self.SavingThread, [])
     evt_2 = UpdateDataEvt(Unbound_EVT_UPDATE_DATA, self.GetId())
     evt_2.SetResults(self.Results)
     if(globalsettings.AUG):
         wx.PostEvent(self.calib_panel, evt)
         self.calib_panel.GetEventHandler().ProcessEvent(evt_2)
     wx.PostEvent(self.scenario_select_panel, evt_2)
     wx.PostEvent(self.plot_panel, evt_2)
     self.StartECRadButton.Enable()
 def __init__(self, ECRad_result_file):
     '''
     Constructor
     '''
     self.org_results_file = ECRad_result_file
     self.ECRad_results = ECRadResults()
     self.ECRad_results.from_mat_file(ECRad_result_file)
     self.N_ch = self.ECRad_results.Scenario.ray_launch[0]["f"]
     self.N_ray = self.ECRad_results.Config["Physics"]["N_ray"]
     if (self.ECRad_results.Config["Physics"]["considered_modes"] == 1):
         self.modes = ["X"]
     elif (self.ECRad_results.Config["Physics"]["considered_modes"] == 2):
         self.modes = ["O"]
     elif (self.ECRad_results.Config["Physics"]["considered_modes"] == 3):
         self.modes = ["X", "O"]
     else:
         raise ValueError("Invalid value in considered modes")
Exemplo n.º 10
0
 def __init__(self, Result=None, Scenario_file=None, Config_file=None):
     '''
     Constructor
     '''
     if (Result is None):
         if (Scenario_file is None or Config_file is None):
             raise ValueError(
                 "Either result or a Scenario and Config file must be present"
             )
         else:
             self.Result = ECRadResults()
             self.Result.Scenario = ECRadScenario(noLoad=True)
             self.Result.Scenario.load(Scenario_file)
             self.Result.Config = ECRadConfig(noLoad=True)
             self.Result.Config.load(Config_file)
     else:
         self.Result = Result
     self.ECRad_F2PY_interface = ECRadF2PYInterface()
 def ECRadRunner(cls, input_queue, output_queue):
     ECRad_inferface = ECRadF2PYInterface()
     while True:
         args = input_queue.get()
         try:
             command = args[0]
             if(command == "close"):
                 break
             Results = args[1]
             if(Results.Config["Execution"]["batch"]):
                 scratch_dir = Results.Config["Execution"]["scratch_dir"]
                 Results.Scenario.to_netcdf(filename=os.path.join(scratch_dir, "Scenario.nc"))
                 Results.Config.to_netcdf(filename=os.path.join(scratch_dir, "Config.nc"))
                 run_ECRad = SetupECRadBatch(Results.Config, Results.Scenario, Results.Scenario["time"][args[2]])
                 ECRad_batch = Popen(run_ECRad)
                 ECRad_batch.wait()
                 try:
                     filename, ed = Results.get_default_filename_and_edition(True)
                     NewResults = ECRadResults(False)
                     NewResults.from_netcdf(filename)
                     NewResults.to_netcdf()
                     output_queue.put([True, NewResults])
                 except:
                     print("Failed to run remotely. Please check .o and .e files at")
                     print(scratch_dir)
                     output_queue.put([False, Results])
             else:
                 Results = ECRad_inferface.process_single_timepoint(Results, args[2])
                 output_queue.put([True, Results])
         except Exception as e:
             print(e)
             output_queue.put([False, Results])
Exemplo n.º 12
0
def run_ECRad_from_script(working_dir, shot, Config, InvokeECRad, args):
    Results = ECRadResults()
    Results.parse_config(Config, Config.time)
    next_time_index_to_analyze = 0
    print("Analyzing {0:d} time points".format(len(Config.time)))
    while True:
        if(next_time_index_to_analyze >= len(Config.time)):
            break
        print("Working on t = {0:1.4f}".format(Config.time[next_time_index_to_analyze]))
        if(os.path.isdir(os.path.join(Config.working_dir, "ECRad_data"))):
            shutil.rmtree(os.path.join(Config.working_dir, "ECRad_data"))
        for diag_key in Config.used_diags_dict:
            if("CT" in diag_key or "IEC" == diag_key):
                if(str(Config.used_diags_dict[diag_key].beamline) not in Config.gy_dict):
                    new_gy = get_ECRH_viewing_angles(Config.shot, \
                                                     Config.used_diags_dict[diag_key].beamline)
                    if(new_gy.error == 0):
                        Config.gy_dict[str(Config.used_diags_dict[diag_key].beamline)] = new_gy
                    else:
                        print("Error when reading viewing angles")
                        print("Launch aborted")
                        return
        if(not prepare_input_files(Config.time, next_time_index_to_analyze, Config)):
            print("Error!! Launch aborted")
            return None
        print("-------- Launching ECRad -----------\n")
        print("-------- INVOKE COMMAND------------\n")
        print(InvokeECRad + " " + Config.working_dir)
        ECRad_process = subprocess.Popen([InvokeECRad, args])
        print("-----------------------------------\n")
        ECRad_process = subprocess.Popen([InvokeECRad, Config.working_dir])
        ECRad_process.wait()
        next_time_index_to_analyze += 1
        try:
            Results.append_new_results()
        except (IOError, IndexError) as e:
            print("Error: Results of ECRad cannot be found")
            print("Most likely cause is an error that occurred within the ECRad")
            print("Please run the ECRad with current input parameters in a separate shell.")
            print("The command to launch the ECRad can be found above.")
            print("Afterwards please send any error messages that appear at sdenk|at|ipp.mpg.de")
            print("If no errors occur make sure that you don't have another instance of ECRad GUI working in the same working directory")
            print(e)
            return None

    Results.tidy_up()
    print("Finished!")
    return Results
Exemplo n.º 13
0
def manipiulate_rays(result_file_in, result_file_out):
    res = ECRadResults()
    res.from_mat_file(result_file_in)
    for index in range(len(res.time)):
        for ich in range(len(res.Scenario.ray_launch[index]["f"])):
            for mode in res.modes:
                if (res.Config["Physics"]["N_ray"] > 1):
                    for iray in range(len(res.ray["s" + mode][index][ich])):
                        res.ray["Te" + mode][index][ich][iray][:] /= 2.0
                else:
                    res.ray["Te" + mode][index][ich][:] /= 2.0
    res.to_mat_file(result_file_out)
Exemplo n.º 14
0
class ECRadDriver():
    '''
    Driver for ECRad. Passes information to ECRad, runs ECRad and extracts results
    '''
    def __init__(self, Result=None, Scenario_file=None, Config_file=None):
        '''
        Constructor
        '''
        if (Result is None):
            if (Scenario_file is None or Config_file is None):
                raise ValueError(
                    "Either result or a Scenario and Config file must be present"
                )
            else:
                self.Result = ECRadResults()
                self.Result.Scenario = ECRadScenario(noLoad=True)
                self.Result.Scenario.load(Scenario_file)
                self.Result.Config = ECRadConfig(noLoad=True)
                self.Result.Config.load(Config_file)
        else:
            self.Result = Result
        self.ECRad_F2PY_interface = ECRadF2PYInterface()

    def run(self, id=None):
        itime = 0
        self.Result.set_dimensions()
        while itime < self.Result.Scenario["dimensions"]["N_time"]:
            try:
                self.process_time_point(itime)
                itime += 1
            except Exception as e:
                print("Error when processing t = {0:1.4f}".format(
                    self.Result.Scenario["time"][itime]))
                print("Removing this time point and continuing")
                raise (e)
                self.Result.Scenario.drop_time_point(itime)
                self.Result.set_dimensions()
        self.Result.tidy_up(autosave=False)
        self.Result.to_netcdf(scratch=True, ed=id)

    def process_time_point(self, itime):
        self.Result = self.ECRad_F2PY_interface.process_single_timepoint(
            self.Result, itime)
 def __init__(self, parent, ECRad_runner_process, ECRad_input_queue, ECRad_output_queue):
     scrolled.ScrolledPanel.__init__(self, parent, wx.ID_ANY)
     self.parent = parent
     self.ECRad_running = False
     self.ECRad_runner_process = ECRad_runner_process
     self.ECRad_input_queue = ECRad_input_queue
     self.ECRad_output_queue = ECRad_output_queue
     self.sizer = wx.BoxSizer(wx.VERTICAL)
     self.Results = ECRadResults(lastused=True)
     self.Bind(EVT_MAKE_ECRAD, self.OnProcessTimeStep)
     self.Bind(EVT_ECRAD_FINISHED, self.OnProcessEnded)
     self.Bind(EVT_NEXT_TIME_STEP, self.OnNextTimeStep)
     self.Bind(EVT_UPDATE_DATA, self.OnUpdate)
     self.Bind(EVT_LOCK_EXPORT, self.OnLockExport)
     self.Bind(wx.EVT_IDLE, self.OnIdle)
     self.Bind(EVT_GENE_DATA_LOADED, self.OnGeneLoaded)
     self.Bind(EVT_ECRAD_RESULT_LOADED, self.OnResultsImported)
     self.Bind(EVT_LOAD_OLD_RESULT, self.OnImport)
     self.SetSizer(self.sizer)
     self.SetSize((400, 400))
     self.SetMinSize((400, 400))
     self.data = None
     self.ControlSizer = wx.BoxSizer(wx.HORIZONTAL)
     self.ButtonSizer = wx.BoxSizer(wx.VERTICAL)
     self.sizer.Add(self.ControlSizer, 0, wx.EXPAND | wx.ALL , 5)
     self.StartECRadButton = wx.Button(self, wx.ID_ANY, \
                                       'Start ECRad')
     self.KillECRadButton = wx.Button(self, wx.ID_ANY, 'Terminate ECRad')
     self.StartECRadButton.Bind(wx.EVT_BUTTON, self.OnStartECRad)
     self.KillECRadButton.Bind(wx.EVT_BUTTON, self.OnKillECRad)
     self.KillECRadButton.Disable()
     self.ExportButton = wx.Button(self, wx.ID_ANY, 'Save results')
     self.ExportButton.SetToolTip("If this is grayed out there is no (new) data to save!")
     self.ExportButton.Bind(wx.EVT_BUTTON, self.OnExport)
     self.ExportButton.Disable()
     self.NameButton = wx.Button(self, wx.ID_ANY, 'Comment Results')
     self.NameButton.Bind(wx.EVT_BUTTON, self.OnName)
     username = "******"
     if(getpass.getuser() in ["sdenk", "g2sdenk", "denk"]):
         username = "******"
     elif(getpass.getuser() == "bva"):
         username = "******"
     elif(getpass.getuser() == "mwillens"):
         username = "******"
     elif(getpass.getuser() == "sfreethy"):
         username = "******"
     self.ButtonSizer.Add(self.StartECRadButton, 0, wx.ALL | \
                     wx.LEFT, 5)
     self.ButtonSizer.Add(self.KillECRadButton, 0, wx.ALL | \
                     wx.LEFT, 5)
     self.ButtonSizer.Add(self.ExportButton, 0, wx.ALL | \
                     wx.LEFT, 5)
     self.ButtonSizer.Add(self.NameButton, 0, wx.ALL | \
                     wx.LEFT, 5)
     self.ControlSizer.Add(self.ButtonSizer, 0, wx.ALIGN_TOP)
     self.Log_Box = wx.TextCtrl(self, wx.ID_ANY, size=(200, 100), \
             style=wx.TE_MULTILINE | wx.TE_READONLY)
     self.Log_Box.AppendText('Welcome to the ECRad GUI' + username + os.linesep)
     self.diag_box_sizer = wx.BoxSizer(wx.VERTICAL)
     self.diag_box_label = wx.StaticText(self, wx.ID_ANY, "Diagnostics")
     self.DiagBox = wx.ListBox(self, wx.ID_ANY, size=(100, 100))
     for diag_key in list(self.Results.Scenario["used_diags_dict"]):
         self.DiagBox.Append(diag_key)
     self.diag_box_sizer.Add(self.diag_box_label, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL , 5)
     self.diag_box_sizer.Add(self.DiagBox, 1, wx.ALL | wx.EXPAND , 5)
     self.time_box_sizer = wx.BoxSizer(wx.VERTICAL)
     self.time_box_label = wx.StaticText(self, wx.ID_ANY, "Time points")
     self.TimeBox = wx.ListBox(self, wx.ID_ANY, size=(100, 100))
     for time in self.Results.Scenario["time"]:
         self.TimeBox.Append("{0:1.5f}".format(time))
     self.time_box_sizer.Add(self.time_box_label, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL , 5)
     self.time_box_sizer.Add(self.TimeBox, 1, wx.ALL | wx.EXPAND , 5)
     self.ControlSizer.Add(self.Log_Box, 1, wx.ALL | wx.EXPAND , 5)
     self.ControlSizer.Add(self.diag_box_sizer, 0, wx.ALL | wx.EXPAND, 5)
     self.ControlSizer.Add(self.time_box_sizer, 0, wx.ALL | wx.EXPAND, 5)
     self.ProgressBar = wx.Gauge(self, wx.ID_ANY, style=wx.GA_HORIZONTAL)
     self.Progress_label = wx.StaticText(self, wx.ID_ANY, "No ECRad run in progress")
     self.Progress_sizer = wx.BoxSizer(wx.HORIZONTAL)
     self.Progress_sizer.Add(self.ProgressBar, 1, wx.ALL | wx.EXPAND, 5)
     self.Progress_sizer.Add(self.Progress_label, 0, wx.ALL, 5)
     self.Redirector = Redirect_Text(self.Log_Box)
     sys.stdout = self.Redirector
     self.index = 0  # Index for the iteration over timepoints
     self.UpperBook = wx.Notebook(self)
     self.scenario_select_panel = ScenarioSelectPanel(self.UpperBook, self.Results.Scenario, self.Results.Config)
     self.UpperBook.AddPage(self.scenario_select_panel, "Select scenario time points")
     self.launch_panel = LaunchPanel(self.UpperBook, self.Results.Scenario, self.Results.Config["Execution"]["working_dir"])
     self.UpperBook.AddPage(self.launch_panel, "Diagnostic configuration")
     self.config_panel = ConfigPanel(self.UpperBook, self.Results.Config)
     self.UpperBook.AddPage(self.config_panel, "ECRad configuration")
     self.plot_panel = PlotPanel(self.UpperBook)
     self.UpperBook.AddPage(self.plot_panel, "Misc. Plots")
     self.sizer.Add(self.Progress_sizer, 0, wx.ALL | wx.EXPAND, 5)
     self.SetScrollRate(20, 20)
     if(globalsettings.AUG):
         self.calib_panel = CalibPanel(self.UpperBook, self.Results.Scenario)
         self.UpperBook.AddPage(self.calib_panel, "ECRad Calibration")
         self.calib_evolution_Panel = CalibEvolutionPanel(self.UpperBook, self.Results.Config["Execution"]["working_dir"])
         self.UpperBook.AddPage(self.calib_evolution_Panel, "Plotting for calibration")
     self.sizer.Add(self.UpperBook, 1, wx.ALL | \
         wx.LEFT, 5)
Exemplo n.º 16
0
def ECRH_weight(fig,
                Result_file,
                time_point,
                ibeam,
                DistWaveFile,
                beam_freq=105.e9,
                ax=None):
    # Currently only RELAX/LUKE distributions supported
    # Extension for GENE trivial though
    if (ax is None):
        ax = fig.add_subplot(111)
    harmonic_n = 2
    Results = ECRadResults()
    Results.from_mat_file(Result_file)
    itime = np.argmin(np.abs(time_point -
                             Results.Scenario.plasma_dict["time"]))
    time_cor = Results.Scenario.plasma_dict["time"][itime]
    EQObj = EQDataExt(Results.Scenario.shot)
    EQObj.set_slices_from_ext(Results.Scenario.plasma_dict["time"],
                              Results.Scenario.plasma_dict["eq_data"])
    B_ax = EQObj.get_B_on_axis(time_cor)
    EqSlice = EQObj.GetSlice(time_point)
    dist_wave_mat = loadmat(DistWaveFile)
    dist_obj = load_f_from_mat(DistWaveFile, True)
    f_inter = make_f_inter(Results.Config["Physics"]["dstf"],
                           dist_obj=dist_obj,
                           EQObj=EQObj,
                           time=time_cor)[0]
    linear_beam = read_waves_mat_to_beam(dist_wave_mat,
                                         EqSlice,
                                         use_wave_prefix=None)
    itme = np.argmin(np.abs(Results.Scenario.plasma_dict["time"] - time_point))
    Te_spl = InterpolatedUnivariateSpline(Results.Scenario.plasma_dict[Results.Scenario.plasma_dict["prof_reference"]][itime], \
                                          np.log(Results.Scenario.plasma_dict["Te"][itme]))
    ne_spl = InterpolatedUnivariateSpline(Results.Scenario.plasma_dict[Results.Scenario.plasma_dict["prof_reference"]][itime], \
                                          np.log(Results.Scenario.plasma_dict["ne"][itme]))
    m = 40
    n = 80
    u_perp_grid = np.linspace(0.0, np.max(dist_obj.u), m)
    u_par_grid = np.linspace(-np.max(dist_obj.u), np.max(f_inter.x), n)
    diag_weight_f = np.zeros((m, n))
    for ray in linear_beam.rays[ibeam]:
        tot_pw_ray, cur_PDP = make_PowerDepo_3D_for_ray(ray, beam_freq, "Re", harmonic_n, \
                                                        B_ax, EqSlice, Te_spl, ne_spl, f_inter, \
                                                        N_pnts=100, fast= True)
        for irhop in range(len(cur_PDP.rho)):
            print(irhop + 1, " / ", len(cur_PDP.rho))
            intercep_points = find_cell_interceps(u_par_grid, u_perp_grid,
                                                  cur_PDP, irhop)
            for i_intercep, intercep_point in enumerate(intercep_points[:-1]):
                i = np.argmin(np.abs(intercep_point[0] - u_par_grid))
                j = np.argmin(np.abs(intercep_point[1] - u_perp_grid))
                if (u_par_grid[i] > intercep_point[0]):
                    i -= 1
                if (u_perp_grid[j] > intercep_point[1]):
                    j -= 1
                if (i < 0 or j < 0):
                    continue  # only happens at the lower bounds, where u_perp is very small and, therefore, also j is very small
                # Compute arclength
                t = np.zeros(cur_PDP.u_par[irhop].shape)
                for i_res_line in range(1, len(cur_PDP.u_par[irhop])):
                    t[i_res_line] = t[i_res_line - 1] + np.sqrt((cur_PDP.u_par[irhop][i_res_line] - cur_PDP.u_par[irhop][i_res_line - 1])**2 + \
                                                                (cur_PDP.u_perp[irhop][i_res_line] - cur_PDP.u_perp[irhop][i_res_line - 1])**2)
                t /= np.max(t)  # Normalize this
                # Sort
                t_spl = InterpolatedUnivariateSpline(cur_PDP.u_par[irhop], t)
                try:
                    PDP_val_spl = InterpolatedUnivariateSpline(
                        t, cur_PDP.val[irhop])
                except Exception as e:
                    print(e)
                t1 = t_spl(intercep_point[0])
                t2 = t_spl(intercep_points[i_intercep + 1][0])
                diag_weight_f[j,i] += tot_pw_ray * \
                                        PDP_val_spl.integral(t1, t2)
    ax.contourf(u_perp_grid, u_par_grid, diag_weight_f.T / np.max(diag_weight_f.flatten()), \
                 levels = np.linspace(0.01,1,10), cmap = plt.get_cmap("Greens"))
    m = cm.ScalarMappable(cmap=plt.cm.get_cmap("Greens"))
    m.set_array(np.linspace(0.01, 1.0, 10))
    cb_diag = fig.colorbar(m, pad=0.15, ticks=[0.0, 0.5, 1.0])
    cb_diag.set_label(r"$\mathrm{d}P/\mathrm{d}s [\si{{a.u.}}]$")
    ax.set_ylabel(r"$u_\parallel$")
    ax.set_xlabel(r"$u_\perp$")
    ax.set_aspect("equal")
    return fig
 def OnImport(self, evt):
     self.Results = ECRadResults()
     print("Now loarding: " + evt.filename)
     print("This takes a moment please wait")
     WorkerThread(self.ImportThread, [evt.filename])
class Main_Panel(scrolled.ScrolledPanel):
    def __init__(self, parent, ECRad_runner_process, ECRad_input_queue, ECRad_output_queue):
        scrolled.ScrolledPanel.__init__(self, parent, wx.ID_ANY)
        self.parent = parent
        self.ECRad_running = False
        self.ECRad_runner_process = ECRad_runner_process
        self.ECRad_input_queue = ECRad_input_queue
        self.ECRad_output_queue = ECRad_output_queue
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.Results = ECRadResults(lastused=True)
        self.Bind(EVT_MAKE_ECRAD, self.OnProcessTimeStep)
        self.Bind(EVT_ECRAD_FINISHED, self.OnProcessEnded)
        self.Bind(EVT_NEXT_TIME_STEP, self.OnNextTimeStep)
        self.Bind(EVT_UPDATE_DATA, self.OnUpdate)
        self.Bind(EVT_LOCK_EXPORT, self.OnLockExport)
        self.Bind(wx.EVT_IDLE, self.OnIdle)
        self.Bind(EVT_GENE_DATA_LOADED, self.OnGeneLoaded)
        self.Bind(EVT_ECRAD_RESULT_LOADED, self.OnResultsImported)
        self.Bind(EVT_LOAD_OLD_RESULT, self.OnImport)
        self.SetSizer(self.sizer)
        self.SetSize((400, 400))
        self.SetMinSize((400, 400))
        self.data = None
        self.ControlSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.ButtonSizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.ControlSizer, 0, wx.EXPAND | wx.ALL , 5)
        self.StartECRadButton = wx.Button(self, wx.ID_ANY, \
                                          'Start ECRad')
        self.KillECRadButton = wx.Button(self, wx.ID_ANY, 'Terminate ECRad')
        self.StartECRadButton.Bind(wx.EVT_BUTTON, self.OnStartECRad)
        self.KillECRadButton.Bind(wx.EVT_BUTTON, self.OnKillECRad)
        self.KillECRadButton.Disable()
        self.ExportButton = wx.Button(self, wx.ID_ANY, 'Save results')
        self.ExportButton.SetToolTip("If this is grayed out there is no (new) data to save!")
        self.ExportButton.Bind(wx.EVT_BUTTON, self.OnExport)
        self.ExportButton.Disable()
        self.NameButton = wx.Button(self, wx.ID_ANY, 'Comment Results')
        self.NameButton.Bind(wx.EVT_BUTTON, self.OnName)
        username = "******"
        if(getpass.getuser() in ["sdenk", "g2sdenk", "denk"]):
            username = "******"
        elif(getpass.getuser() == "bva"):
            username = "******"
        elif(getpass.getuser() == "mwillens"):
            username = "******"
        elif(getpass.getuser() == "sfreethy"):
            username = "******"
        self.ButtonSizer.Add(self.StartECRadButton, 0, wx.ALL | \
                        wx.LEFT, 5)
        self.ButtonSizer.Add(self.KillECRadButton, 0, wx.ALL | \
                        wx.LEFT, 5)
        self.ButtonSizer.Add(self.ExportButton, 0, wx.ALL | \
                        wx.LEFT, 5)
        self.ButtonSizer.Add(self.NameButton, 0, wx.ALL | \
                        wx.LEFT, 5)
        self.ControlSizer.Add(self.ButtonSizer, 0, wx.ALIGN_TOP)
        self.Log_Box = wx.TextCtrl(self, wx.ID_ANY, size=(200, 100), \
                style=wx.TE_MULTILINE | wx.TE_READONLY)
        self.Log_Box.AppendText('Welcome to the ECRad GUI' + username + os.linesep)
        self.diag_box_sizer = wx.BoxSizer(wx.VERTICAL)
        self.diag_box_label = wx.StaticText(self, wx.ID_ANY, "Diagnostics")
        self.DiagBox = wx.ListBox(self, wx.ID_ANY, size=(100, 100))
        for diag_key in list(self.Results.Scenario["used_diags_dict"]):
            self.DiagBox.Append(diag_key)
        self.diag_box_sizer.Add(self.diag_box_label, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL , 5)
        self.diag_box_sizer.Add(self.DiagBox, 1, wx.ALL | wx.EXPAND , 5)
        self.time_box_sizer = wx.BoxSizer(wx.VERTICAL)
        self.time_box_label = wx.StaticText(self, wx.ID_ANY, "Time points")
        self.TimeBox = wx.ListBox(self, wx.ID_ANY, size=(100, 100))
        for time in self.Results.Scenario["time"]:
            self.TimeBox.Append("{0:1.5f}".format(time))
        self.time_box_sizer.Add(self.time_box_label, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL , 5)
        self.time_box_sizer.Add(self.TimeBox, 1, wx.ALL | wx.EXPAND , 5)
        self.ControlSizer.Add(self.Log_Box, 1, wx.ALL | wx.EXPAND , 5)
        self.ControlSizer.Add(self.diag_box_sizer, 0, wx.ALL | wx.EXPAND, 5)
        self.ControlSizer.Add(self.time_box_sizer, 0, wx.ALL | wx.EXPAND, 5)
        self.ProgressBar = wx.Gauge(self, wx.ID_ANY, style=wx.GA_HORIZONTAL)
        self.Progress_label = wx.StaticText(self, wx.ID_ANY, "No ECRad run in progress")
        self.Progress_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.Progress_sizer.Add(self.ProgressBar, 1, wx.ALL | wx.EXPAND, 5)
        self.Progress_sizer.Add(self.Progress_label, 0, wx.ALL, 5)
        self.Redirector = Redirect_Text(self.Log_Box)
        sys.stdout = self.Redirector
        self.index = 0  # Index for the iteration over timepoints
        self.UpperBook = wx.Notebook(self)
        self.scenario_select_panel = ScenarioSelectPanel(self.UpperBook, self.Results.Scenario, self.Results.Config)
        self.UpperBook.AddPage(self.scenario_select_panel, "Select scenario time points")
        self.launch_panel = LaunchPanel(self.UpperBook, self.Results.Scenario, self.Results.Config["Execution"]["working_dir"])
        self.UpperBook.AddPage(self.launch_panel, "Diagnostic configuration")
        self.config_panel = ConfigPanel(self.UpperBook, self.Results.Config)
        self.UpperBook.AddPage(self.config_panel, "ECRad configuration")
        self.plot_panel = PlotPanel(self.UpperBook)
        self.UpperBook.AddPage(self.plot_panel, "Misc. Plots")
        self.sizer.Add(self.Progress_sizer, 0, wx.ALL | wx.EXPAND, 5)
        self.SetScrollRate(20, 20)
        if(globalsettings.AUG):
            self.calib_panel = CalibPanel(self.UpperBook, self.Results.Scenario)
            self.UpperBook.AddPage(self.calib_panel, "ECRad Calibration")
            self.calib_evolution_Panel = CalibEvolutionPanel(self.UpperBook, self.Results.Config["Execution"]["working_dir"])
            self.UpperBook.AddPage(self.calib_evolution_Panel, "Plotting for calibration")
        self.sizer.Add(self.UpperBook, 1, wx.ALL | \
            wx.LEFT, 5)

#     def __del__(self):
#         if self.ECRad_process is not None:
#             self.ECRad_process.Detach()
#             self.ECRad_process.CloseOutput()
#             self.ECRad_process = None

    # Overwrite this to stop the window from constantly jumping
    def OnChildFocus(self, evt):
        pass

    def OnStartECRad(self, evt):
        if(self.ECRad_running):
            print('ECRad is still running - please wait!')
            return
        evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
        evt.SetStatus('Preparing run - GUI might be unresponsive for minutes - please wait!')
        self.GetEventHandler().ProcessEvent(evt)
        try:
            self.Results.Config = self.config_panel.UpdateConfig(self.Results.Config)
        except ValueError as e:
            print("Failed to parse Configuration")
            print("Reason: ", e)
            evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
            evt.SetStatus('')
            self.GetEventHandler().ProcessEvent(evt)
            return
        if(self.Results.Config["Physics"]["dstf"] not in ["Th", "Re", "Lu", "Ge", "GB"]):
            print("Invalid choice of distribution")
            print("Possible options:")
            print("Th -> thermal plasma")
            print("Re -> distribution function computed by RELAX")
            print("Lu -> distribution function computed by LUKE (deprecated)")
            print("Ge, GB -> distribution function computed by GENE (deprecated)")
            print("Please select a valid distribution function identifier.")
            return
        scenario_updated = False
        # Reset only the result fields but leave Scenario and Config untouched
        self.Results.reset(light=True)
        # Sets time points and stores plasma data in Scenario
        if(self.scenario_select_panel.FullUpdateNeeded() or not self.Results.Scenario.plasma_set):
            try:
                self.Results.Scenario = self.scenario_select_panel.UpdateScenario(self.Results.Scenario, self.Results.Config, None)
                if(not self.Results.Scenario.plasma_set):
                    evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
                    evt.SetStatus('')
                    self.GetEventHandler().ProcessEvent(evt)
                    return
            except ValueError as e:
                print("Failed to load Scenario")
                print("Reason: ", e)
                evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
                evt.SetStatus('')
                self.GetEventHandler().ProcessEvent(evt)
                return
            self.TimeBox.Clear()
            for t in self.Results.Scenario["time"]:
                self.TimeBox.Append("{0:1.4f}".format(t))
            scenario_updated = True
        else:
            self.Results.Scenario = self.scenario_select_panel.SetScaling(self.Results.Scenario)
        if(self.launch_panel.UpdateNeeded() or not self.Results.Scenario.diags_set):
            try:
                self.Results.Scenario = self.launch_panel.UpdateScenario(self.Results.Scenario)
                if(not self.Results.Scenario.diags_set):
                    evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
                    evt.SetStatus('')
                    self.GetEventHandler().ProcessEvent(evt)
                    return
            except ValueError as e:
                print("Failed to parse diagnostic info")
                print("Reason: ", e)
                evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
                evt.SetStatus('')
                self.GetEventHandler().ProcessEvent(evt)
                return
            self.DiagBox.Clear()
            for diag in list(self.Results.Scenario["used_diags_dict"]):
                self.DiagBox.Append(diag)
            scenario_updated = True
        self.Results.Scenario.set_up_dimensions()
        # Stores launch data in Scenario
        self.stop_current_evaluation = False
        self.index = 0
        old_comment = self.Results.comment
        self.Results.comment = old_comment # Keep the comment
        if(len(list(self.Results.Scenario["used_diags_dict"].keys())) == 0):
            print("No diagnostics selected")
            print("Run aborted")
            evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
            evt.SetStatus('')
            self.GetEventHandler().ProcessEvent(evt)
            return
        if(len(self.Results.Scenario["time"]) == 0):
            print("No time points selected")
            print("Run aborted")
            evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
            evt.SetStatus('')
            self.GetEventHandler().ProcessEvent(evt)
            return
        if(self.Results.Config["Physics"]["dstf"] == "Re"):
            if(self.Results.Scenario["dist_obj"] is None):
                fileDialog=wx.FileDialog(self, "Selectr file with bounce averaged distribution data", \
                                                     defaultDir = self.Results.Config["Execution"]["working_dir"], \
                                                     wildcard="matlab files (*.mat)|*.mat",
                                                     style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
                if(fileDialog.ShowModal() == wx.ID_CANCEL):
                    print("Launch aborted")
                    return
                else:
                    pathname = fileDialog.GetPath()
                    self.Results.Scenario.load_dist_obj(pathname)
                    fileDialog.Destroy()
        self.Results.Config.autosave()
        if(self.Results.Config["Physics"]["dstf"] not in ["Ge", "GB"]):
            self.FinalECRadSetup(scenario_updated)
        else:
            if(len(self.Results.Scenario["time"]) != 1):
                print("For GENE distributions please select only one time point, i.e. the time point of the gene calcuation")
                evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
                evt.SetStatus('')
                self.GetEventHandler().ProcessEvent(evt)
                return
            fileDialog=wx.FileDialog(self, "Selectr file with GENE distribution data", \
                                                 defaultDir = self.Results.Config["Execution"]["working_dir"], \
                                                 wildcard="hdf5 files (*.h5)|*.h5",
                                                 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
            if(fileDialog.ShowModal() == wx.ID_CANCEL):
                print("Launch aborted")
                return
            else:
                pathname = fileDialog.GetPath()
                WorkerThread(self.LoadGeneData, [pathname])
                fileDialog.Destroy()
            
    def LoadGeneData(self, args):
        pathname = args[0]
        evt = GENEDataEvt(Unbound_EVT_GENE_DATA_LOADED, wx.ID_ANY)
        if(self.Results.Scenario.load_GENE_obj(pathname, self.Results.Config["Physics"]["dstf"])):
            evt.set_state(0)
        else:
            evt.set_state(-1)
        wx.PostEvent(self, evt)
     
     
    def OnGeneLoaded(self, evt):
        if(evt.state == 0):
            gene_dlg = Select_GENE_timepoints_dlg(self, self.Results.Scenario["GENE_obj"].time)
            if(gene_dlg.ShowModal() == wx.ID_OK):
                if(len(gene_dlg.used) == 0):
                    print("No time point selected")
                    evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
                    evt.SetStatus('')
                    wx.PostEvent(self, evt)
                    return
                if(not self.Results.Scenario.integrate_GeneData(np.asarray(gene_dlg.used, dtype=np.float) * 1.e-3)):
                    print("GENE object not properly initialized - this is most likely due to a bug in the GUI")
                    evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
                    evt.SetStatus('')
                    wx.PostEvent(self, evt)
                    return
                evt_out_2 = UpdateDataEvt(Unbound_EVT_UPDATE_DATA, self.GetId())
                evt_out_2.SetResults(self.Results)
                wx.PostEvent(self.scenario_select_panel, evt_out_2)
                gene_dlg.Destroy()
                self.TimeBox.Clear()
                for time in self.Results.Scenario["time"]:
                    self.TimeBox.Append("{0:1.5f}".format(time))
                self.FinalECRadSetup(True)
            else:
                print("Aborted")
                evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
                evt.SetStatus('')
                wx.PostEvent(self, evt)
                return
        else:
            print("Error when loading GENE data - see above")
            evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
            evt.SetStatus('')
            wx.PostEvent(self, evt)
            return         

    def FinalECRadSetup(self, scenario_updated):
        # Thinga we need to do just before we get going
        if(scenario_updated):
                self.Results.Scenario.autosave()
        self.Results.set_dimensions()
        self.ProgressBar.SetRange(self.Results.Scenario["dimensions"]["N_time"])
        evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
        evt.SetStatus('ECRad is running - please wait.')
        wx.PostEvent(self, evt)
        self.Progress_label.SetLabel("ECRad running - ({0:d}/{1:d})".format(self.index + 1,len(self.Results.Scenario["time"])))
        self.ProgressBar.SetValue(self.index)
        self.ExportButton.Disable()
        self.NameButton.Disable()
        self.StartECRadButton.Disable()
        evt = wx.PyCommandEvent(Unbound_EVT_MAKE_ECRAD, self.GetId())
        wx.PostEvent(self, evt)

    def OnProcessTimeStep(self, evt):
        self.ECRad_running = True
        self.ECRad_input_queue.put(["run ECRad", self.Results, self.index]) 
        
    def ECRadRunner(cls, input_queue, output_queue):
        ECRad_inferface = ECRadF2PYInterface()
        while True:
            args = input_queue.get()
            try:
                command = args[0]
                if(command == "close"):
                    break
                Results = args[1]
                if(Results.Config["Execution"]["batch"]):
                    scratch_dir = Results.Config["Execution"]["scratch_dir"]
                    Results.Scenario.to_netcdf(filename=os.path.join(scratch_dir, "Scenario.nc"))
                    Results.Config.to_netcdf(filename=os.path.join(scratch_dir, "Config.nc"))
                    run_ECRad = SetupECRadBatch(Results.Config, Results.Scenario, Results.Scenario["time"][args[2]])
                    ECRad_batch = Popen(run_ECRad)
                    ECRad_batch.wait()
                    try:
                        filename, ed = Results.get_default_filename_and_edition(True)
                        NewResults = ECRadResults(False)
                        NewResults.from_netcdf(filename)
                        NewResults.to_netcdf()
                        output_queue.put([True, NewResults])
                    except:
                        print("Failed to run remotely. Please check .o and .e files at")
                        print(scratch_dir)
                        output_queue.put([False, Results])
                else:
                    Results = ECRad_inferface.process_single_timepoint(Results, args[2])
                    output_queue.put([True, Results])
            except Exception as e:
                print(e)
                output_queue.put([False, Results])
    
    ECRadRunner = classmethod(ECRadRunner)
    
            
    def OnProcessEnded(self, evt):
        self.ECRad_running = False
        if(evt.success):
            if(self.Results.Config["Execution"]["batch"]):
                self.index = self.Results.Scenario["dimensions"]["N_time"]
            # Append times twice to track which time points really do have results in case of crashes
            self.index += 1
        else:
            if(self.Results.Config["Execution"]["batch"]):
                # If batch crashes we have to dump everything
                self.index = 0
                while self.index < self.Results.Scenario["dimensions"]["N_time"]:
                    self.Results.Scenario.drop_time_point(self.index)
            else:
                print("Sorry, ECRad crashed. Please send the log console output to Severin Denk")
                print("Skipping current time point {0:1.4f} and continuing".format(self.Results.Scenario["time"][self.index]))
                self.Results.Scenario.drop_time_point(self.index)
                self.ProgressBar.SetRange(self.Results.Scenario["dimensions"]["N_time"])
        if(self.index < len(self.Results.Scenario["time"]) and not self.stop_current_evaluation):
            evt = NewStatusEvt(Unbound_EVT_NEXT_TIME_STEP, self.GetId())
            wx.PostEvent(self, evt)
        else:
            self.FinishUpECRad()
                        
    def OnNextTimeStep(self, evt):
        if(not self.stop_current_evaluation):
            evt = wx.PyCommandEvent(Unbound_EVT_MAKE_ECRAD, self.GetId())
            wx.PostEvent(self, evt)
        else:
            self.FinishUpECRad()
            
    def FinishUpECRad(self):
        if(self.Results.Scenario["dimensions"]["N_time"] == 0):
            # Unsuccessful termination
            print("None of the ECRad runs were completed succesfully - sorry")
            self.Results = ECRadResults()
            # We have deleted all entries from the Scenario we need to rebuilt this
            self.Results.Scenario.plasma_set = False
            self.Progress_label.SetLabel("No ECRad run in progress")
            self.ProgressBar.SetRange(1)
            self.ProgressBar.SetValue(1)
            evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
            evt.SetStatus('ECRad failed - sorry!')
            self.GetEventHandler().ProcessEvent(evt)
            self.stop_current_evaluation = True
            self.StartECRadButton.Enable()
            return
        if(not self.Results.Config["Execution"]["batch"]):
            # Remove time points in case of early termination
            for i in range(self.index, self.Results.Scenario["dimensions"]["N_time"]):
                self.Results.Scenario.drop_time_point(i)
            self.Results.tidy_up(False)
        self.TimeBox.Clear()
        for t in self.Results.Scenario["time"]:
            self.TimeBox.Append("{0:1.4f}".format(t))
        self.KillECRadButton.Disable()
        self.stop_current_evaluation = False
        self.ExportButton.Enable()
        self.NameButton.Enable()
        self.Progress_label.SetLabel("No ECRad run in progress")
        self.ProgressBar.SetRange(self.index)
        self.ProgressBar.SetValue(self.index)
        evt = wx.PyCommandEvent()
        evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
        evt.SetStatus('ECRad has Finished!')
        wx.PostEvent(self, evt)
        if(not self.Results.Config["Execution"]["batch"]):
            print("Now saving results")
            print("This takes a moment please wait")
            WorkerThread(self.SavingThread, [])
        evt_2 = UpdateDataEvt(Unbound_EVT_UPDATE_DATA, self.GetId())
        evt_2.SetResults(self.Results)
        if(globalsettings.AUG):
            wx.PostEvent(self.calib_panel, evt)
            self.calib_panel.GetEventHandler().ProcessEvent(evt_2)
        wx.PostEvent(self.scenario_select_panel, evt_2)
        wx.PostEvent(self.plot_panel, evt_2)
        self.StartECRadButton.Enable()
        
    def SavingThread(self, args):
        try:
            self.Results.autosave()
        except Exception as e:
            print("ERROR: Failed to save results")
            print(e)

    def OnKillECRad(self, evt):
        self.stop_current_evaluation = True
        print("Waiting for current calculation to finish")
        evt = NewStatusEvt(Unbound_EVT_NEW_STATUS, self.GetId())
        evt.SetStatus('Termination scheduled - please wait!')
        self.GetEventHandler().ProcessEvent(evt)
        self.KillECRadButton.Disable()
    

    def OnUpdate(self, evt):
        self.Results = evt.Results
        self.DiagBox.Clear()
        for diag_key in list(self.Results.Scenario["used_diags_dict"]):
            self.DiagBox.Append(diag_key)
        self.TimeBox.Clear()
        for time in self.Results.Scenario["time"]:
            self.TimeBox.Append("{0:1.5f}".format(time))
        evt_out = UpdateConfigEvt(Unbound_EVT_UPDATE_CONFIG, self.GetId())
        self.GetEventHandler().ProcessEvent(evt_out)
        self.ExportButton.Enable()
        self.NameButton.Enable()
        print("Updated main results")

    def OnImport(self, evt):
        self.Results = ECRadResults()
        print("Now loarding: " + evt.filename)
        print("This takes a moment please wait")
        WorkerThread(self.ImportThread, [evt.filename])
        
    def ImportThread(self,args):
        evt = ThreadFinishedEvt(Unbound_EVT_ECRAD_RESULT_LOADED, self.GetId())
        try:
            self.Results.load(args[0])
            evt.SetSuccess(True)
        except Exception as e:
            print(e)
            evt.SetSuccess(False)
        wx.PostEvent(self, evt)
        
    def OnResultsImported(self, evt):
        if(evt.success):
            print("Results loaded")
            self.DiagBox.Clear()
            for diag_key in self.Results.Scenario["used_diags_dict"]:
                self.DiagBox.Append(diag_key)
            self.TimeBox.Clear()
            for time in self.Results.Scenario["time"]:
                self.TimeBox.Append("{0:1.5f}".format(time))
            evt_out = UpdateConfigEvt(Unbound_EVT_UPDATE_CONFIG, self.GetId())
            evt_out.set_config(self.Results.Config)
            evt_out.set_data_origin(self.Results.data_origin)
            wx.PostEvent(self.config_panel, evt_out)
            evt_out_2 = UpdateDataEvt(Unbound_EVT_UPDATE_DATA, self.GetId())
            evt_out_2.SetResults(self.Results)
            evt_out_2.SetPath(self.Results.data_origin)
            if(globalsettings.AUG):
                wx.PostEvent(self.calib_panel, evt_out_2)
            wx.PostEvent(self.scenario_select_panel, evt_out_2)
            wx.PostEvent(self.launch_panel, evt_out_2)
            wx.PostEvent(self.plot_panel, evt_out_2)
        else:
            print("ERROR: Failed to load Results")

    def OnExport(self, evt):
        try:
            try:
                NewConfig = self.config_panel.UpdateConfig(self.Results.Config)
                self.Results.Config["Execution"]["working_dir"] = NewConfig["Execution"]["working_dir"]
            except ValueError as e:
                print("Failed to parse Configuration")
                print("Reason: ", e)
                print("Did not update working directory")
            if(self.Results is not None):
                WorkerThread(self.Results.to_netcdf)
            else:
                print("No results to save")
        except AttributeError as e:
            print("No results to save")
            print(e)
        except IOError as e:
            print("Failed to save results")
            print(e)

    def OnLockExport(self, evt):
        self.ExportButton.Disable()
        self.NameButton.Disable()

    def OnIdle(self, evt):
        if(self.ECRad_running):
            try:
                success, self.Results = self.ECRad_output_queue.get(block=False)
                evt = ProccessFinishedEvt(Unbound_EVT_ECRAD_FINISHED, self.GetId())
                evt.SetSuccess(success)
                wx.PostEvent(self, evt)
                return
            except queue.Empty:
                pass
            if(not self.ECRad_runner_process.is_alive()):
                self.ECRad_runner_process = Process(target=Main_Panel.ECRadRunner, \
                                                    args=(self.ECRad_input_queue, \
                                                          self.ECRad_output_queue))
                self.ECRad_runner_process.start()
                success = False
                evt = ProccessFinishedEvt(Unbound_EVT_ECRAD_FINISHED, self.GetId())
                evt.SetSuccess(success)
                wx.PostEvent(self, evt)

#         if(self.ECRad_process is not None):
#             stream = self.ECRad_process.GetInputStream()
#             if stream is not None:
#                 if stream.CanRead():
#                     text = stream.read()
#                     self.Log_Box.AppendText(text)
#             evt.RequestMore()
#         elif(self.ECRad_running):
#             print("ECRad seems to have crashed without the corresponding event chain firing")
#             print("This might cause some weird stuff from here on out")
#             print("Trying to fix it...")
#             self.ECRad_running = False
#             self.OnProcessEnded(None) 

        
    def OnName(self, evt):
        if(self.Results.comment == None):
            comment = ""
        else:
            print(self.Results.comment)
            comment = self.Results.comment
        comment_dialogue = wx.TextEntryDialog(self, 'Please type comment for your calculation!', value=comment)
        if(comment_dialogue.ShowModal() == wx.ID_OK):
            self.Results.comment = comment_dialogue.GetValue()
Exemplo n.º 19
0
def run_ECRad():
    args = sys.argv
    working_dir = args[1]
    shot = int(args[2])
    diag_id = args[3]
    shot_data_file = os.path.join(working_dir, args[4])
    times_to_analyze = None
    try:
        if(len(args) > 5):
            try:
                times_to_analyze = np.loadtxt(os.path.join(working_dir, args[5]))
                if(times_to_analyze.ndim == 0):
                    times_to_analyze = np.array([times_to_analyze])
            except:
                print("Failed to load " + os.path.join(working_dir, args[5]))
                print("Analyzing everything")
    except Exception as e:
        print("Initialization failed.")
        print("Error:", e)
        print("Usage: python run_ECRad_no_GUI.py <shotno> <diag id>")
        if(globalsettings.TCV):
            print("Possible diag ids: UCE, LCE, VCE, CCE")
        elif(globalsettings.AUG):
            print("Possible diag ids: ECE, CTA, CTC, IEC, ECN, ECO")
        else:
            print("Only AUG or TCV supported at this time")
        print("Got the following args", args)
        return -1
    try:
        Config = ECRadConfig()
        Config.from_mat_file(path=os.path.join(working_dir, "UserConfig.mat"))
    except IOError:
        print("Failed to load user config at : ")
        print(os.path.join(working_dir, "UserConfig.mat"))
    Config.working_dir = working_dir
    if(globalsettings.TCV):
        Config.time, Config.plasma_dict = load_plasma_from_mat(Config, shot_data_file)
        if(diag_id in ["UCE", "LCE", "VCE"]):
            Config.used_diags_dict.update({diag_id: Diag(diag_id, "TCV", diag_id, 0)})
        else:
            print("Selected diag_id {0:s} is not supported for TCV".format(diag_id))
            return -1
        Config.Ext_plasma = True
    elif(globalsettings.AUG):
        Config.time, Config.plasma_dict = load_IDA_data(shot, timepoints=None, exp="AUGD", ed=0)
        if(diag_id == "ECE"):
            Config.used_diags_dict.update({diag_id: Diag(diag_id, "AUGD", 'RMD', 0)})
        elif(diag_id in ["CTA", "CTC", "IEC"]):
            if(shot > 33724):
                if(diag_id == "CTA"):
                    beamline = 7
                elif(diag_id == "CTC"):
                    beamline = 8
                else:
                    beamline = 5
            else:
                if(diag_id == "CTA"):
                    beamline = 6
                else:
                    beamline = 5
            Config.used_diags_dict.update({diag_id: ECRH_diag(diag_id, "AUGD", diag_id, 0, beamline, 1.0, True)})
        elif(diag_id in ["ECN", "ECO"]):
            if(diag_id == "ECN"):
                Config.used_diags_dict.update({diag_id: ECI_diag(diag_id, "AUGD", "TDI", 0, "ECEI", "RZN", 0)})
            else:
                Config.used_diags_dict.update({diag_id: ECI_diag(diag_id, "AUGD", "TDI", 0, "ECEI", "RZO", 0)})
            Config.ECI_dict = get_ECI_launch(Config.used_diags_dict[diag_id], Config.shot)
        else:
            print("Selected diag_id {0:s} is not supported for TCV".format(diag_id))
            return -1
    else:
        print("Only AUG or TCV supported at this time")
    if(Config.time == None):
        print("Failed to initialize")
        return -1
    Config.shot = shot
    Config.working_dir = working_dir
    for diag_key in Config.used_diags_dict:
        if("CT" in diag_key or "IEC" == diag_key):
            if(str(Config.used_diags_dict[diag_key].beamline) not in Config.gy_dict):
                new_gy = get_ECRH_viewing_angles(Config.shot, \
                                                Config.used_diags_dict[diag_key].beamline)
                if(new_gy.error == 0):
                    Config.gy_dict[str(Config.used_diags_dict[diag_key].beamline)] = new_gy
                else:
                    print("Error when reading viewing angles")
                    print("Launch aborted")
                    return
    Results = ECRadResults()
    Results.parse_config(Config, Config.time)
    if(not times_to_analyze is None):
        it_ext = 0
        actual_times = []
        for i in range(len(times_to_analyze)):
            actual_times.append(np.argmin(np.abs(Config.time - times_to_analyze[it_ext])))
        actual_times = np.array(actual_times)
        Config.time = Config.time[actual_times]
        Config.plasma_dict["Te"] = Config.plasma_dict["Te"][actual_times]
        Config.plasma_dict["ne"] = Config.plasma_dict["ne"][actual_times]
        Config.plasma_dict["rhop"] = Config.plasma_dict["rhop"][actual_times]
        Config.plasma_dict["ne_rhop_scale"] = Config.plasma_dict["ne_rhop_scale"][actual_times]
        if(Config.plasma_dict["eq_data"] is not None):
            Config.plasma_dict["eq_data"] = Config.plasma_dict["eq_data"][actual_times]
    if(not Config.debug and globalsettings.AUG):
        InvokeECRad = "/afs/ipp-garching.mpg.de/home/s/sdenk/F90/ECRad_Model/ECRad_model"
    elif(globalsettings.AUG):
        InvokeECRad = "/marconi_work/eufus_gw/work/g2sdenk/ECRad_Model_parallel/ECRad_model"
    elif(globalsettings.TCV and Config.debug):
        InvokeECRad = "../ECRad_Model_TCV/ECRad_model"
    elif(globalsettings.TCV):
        InvokeECRad = "../ECRad_Model_TCV_no_debug/ECRad_model"
    else:
        print('Neither AUG nor TCV selected - no Machine!!')
        raise IOError
    Results = run_ECRad_from_script(working_dir, shot, Config, InvokeECRad, working_dir)
    Results.to_mat_file()
    print("Finished successfully")